context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Linq; using Rynchodon.AntennaRelay; using Rynchodon.Attached; using Rynchodon.Autopilot.Data; using VRage.Game.ModAPI; using VRageMath; namespace Rynchodon.Autopilot { /// <summary> /// Finds a friendly grid and possibly a block, given a ship controller block. /// </summary> public class GridFinder { public enum ReasonCannotTarget : byte { None, Too_Far, Grid_Condition, Too_Fast } private const ulong SearchInterval_Grid = 100ul, SearchInterval_Block = 100ul; public readonly string m_targetGridName, m_targetBlockName; private readonly ShipControllerBlock m_controlBlock; private readonly AttachedGrid.AttachmentKind m_allowedAttachment; private readonly Logger m_logger; private readonly AllNavigationSettings m_navSet; private readonly bool m_mustBeRecent; public Vector3D m_startPosition; public ulong NextSearch_Grid { get; private set; } public ulong NextSearch_Block { get; private set; } public virtual LastSeen Grid { get; protected set; } public IMyCubeBlock Block { get; private set; } public Func<LastSeen, double> OrderValue; public Func<IMyCubeGrid, bool> GridCondition; /// <summary>Block requirements, other than can control.</summary> public Func<IMyCubeBlock, bool> BlockCondition; public ReasonCannotTarget m_reason; public LastSeen m_bestGrid; protected float MaximumRange; protected long m_targetEntityId; //private Vector3I m_previousCell; private RelayStorage m_netStore { get { return m_controlBlock.NetworkStorage; } } /// <summary> /// Creates a GridFinder to find a friendly grid based on its name. /// </summary> public GridFinder(AllNavigationSettings navSet, ShipControllerBlock controller, string targetGrid, string targetBlock = null, AttachedGrid.AttachmentKind allowedAttachment = AttachedGrid.AttachmentKind.Permanent, bool mustBeRecent = false) { this.m_logger = new Logger(controller.CubeBlock); m_logger.debugLog("navSet == null", Logger.severity.FATAL, condition: navSet == null); m_logger.debugLog("controller == null", Logger.severity.FATAL, condition: controller == null); m_logger.debugLog("controller.CubeBlock == null", Logger.severity.FATAL, condition: controller.CubeBlock == null); m_logger.debugLog("targetGrid == null", Logger.severity.FATAL, condition: targetGrid == null); this.m_targetGridName = targetGrid.LowerRemoveWhitespace(); if (targetBlock != null) this.m_targetBlockName = targetBlock.LowerRemoveWhitespace(); this.m_controlBlock = controller; this.m_allowedAttachment = allowedAttachment; this.MaximumRange = 0f; this.m_navSet = navSet; this.m_mustBeRecent = mustBeRecent; this.m_startPosition = m_controlBlock.CubeBlock.GetPosition(); } /// <summary> /// Creates a GridFinder to find an enemy grid based on distance. /// </summary> public GridFinder(AllNavigationSettings navSet, ShipControllerBlock controller, float maxRange = 0f) { this.m_logger = new Logger(controller.CubeBlock); m_logger.debugLog("navSet == null", Logger.severity.FATAL, condition: navSet == null); m_logger.debugLog("controller == null", Logger.severity.FATAL, condition: controller == null); m_logger.debugLog("controller.CubeBlock == null", Logger.severity.FATAL, condition: controller.CubeBlock == null); this.m_controlBlock = controller; //this.m_enemies = new List<LastSeen>(); this.MaximumRange = maxRange; this.m_navSet = navSet; this.m_mustBeRecent = true; this.m_startPosition = m_controlBlock.CubeBlock.GetPosition(); } public void Update() { if (Grid == null || OrderValue != null) { if (Globals.UpdateCount >= NextSearch_Grid) GridSearch(); } else GridUpdate(); if (Grid != null && m_targetBlockName != null) { if (Block == null) { if (Globals.UpdateCount >= NextSearch_Block) BlockSearch(); } else BlockCheck(); } } /// <summary> /// Find a seen grid that matches m_targetGridName /// </summary> private void GridSearch() { NextSearch_Grid = Globals.UpdateCount + SearchInterval_Grid; if (m_targetGridName != null) GridSearch_Friend(); else GridSearch_Enemy(); } private void GridSearch_Friend() { int bestNameLength = int.MaxValue; RelayStorage store = m_netStore; if (store == null) { m_logger.debugLog("no storage", Logger.severity.DEBUG); return; } store.SearchLastSeen(seen => { IMyCubeGrid grid = seen.Entity as IMyCubeGrid; if (grid != null && grid.DisplayName.Length < bestNameLength && grid.DisplayName.LowerRemoveWhitespace().Contains(m_targetGridName) && CanTarget(seen)) { Grid = seen; bestNameLength = grid.DisplayName.Length; if (bestNameLength == m_targetGridName.Length) { m_logger.debugLog("perfect match LastSeen: " + seen.Entity.getBestName()); return true; } } return false; }); if (Grid != null) m_logger.debugLog("Best match LastSeen: " + Grid.Entity.getBestName()); } private void GridSearch_Enemy() { RelayStorage store = m_netStore; if (store == null) { m_logger.debugLog("no storage", Logger.severity.DEBUG); return; } if (m_targetEntityId != 0L) { LastSeen target; if (store.TryGetLastSeen(m_targetEntityId, out target) && CanTarget(target)) { Grid = target; m_logger.debugLog("found target: " + target.Entity.getBestName()); } else Grid = null; return; } List<LastSeen> enemies = ResourcePool<List<LastSeen>>.Get(); Vector3D position = m_controlBlock.CubeBlock.GetPosition(); store.SearchLastSeen(seen => { if (!seen.IsValid || !seen.isRecent()) return false; IMyCubeGrid asGrid = seen.Entity as IMyCubeGrid; if (asGrid == null) return false; if (!m_controlBlock.CubeBlock.canConsiderHostile(asGrid)) return false; enemies.Add(seen); m_logger.debugLog("enemy: " + asGrid.DisplayName); return false; }); m_logger.debugLog("number of enemies: " + enemies.Count); IOrderedEnumerable<LastSeen> enemiesByDistance = enemies.OrderBy(OrderValue != null ? OrderValue : seen => Vector3D.DistanceSquared(position, seen.GetPosition())); m_reason = ReasonCannotTarget.None; foreach (LastSeen enemy in enemiesByDistance) { if (CanTarget(enemy)) { Grid = enemy; m_logger.debugLog("found target: " + enemy.Entity.getBestName()); enemies.Clear(); ResourcePool<List<LastSeen>>.Return(enemies); return; } } Grid = null; m_logger.debugLog("nothing found"); enemies.Clear(); ResourcePool<List<LastSeen>>.Return(enemies); } private void GridUpdate() { m_logger.debugLog("Grid == null", Logger.severity.FATAL, condition: Grid == null); if (!Grid.IsValid) { m_logger.debugLog("no longer valid: " + Grid.Entity.getBestName(), Logger.severity.DEBUG); Grid = null; return; } if (m_mustBeRecent && !Grid.isRecent()) { m_logger.debugLog("no longer recent: " + Grid.Entity.getBestName() + ", age: " + (Globals.ElapsedTime - Grid.LastSeenAt)); Grid = null; return; } if (!CanTarget(Grid)) { m_logger.debugLog("can no longer target: " + Grid.Entity.getBestName(), Logger.severity.DEBUG); Grid = null; return; } RelayStorage storage = m_netStore; if (storage == null) { m_logger.debugLog("lost storage", Logger.severity.DEBUG); Grid = null; return; } LastSeen updated; if (!m_netStore.TryGetLastSeen(Grid.Entity.EntityId, out updated)) { m_logger.alwaysLog("Where does the good go? Searching for " + Grid.Entity.EntityId, Logger.severity.WARNING); Grid = null; return; } //m_logger.debugLog("updating grid last seen " + Grid.LastSeenAt + " => " + updated.LastSeenAt, "GridUpdate()"); Grid = updated; } /// <summary> /// Find a block that matches m_targetBlockName. /// </summary> private void BlockSearch() { m_logger.debugLog("Grid == null", Logger.severity.FATAL, condition: Grid == null); m_logger.debugLog("m_targetBlockName == null", Logger.severity.FATAL, condition: m_targetBlockName == null); NextSearch_Block = Globals.UpdateCount + SearchInterval_Block; Block = null; int bestNameLength = int.MaxValue; IMyCubeGrid asGrid = Grid.Entity as IMyCubeGrid; m_logger.debugLog("asGrid == null", Logger.severity.FATAL, condition: asGrid == null); foreach (IMyCubeBlock Fatblock in AttachedGrid.AttachedCubeBlocks(asGrid, m_allowedAttachment, true)) { if (!m_controlBlock.CubeBlock.canControlBlock(Fatblock)) continue; string blockName = Fatblock.DisplayNameText.LowerRemoveWhitespace(); if (BlockCondition != null && !BlockCondition(Fatblock)) continue; //m_logger.debugLog("checking block name: \"" + blockName + "\" contains \"" + m_targetBlockName + "\"", "BlockSearch()"); if (blockName.Length < bestNameLength && blockName.Contains(m_targetBlockName)) { m_logger.debugLog("block name matches: " + Fatblock.DisplayNameText); Block = Fatblock; bestNameLength = blockName.Length; if (m_targetBlockName.Length == bestNameLength) return; } } } private void BlockCheck() { m_logger.debugLog("Grid == null", Logger.severity.FATAL, condition: Grid == null); m_logger.debugLog("m_targetBlockName == null", Logger.severity.FATAL, condition: m_targetBlockName == null); m_logger.debugLog("Block == null", Logger.severity.FATAL, condition: Block == null); if (!m_controlBlock.CubeBlock.canControlBlock(Block)) { m_logger.debugLog("lost control of block: " + Block.DisplayNameText, Logger.severity.DEBUG); Block = null; return; } if (BlockCondition != null && !BlockCondition(Block)) { m_logger.debugLog("Block does not statisfy condition: " + Block.DisplayNameText, Logger.severity.DEBUG); Block = null; return; } } private bool CanTarget(LastSeen seen) { try { // if it is too far from start, cannot target if (MaximumRange > 1f && Vector3.DistanceSquared(m_startPosition, seen.GetPosition()) > MaximumRange * MaximumRange) { m_logger.debugLog("out of range: " + seen.Entity.getBestName()); if (m_reason < ReasonCannotTarget.Too_Far) { m_reason = ReasonCannotTarget.Too_Far; m_bestGrid = seen; } return false; } // if it is too fast, cannot target float speedTarget = m_navSet.Settings_Task_NavEngage.SpeedTarget - 1f; if (seen.GetLinearVelocity().LengthSquared() >= speedTarget * speedTarget) { m_logger.debugLog("too fast to target: " + seen.Entity.getBestName() + ", speed: " + seen.GetLinearVelocity().Length() + ", my speed: " + m_navSet.Settings_Task_NavEngage.SpeedTarget); if (m_reason < ReasonCannotTarget.Too_Fast) { m_reason = ReasonCannotTarget.Too_Fast; m_bestGrid = seen; } return false; } if (GridCondition != null && !GridCondition(seen.Entity as IMyCubeGrid)) { m_logger.debugLog("Failed grid condition: " + seen.Entity.getBestName()); if (m_reason < ReasonCannotTarget.Grid_Condition) { m_reason = ReasonCannotTarget.Grid_Condition; m_bestGrid = seen; } return false; } m_bestGrid = seen; return true; } catch (NullReferenceException nre) { m_logger.alwaysLog("Exception: " + nre, Logger.severity.ERROR); if (!seen.Entity.Closed) throw; m_logger.debugLog("Caught exception caused by grid closing, ignoring."); return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Collections.Generic; using System.CommandLine; using System.Reflection; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Internal.IL; using Internal.CommandLine; using System.Text.RegularExpressions; using System.Globalization; using System.Resources; namespace ILVerify { class Program { private const string SystemModuleSimpleName = "mscorlib"; private bool _help; private Dictionary<string, string> _inputFilePaths = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); private Dictionary<string, string> _referenceFilePaths = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); private IReadOnlyList<Regex> _includePatterns = Array.Empty<Regex>(); private IReadOnlyList<Regex> _excludePatterns = Array.Empty<Regex>(); private SimpleTypeSystemContext _typeSystemContext; private ResourceManager _stringResourceManager; private int _numErrors; private Program() { } private void Help(string helpText) { Console.WriteLine("ILVerify version " + typeof(Program).Assembly.GetName().Version.ToString()); Console.WriteLine(); Console.WriteLine("--help Display this usage message (Short form: -?)"); Console.WriteLine("--reference Reference metadata from the specified assembly (Short form: -r)"); Console.WriteLine("--include Use only methods/types/namespaces, which match the given regular expression(s) (Short form: -i)"); Console.WriteLine("--include-file Same as --include, but the regular expression(s) are declared line by line in the specified file."); Console.WriteLine("--exclude Skip methods/types/namespaces, which match the given regular expression(s) (Short form: -e)"); Console.WriteLine("--exclude-file Same as --exclude, but the regular expression(s) are declared line by line in the specified file."); } public static IReadOnlyList<Regex> StringPatternsToRegexList(IReadOnlyList<string> patterns) { List<Regex> patternList = new List<Regex>(); foreach (var pattern in patterns) patternList.Add(new Regex(pattern, RegexOptions.Compiled)); return patternList; } private ArgumentSyntax ParseCommandLine(string[] args) { IReadOnlyList<string> inputFiles = Array.Empty<string>(); IReadOnlyList<string> referenceFiles = Array.Empty<string>(); IReadOnlyList<string> includePatterns = Array.Empty<string>(); IReadOnlyList<string> excludePatterns = Array.Empty<string>(); string includeFile = string.Empty; string excludeFile = string.Empty; AssemblyName name = typeof(Program).GetTypeInfo().Assembly.GetName(); ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { syntax.ApplicationName = name.Name.ToString(); // HandleHelp writes to error, fails fast with crash dialog and lacks custom formatting. syntax.HandleHelp = false; syntax.HandleErrors = true; syntax.DefineOption("h|help", ref _help, "Help message for ILC"); syntax.DefineOptionList("r|reference", ref referenceFiles, "Reference file(s) for compilation"); syntax.DefineOptionList("i|include", ref includePatterns, "Use only methods/types/namespaces, which match the given regular expression(s)"); syntax.DefineOption("include-file", ref includeFile, "Same as --include, but the regular expression(s) are declared line by line in the specified file."); syntax.DefineOptionList("e|exclude", ref excludePatterns, "Skip methods/types/namespaces, which match the given regular expression(s)"); syntax.DefineOption("exclude-file", ref excludeFile, "Same as --exclude, but the regular expression(s) are declared line by line in the specified file."); syntax.DefineParameterList("in", ref inputFiles, "Input file(s) to compile"); }); foreach (var input in inputFiles) Helpers.AppendExpandedPaths(_inputFilePaths, input, true); foreach (var reference in referenceFiles) Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false); if (!string.IsNullOrEmpty(includeFile)) { if (includePatterns.Count > 0) Console.WriteLine("[Warning] --include-file takes precedence over --include"); includePatterns = File.ReadAllLines(includeFile); } _includePatterns = StringPatternsToRegexList(includePatterns); if (!string.IsNullOrEmpty(excludeFile)) { if (excludePatterns.Count > 0) Console.WriteLine("[Warning] --exclude-file takes precedence over --exclude"); excludePatterns = File.ReadAllLines(excludeFile); } _excludePatterns = StringPatternsToRegexList(excludePatterns); return argSyntax; } private void VerifyMethod(MethodDesc method, MethodIL methodIL) { // Console.WriteLine("Verifying: " + method.ToString()); try { var importer = new ILImporter(method, methodIL); importer.ReportVerificationError = (args) => { var message = new StringBuilder(); message.Append("[IL]: Error: "); message.Append("["); message.Append(_typeSystemContext.GetModulePath(((EcmaMethod)method).Module)); message.Append(" : "); message.Append(((EcmaType)method.OwningType).Name); message.Append("::"); message.Append(method.Name); message.Append("]"); message.Append("[offset 0x"); message.Append(args.Offset.ToString("X8")); message.Append("]"); if (args.Found != null) { message.Append("[found "); message.Append(args.Found); message.Append("]"); } if (args.Expected != null) { message.Append("[expected "); message.Append(args.Expected); message.Append("]"); } if (args.Token != 0) { message.Append("[token 0x"); message.Append(args.Token.ToString("X8")); message.Append("]"); } message.Append(" "); if (_stringResourceManager == null) { _stringResourceManager = new ResourceManager("ILVerify.Resources.Strings", Assembly.GetExecutingAssembly()); } var str = _stringResourceManager.GetString(args.Code.ToString(), CultureInfo.InvariantCulture); message.Append(string.IsNullOrEmpty(str) ? args.Code.ToString() : str); Console.WriteLine(message); _numErrors++; }; importer.Verify(); } catch (NotImplementedException e) { Console.Error.WriteLine($"Error in {method}: {e.Message}"); } catch (InvalidProgramException e) { Console.Error.WriteLine($"Error in {method}: {e.Message}"); } catch (VerificationException) { } catch (BadImageFormatException) { Console.WriteLine("Unable to resolve token"); } catch (PlatformNotSupportedException e) { Console.WriteLine(e.Message); } } private void VerifyModule(EcmaModule module) { foreach (var methodHandle in module.MetadataReader.MethodDefinitions) { var method = (EcmaMethod)module.GetMethod(methodHandle); var methodIL = EcmaMethodIL.Create(method); if (methodIL == null) continue; var methodName = method.ToString(); if (_includePatterns.Count > 0 && !_includePatterns.Any(p => p.IsMatch(methodName))) continue; if (_excludePatterns.Any(p => p.IsMatch(methodName))) continue; VerifyMethod(method, methodIL); } } private int Run(string[] args) { ArgumentSyntax syntax = ParseCommandLine(args); if (_help) { Help(syntax.GetHelpText()); return 1; } if (_inputFilePaths.Count == 0) throw new CommandLineException("No input files specified"); _typeSystemContext = new SimpleTypeSystemContext(); _typeSystemContext.InputFilePaths = _inputFilePaths; _typeSystemContext.ReferenceFilePaths = _referenceFilePaths; _typeSystemContext.SetSystemModule(_typeSystemContext.GetModuleForSimpleName(SystemModuleSimpleName)); foreach (var inputPath in _inputFilePaths.Values) { _numErrors = 0; VerifyModule(_typeSystemContext.GetModuleFromPath(inputPath)); if (_numErrors > 0) Console.WriteLine(_numErrors + " Error(s) Verifying " + inputPath); else Console.WriteLine("All Classes and Methods in " + inputPath + " Verified."); } return 0; } private static int Main(string[] args) { try { return new Program().Run(args); } catch (Exception e) { Console.Error.WriteLine("Error: " + e.Message); return 1; } } } }
using System; using System.Globalization; #if !BUILDTASK using Avalonia.Animation.Animators; #endif using Avalonia.Utilities; namespace Avalonia { /// <summary> /// Defines a point. /// </summary> #if !BUILDTASK public #endif readonly struct Point : IEquatable<Point> { static Point() { #if !BUILDTASK Animation.Animation.RegisterAnimator<PointAnimator>(prop => typeof(Point).IsAssignableFrom(prop.PropertyType)); #endif } /// <summary> /// The X position. /// </summary> private readonly double _x; /// <summary> /// The Y position. /// </summary> private readonly double _y; /// <summary> /// Initializes a new instance of the <see cref="Point"/> structure. /// </summary> /// <param name="x">The X position.</param> /// <param name="y">The Y position.</param> public Point(double x, double y) { _x = x; _y = y; } /// <summary> /// Gets the X position. /// </summary> public double X => _x; /// <summary> /// Gets the Y position. /// </summary> public double Y => _y; /// <summary> /// Converts the <see cref="Point"/> to a <see cref="Vector"/>. /// </summary> /// <param name="p">The point.</param> public static implicit operator Vector(Point p) { return new Vector(p._x, p._y); } /// <summary> /// Negates a point. /// </summary> /// <param name="a">The point.</param> /// <returns>The negated point.</returns> public static Point operator -(Point a) { return new Point(-a._x, -a._y); } /// <summary> /// Checks for equality between two <see cref="Point"/>s. /// </summary> /// <param name="left">The first point.</param> /// <param name="right">The second point.</param> /// <returns>True if the points are equal; otherwise false.</returns> public static bool operator ==(Point left, Point right) { return left.Equals(right); } /// <summary> /// Checks for inequality between two <see cref="Point"/>s. /// </summary> /// <param name="left">The first point.</param> /// <param name="right">The second point.</param> /// <returns>True if the points are unequal; otherwise false.</returns> public static bool operator !=(Point left, Point right) { return !(left == right); } /// <summary> /// Adds two points. /// </summary> /// <param name="a">The first point.</param> /// <param name="b">The second point.</param> /// <returns>A point that is the result of the addition.</returns> public static Point operator +(Point a, Point b) { return new Point(a._x + b._x, a._y + b._y); } /// <summary> /// Adds a vector to a point. /// </summary> /// <param name="a">The point.</param> /// <param name="b">The vector.</param> /// <returns>A point that is the result of the addition.</returns> public static Point operator +(Point a, Vector b) { return new Point(a._x + b.X, a._y + b.Y); } /// <summary> /// Subtracts two points. /// </summary> /// <param name="a">The first point.</param> /// <param name="b">The second point.</param> /// <returns>A point that is the result of the subtraction.</returns> public static Point operator -(Point a, Point b) { return new Point(a._x - b._x, a._y - b._y); } /// <summary> /// Subtracts a vector from a point. /// </summary> /// <param name="a">The point.</param> /// <param name="b">The vector.</param> /// <returns>A point that is the result of the subtraction.</returns> public static Point operator -(Point a, Vector b) { return new Point(a._x - b.X, a._y - b.Y); } /// <summary> /// Multiplies a point by a factor coordinate-wise /// </summary> /// <param name="p">Point to multiply</param> /// <param name="k">Factor</param> /// <returns>Points having its coordinates multiplied</returns> public static Point operator *(Point p, double k) => new Point(p.X * k, p.Y * k); /// <summary> /// Multiplies a point by a factor coordinate-wise /// </summary> /// <param name="p">Point to multiply</param> /// <param name="k">Factor</param> /// <returns>Points having its coordinates multiplied</returns> public static Point operator *(double k, Point p) => new Point(p.X * k, p.Y * k); /// <summary> /// Divides a point by a factor coordinate-wise /// </summary> /// <param name="p">Point to divide by</param> /// <param name="k">Factor</param> /// <returns>Points having its coordinates divided</returns> public static Point operator /(Point p, double k) => new Point(p.X / k, p.Y / k); /// <summary> /// Applies a matrix to a point. /// </summary> /// <param name="point">The point.</param> /// <param name="matrix">The matrix.</param> /// <returns>The resulting point.</returns> public static Point operator *(Point point, Matrix matrix) { return new Point( (point.X * matrix.M11) + (point.Y * matrix.M21) + matrix.M31, (point.X * matrix.M12) + (point.Y * matrix.M22) + matrix.M32); } /// <summary> /// Parses a <see cref="Point"/> string. /// </summary> /// <param name="s">The string.</param> /// <returns>The <see cref="Point"/>.</returns> public static Point Parse(string s) { using (var tokenizer = new StringTokenizer(s, CultureInfo.InvariantCulture, exceptionMessage: "Invalid Point.")) { return new Point( tokenizer.ReadDouble(), tokenizer.ReadDouble() ); } } /// <summary> /// Returns a boolean indicating whether the point is equal to the other given point. /// </summary> /// <param name="other">The other point to test equality against.</param> /// <returns>True if this point is equal to other; False otherwise.</returns> public bool Equals(Point other) { // ReSharper disable CompareOfFloatsByEqualityOperator return _x == other._x && _y == other._y; // ReSharper enable CompareOfFloatsByEqualityOperator } /// <summary> /// Checks for equality between a point and an object. /// </summary> /// <param name="obj">The object.</param> /// <returns> /// True if <paramref name="obj"/> is a point that equals the current point. /// </returns> public override bool Equals(object obj) => obj is Point other && Equals(other); /// <summary> /// Returns a hash code for a <see cref="Point"/>. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { unchecked { int hash = 17; hash = (hash * 23) + _x.GetHashCode(); hash = (hash * 23) + _y.GetHashCode(); return hash; } } /// <summary> /// Returns the string representation of the point. /// </summary> /// <returns>The string representation of the point.</returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0}, {1}", _x, _y); } /// <summary> /// Transforms the point by a matrix. /// </summary> /// <param name="transform">The transform.</param> /// <returns>The transformed point.</returns> public Point Transform(Matrix transform) { var x = X; var y = Y; var xadd = y * transform.M21 + transform.M31; var yadd = x * transform.M12 + transform.M32; x *= transform.M11; x += xadd; y *= transform.M22; y += yadd; return new Point(x, y); } /// <summary> /// Returns a new point with the specified X coordinate. /// </summary> /// <param name="x">The X coordinate.</param> /// <returns>The new point.</returns> public Point WithX(double x) { return new Point(x, _y); } /// <summary> /// Returns a new point with the specified Y coordinate. /// </summary> /// <param name="y">The Y coordinate.</param> /// <returns>The new point.</returns> public Point WithY(double y) { return new Point(_x, y); } /// <summary> /// Deconstructs the point into its X and Y coordinates. /// </summary> /// <param name="x">The X coordinate.</param> /// <param name="y">The Y coordinate.</param> public void Deconstruct(out double x, out double y) { x = this._x; y = this._y; } /// <summary> /// Gets a value indicating whether the X and Y coordinates are zero. /// </summary> public bool IsDefault { get { return (_x == 0) && (_y == 0); } } } }
using UnityEngine; using System.Collections.Generic; using SanityEngine.Structure.Graph; using SanityEngine.Structure.Graph.NavMesh; [AddComponentMenu("Sanity Engine/Level Representation/Pseudo-Grid Generator"), ExecuteInEditMode()] public class PseudoGridGenerator// : UnityGraph { #if false private delegate bool Sample(Vector3 pos, Vector3 dir, out Vector3 result); public enum SamplerType { CENTER, CORNERS_AVG, CORNERS_MIN, CORNERS_MAX, MONTE_CARLO }; public enum EdgeCostAlgorithm { ONE_PLUS_POS_SLOPE, ONE, EUCLIDEAN_DISTANCE }; public enum GridType { EIGHT_GRID, FOUR_GRID }; public SamplerType samplingType = SamplerType.MONTE_CARLO; public int xRes = 10; public int yRes = 10; public bool noHitNoCell = true; public bool removeOrphans = true; public float maxSlope = float.PositiveInfinity; public float maxHeight = float.PositiveInfinity; public bool edgeRaycast = false; public EdgeCostAlgorithm edgeCostAlgorithm; public GridType gridType; public bool drawGrid = true; PseudoGridCell[] cells; GraphChangeHelper helper; void Awake() { helper = new GraphChangeHelper(); cells = GetComponentsInChildren<PseudoGridCell>(); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnDrawGizmos() { if(drawGrid) { DrawGizmos(); } } void OnDrawGizmosSelected() { if(!drawGrid) { DrawGizmos(); } } void DrawGizmos() { Vector3 pos = transform.position; Gizmos.matrix = Matrix4x4.TRS(pos, transform.rotation, Vector3.one); Gizmos.color = Color.blue; Gizmos.DrawLine(Vector3.zero, Vector3.up * transform.localScale.y * 0.5f); Gizmos.color = Color.white; Gizmos.DrawWireCube(Vector3.zero, transform.localScale); } public void FindCells() { List<GameObject> del = new List<GameObject>(); foreach(Transform child in transform) { del.Add(child.gameObject); } foreach(GameObject obj in del) { DestroyImmediate(obj); } Sample sampler = null; switch(samplingType) { case SamplerType.CENTER: sampler = SampleCenter; break; case SamplerType.CORNERS_AVG: sampler = SampleCornersAvg; break; case SamplerType.CORNERS_MIN: sampler = SampleCornersMin; break; case SamplerType.CORNERS_MAX: sampler = SampleCornersMax; break; case SamplerType.MONTE_CARLO: sampler = SampleMonteCarlo; break; } float xSize = transform.localScale.x / xRes; float ySize = transform.localScale.z / yRes; float thickness = transform.localScale.y * 0.1f; float xOff = xSize * 0.5f; float yOff = ySize * 0.5f; Vector3 down = transform.up * -transform.localScale.y; Vector3 top = Vector3.up * transform.localScale.y * 0.5f; Vector3 scale = new Vector3(xSize, thickness, ySize); Vector3 start = new Vector3(-xOff * xRes + xOff, 0.0f, -yOff * yRes + yOff); float localMaxHeight = maxHeight / transform.localScale.y; PseudoGridCell[,] cells = new PseudoGridCell[yRes, xRes]; // Node creation pass for(int y = 0; y < yRes ; y ++) { for(int x = 0; x < xRes ; x ++) { Vector3 rayPos = transform.position + transform.rotation * (new Vector3(xSize * x, 0f, ySize * y) + start + top); Vector3 pos = Vector3.zero; if(!sampler(rayPos, down, out pos) && noHitNoCell) { continue; } Vector3 localPos = transform.InverseTransformPoint(pos); if(localPos.y + 0.5f > localMaxHeight) { continue; } GameObject cell = new GameObject("Cell (" + x + "," + y + ")"); cell.transform.position = pos; cell.transform.rotation = transform.rotation; cell.transform.parent = transform; cell.transform.localScale = scale; cell.gameObject.layer = gameObject.layer; BoxCollider box = cell.AddComponent<BoxCollider>(); box.isTrigger = true; Vector3 s = transform.localScale; box.size = new Vector3(1.0f/s.x, 1.0f/s.y, 1.0f/s.z); cells[y, x] = cell.AddComponent<PseudoGridCell>(); } } // Edge creation pass List<GameObjectEdge> edges = new List<GameObjectEdge>(); for(int y = 0; y < yRes ; y ++) { for(int x = 0; x < xRes ; x ++) { edges.Clear(); PseudoGridCell src = cells[y, x]; if(src == null) { continue; } for(int dy = -1; dy <= 1; dy ++) { for(int dx = -1; dx <= 1; dx ++) { if(gridType == GridType.FOUR_GRID && Mathf.Abs(dx) + Mathf.Abs(dy) >= 2) { continue; } int x2 = x + dx, y2 = y + dy; // Skip the center if((dx == 0 && dy == 0) || x2 < 0 || x2 >= cells.GetLength(1) || y2 < 0 || y2 >= cells.GetLength(0)) { // TODO add 4-/8- criteria continue; } PseudoGridCell dest = cells[y2, x2]; if(dest == null) { continue; } Vector3 diff = dest.transform.position - src.transform.position; float slope = Mathf.Abs(Vector3.Dot(diff, transform.up)); if(slope < maxSlope) { edges.Add(new GameObjectEdge(dest, CalculateEdgeCost(src, dest))); } } } src.edges = edges.ToArray(); } } if(removeOrphans) { for(int y = 0; y < yRes ; y ++) { for(int x = 0; x < xRes ; x ++) { if(cells[y, x] == null) { continue; } if(cells[y, x].edges.Length == 0) { DestroyImmediate(cells[y, x]); } } } } } bool SampleCenter(Vector3 pos, Vector3 dir, out Vector3 result) { if(RaycastNearest(pos, dir, out result)) { return true; } result = pos + dir; return false; } bool SampleCornersAvg(Vector3 pos, Vector3 dir, out Vector3 result) { Vector3 r = transform.right * (transform.localScale.x / xRes) * 0.5f; Vector3 f = transform.forward * (transform.localScale.z / yRes) * 0.5f; Vector3 sum = Vector3.zero; int hits = 0; Vector3 hit; if(RaycastNearest(pos - r - f, dir, out hit)) { sum += hit - pos; hits ++; } if(RaycastNearest(pos + r - f, dir, out hit)) { sum += hit - pos; hits ++; } if(RaycastNearest(pos - r + f, dir, out hit)) { sum += hit - pos; hits ++; } if(RaycastNearest(pos + r + f, dir, out hit)) { sum += hit - pos; hits ++; } sum += dir * (4 - hits); float dist = (sum / 4f).magnitude / dir.magnitude; result = pos + dir * dist; return hits > 0; } bool SampleCornersMin(Vector3 pos, Vector3 dir, out Vector3 result) { Vector3 r = transform.right * (transform.localScale.x / xRes) * 0.5f; Vector3 f = transform.forward * (transform.localScale.z / yRes) * 0.5f; float minDist = float.PositiveInfinity; float max = dir.magnitude; Vector3 hit; bool didHit = false; if(RaycastNearest(pos - r - f, dir, out hit)) { minDist = Mathf.Min(minDist, (hit - pos).magnitude); didHit = true; } if(RaycastNearest(pos + r - f, dir, out hit)) { minDist = Mathf.Min(minDist, (hit - pos).magnitude); didHit = true; } if(RaycastNearest(pos - r + f, dir, out hit)) { minDist = Mathf.Min(minDist, (hit - pos).magnitude); didHit = true; } if(RaycastNearest(pos + r + f, dir, out hit)) { minDist = Mathf.Min(minDist, (hit - pos).magnitude); didHit = true; } minDist = Mathf.Min(minDist, max); result = pos + dir * minDist / max; return didHit; } bool SampleCornersMax(Vector3 pos, Vector3 dir, out Vector3 result) { Vector3 r = transform.right * (transform.localScale.x / xRes) * 0.5f; Vector3 f = transform.forward * (transform.localScale.z / yRes) * 0.5f; bool wasHit = false; float maxDist = 0f; Vector3 hit; if(RaycastNearest(pos - r - f, dir, out hit)) { maxDist = Mathf.Max(maxDist, (hit - pos).magnitude); wasHit = true; } if(RaycastNearest(pos + r - f, dir, out hit)) { maxDist = Mathf.Max(maxDist, (hit - pos).magnitude); wasHit = true; } if(RaycastNearest(pos - r + f, dir, out hit)) { maxDist = Mathf.Max(maxDist, (hit - pos).magnitude); wasHit = true; } if(RaycastNearest(pos + r + f, dir, out hit)) { maxDist = Mathf.Max(maxDist, (hit - pos).magnitude); wasHit = true; } if(!wasHit) { maxDist = dir.magnitude; } result = pos + dir * maxDist / dir.magnitude; return wasHit; } bool SampleMonteCarlo(Vector3 pos, Vector3 dir, out Vector3 result) { Vector3 r = transform.right * (transform.localScale.x / xRes) * 0.5f; Vector3 f = transform.forward * (transform.localScale.z / yRes) * 0.5f; const int numRays = 9; Vector3 sum = Vector3.zero; int hits = 0; for(int i = 0; i < numRays; i ++) { Vector3 p = pos + r * Random.Range(-1f, 1f) + f * Random.Range(-1f, 1f); Vector3 hit; if(RaycastNearest(p, dir, out hit)) { sum += hit - pos; hits ++; } } sum += dir * (numRays - hits); float dist = (sum / numRays).magnitude / dir.magnitude; result = pos + dir * dist; return hits > 0; } bool RaycastNearest(Vector3 pos, Vector3 dir, out Vector3 point) { RaycastHit[] hits = Physics.RaycastAll(pos, dir, dir.magnitude, ~0); float minDist = float.PositiveInfinity; point = Vector3.zero; foreach(RaycastHit hit in hits) { float dist = hit.distance; if(dist < minDist) { minDist = dist; point = hit.point; } } return hits.Length != 0; } float CalculateEdgeCost(PseudoGridCell src, PseudoGridCell tgt) { switch(edgeCostAlgorithm) { case EdgeCostAlgorithm.EUCLIDEAN_DISTANCE: return Vector3.Distance(tgt.transform.position, src.transform.position); case EdgeCostAlgorithm.ONE_PLUS_POS_SLOPE: return 1.0f + Mathf.Max(0f, Vector3.Dot((tgt.transform.position - src.transform.position), transform.up)); case EdgeCostAlgorithm.ONE: break; } return 1.0f; } public override bool HasChanged { get { return helper.HasChanged; } } public override Edge[] GetChangedEdges() { return helper.GetChangedEdges(); } public override void ResetChanges() { helper.Reset(); } public override NavMeshNode Quantize(Vector3 pos) { // FIXME this is slow float minDist = float.PositiveInfinity; PseudoGridCell nearest = null; foreach(PseudoGridCell cell in cells) { float dist = (pos - cell.transform.position).sqrMagnitude; if(dist < minDist) { nearest = cell; minDist = dist; } } return nearest; } #endif }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Configuration; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.UI; using ASC.Core; using ASC.Core.Users; using ASC.Web.Core; using ASC.Web.Core.Client.Bundling; using ASC.Web.Core.Client.HttpHandlers; using ASC.Web.Core.Mobile; using ASC.Web.Core.Utility; using ASC.Web.Core.Utility.Skins; using ASC.Web.Core.WebZones; using ASC.Web.Studio.Core; using ASC.Web.Studio.PublicResources; using ASC.Web.Studio.UserControls.Common; using ASC.Web.Studio.UserControls.Common.Support; using ASC.Web.Studio.UserControls.Common.ThirdPartyBanner; using ASC.Web.Studio.UserControls.Management; using ASC.Web.Studio.UserControls.Statistics; using ASC.Web.Studio.Utility; namespace ASC.Web.Studio.Masters { public partial class BaseTemplate : MasterPage { /// <summary> /// Block side panel /// </summary> public bool DisabledSidePanel { get; set; } public bool DisabledTopStudioPanel { get; set; } public bool DisabledLayoutMedia { get; set; } private bool? _enableWebChat; public bool EnabledWebChat { get { return _enableWebChat.HasValue && _enableWebChat.Value; } set { _enableWebChat = value; } } public string HubUrl { get; set; } public bool IsMobile { get; set; } public TopStudioPanel TopStudioPanel; protected override void OnInit(EventArgs e) { base.OnInit(e); TopStudioPanel = (TopStudioPanel)LoadControl(TopStudioPanel.Location); MetaKeywords.Content = Resource.MetaKeywords; MetaDescription.Content = Resource.MetaDescription.HtmlEncode(); MetaDescriptionOG.Content = Resource.MetaDescription.HtmlEncode(); MetaTitleOG.Content = (String.IsNullOrEmpty(Page.Title) ? Resource.MainPageTitle : Page.Title).HtmlEncode(); CanonicalURLOG.Content = HttpContext.Current.Request.Url.Scheme + "://" + Request.GetUrlRewriter().Host; MetaImageOG.Content = WebImageSupplier.GetAbsoluteWebPath("logo/fb_icon_325x325.jpg"); } protected void Page_Load(object sender, EventArgs e) { InitScripts(); HubUrl = ConfigurationManagerExtension.AppSettings["web.hub"] ?? string.Empty; if (!_enableWebChat.HasValue || _enableWebChat.Value) { EnabledWebChat = Convert.ToBoolean(ConfigurationManager.AppSettings["web.chat"] ?? "false") && WebItemManager.Instance.GetItems(WebZoneType.CustomProductList, ItemAvailableState.Normal).Any(id => id.ID == WebItemManager.TalkProductID) && !(Request.Browser != null && Request.Browser.Browser == "IE" && Request.Browser.MajorVersion < 11); } IsMobile = MobileDetector.IsMobile; if (!DisabledSidePanel && EnabledWebChat && !IsMobile) { SmallChatHolder.Controls.Add(LoadControl(UserControls.Common.SmallChat.SmallChat.Location)); } if (!DisabledSidePanel && !CoreContext.Configuration.Personal) { /** InvitePanel popup **/ InvitePanelHolder.Controls.Add(LoadControl(InvitePanel.Location)); } if ((!DisabledSidePanel || !DisabledTopStudioPanel) && !TopStudioPanel.DisableSettings && HubUrl != string.Empty && SecurityContext.IsAuthenticated) { AddBodyScripts(ResolveUrl, "~/js/third-party/socket.io.js", "~/js/asc/core/asc.socketio.js"); } if (!DisabledTopStudioPanel) { TopContent.Controls.Add(TopStudioPanel); } if (!EmailActivated && !CoreContext.Configuration.Personal && SecurityContext.IsAuthenticated && EmailActivationSettings.LoadForCurrentUser().Show) { activateEmailPanel.Controls.Add(LoadControl(ActivateEmailPanel.Location)); } if (ThirdPartyBanner.Display && !Request.DesktopApp()) { BannerHolder.Controls.Add(LoadControl(ThirdPartyBanner.Location)); } var curUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); if (!DisabledSidePanel) { TariffNotifyHolder.Controls.Add(LoadControl(TariffNotify.Location)); } if (curUser.IsVisitor() && !curUser.IsOutsider()) { var collaboratorPopupSettings = CollaboratorSettings.LoadForCurrentUser(); if (collaboratorPopupSettings.FirstVisit) { AddBodyScripts(ResolveUrl, "~/js/asc/core/collaborators.js"); } } var matches = Regex.Match(HttpContext.Current.Request.Url.AbsolutePath, "(products|addons)/(\\w+)/(share\\.aspx|saveas\\.aspx|filechoice\\.aspx|ganttchart\\.aspx|jabberclient\\.aspx|timer\\.aspx|generatedreport\\.aspx).*", RegexOptions.IgnoreCase); if (SecurityContext.IsAuthenticated && !matches.Success) { LiveChatHolder.Controls.Add(LoadControl(SupportChat.Location)); AddBodyScripts(ResolveUrl, "~/UserControls/Common/Support/livechat.js"); } } protected string RenderStatRequest() { if (string.IsNullOrEmpty(SetupInfo.StatisticTrackURL)) return string.Empty; var page = HttpUtility.UrlEncode(Page.AppRelativeVirtualPath.Replace("~", "")); return String.Format("<img style=\"display:none;\" src=\"{0}\"/>", SetupInfo.StatisticTrackURL + "&page=" + page); } protected bool EmailActivated { get { var usr = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); return usr.CreateDate.Date == DateTime.UtcNow.Date || usr.ActivationStatus == EmployeeActivationStatus.Activated; } } protected string ColorThemeClass { get { return ColorThemesSettings.GetColorThemesSettings(); } } #region Operations private void InitScripts() { AddStyles(r => r, "~/skins/<theme_folder>/main.less"); AddClientScript( new MasterResources.MasterSettingsResources(), new MasterResources.MasterUserResources(), new MasterResources.MasterFileUtilityResources(), new MasterResources.MasterCustomResources(), new MasterResources.MasterLocalizationResources() ); InitProductSettingsInlineScript(); InitStudioSettingsInlineScript(); } private void InitStudioSettingsInlineScript() { var paid = !TenantStatisticsProvider.IsNotPaid(); var showPromotions = paid && PromotionsSettings.Load().Show; var showTips = !Request.DesktopApp() && paid && TipsSettings.LoadForCurrentUser().Show; var script = new StringBuilder(); script.AppendFormat("window.ASC.Resources.Master.ShowPromotions={0};", showPromotions.ToString().ToLowerInvariant()); script.AppendFormat("window.ASC.Resources.Master.ShowTips={0};", showTips.ToString().ToLowerInvariant()); RegisterInlineScript(script.ToString(), true, false); } private void InitProductSettingsInlineScript() { var isAdmin = false; if (!CoreContext.Configuration.Personal) { isAdmin = WebItemSecurity.IsProductAdministrator(CommonLinkUtility.GetProductID(), SecurityContext.CurrentAccount.ID); if (!isAdmin) { isAdmin = WebItemSecurity.IsProductAdministrator(CommonLinkUtility.GetAddonID(), SecurityContext.CurrentAccount.ID); } } RegisterInlineScript(string.Format("window.ASC.Resources.Master.IsProductAdmin={0};", isAdmin.ToString().ToLowerInvariant()), true, false); } #region Style public BaseTemplate AddStyles(Func<string, string> converter, params string[] src) { foreach (var s in src) { if (s.Contains(ColorThemesSettings.ThemeFolderTemplate)) { if (ThemeStyles == null) continue; ThemeStyles.AddSource(r => ResolveUrl(ColorThemesSettings.GetThemeFolderName(converter(r))), s); } else { if (HeadStyles == null) continue; HeadStyles.AddSource(converter, s); } } return this; } #endregion #region Scripts public BaseTemplate AddBodyScripts(Func<string, string> converter, params string[] src) { if (BodyScripts == null) return this; BodyScripts.AddSource(converter, src); return this; } public BaseTemplate AddStaticBodyScripts(ScriptBundleData bundleData) { StaticScript.SetData(bundleData); return this; } public BaseTemplate AddStaticStyles(StyleBundleData bundleData) { StaticStyle.SetData(bundleData); return this; } public BaseTemplate RegisterInlineScript(string script, bool beforeBodyScripts = false, bool onReady = true) { var tuple = new Tuple<string, bool>(script, onReady); if (!beforeBodyScripts) InlineScript.Scripts.Add(tuple); else InlineScriptBefore.Scripts.Add(tuple); return this; } #endregion #region ClientScript public BaseTemplate AddClientScript(ClientScript clientScript) { var localizationScript = clientScript as ClientScriptLocalization; if (localizationScript != null) { clientLocalizationScript.AddScript(clientScript); return this; } baseTemplateMasterScripts.AddScript(clientScript); return this; } public BaseTemplate AddClientScript(params ClientScript[] clientScript) { foreach (var script in clientScript) { AddClientScript(script); } return this; } #endregion #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Threading; using NUnit.Framework; namespace Apache.NMS.Test { [TestFixture] public class ConsumerTest : NMSTestSupport { protected const int COUNT = 25; protected const string VALUE_NAME = "value"; private bool dontAck; // The .NET CF does not have the ability to interrupt threads, so this test is impossible. #if !NETCF [Test] public void TestNoTimeoutConsumer( [Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge, AcknowledgementMode.DupsOkAcknowledge, AcknowledgementMode.Transactional)] AcknowledgementMode ackMode) { // Launch a thread to perform IMessageConsumer.Receive(). // If it doesn't fail in less than three seconds, no exception was thrown. Thread receiveThread = new Thread(new ThreadStart(TimeoutConsumerThreadProc)); using(IConnection connection = CreateConnection()) { connection.Start(); using(ISession session = connection.CreateSession(ackMode)) { ITemporaryQueue queue = session.CreateTemporaryQueue(); using(this.timeoutConsumer = session.CreateConsumer(queue)) { receiveThread.Start(); if(receiveThread.Join(3000)) { Assert.Fail("IMessageConsumer.Receive() returned without blocking. Test failed."); } else { // Kill the thread - otherwise it'll sit in Receive() until a message arrives. receiveThread.Interrupt(); } } } } } protected IMessageConsumer timeoutConsumer; protected void TimeoutConsumerThreadProc() { try { timeoutConsumer.Receive(); } catch(ArgumentOutOfRangeException e) { // The test failed. We will know because the timeout will expire inside TestNoTimeoutConsumer(). Assert.Fail("Test failed with exception: " + e.Message); } catch(ThreadInterruptedException) { // The test succeeded! We were still blocked when we were interrupted. } catch(Exception e) { // Some other exception occurred. Assert.Fail("Test failed with exception: " + e.Message); } } [Test] public void TestSyncReceiveConsumerClose( [Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge, AcknowledgementMode.DupsOkAcknowledge, AcknowledgementMode.Transactional)] AcknowledgementMode ackMode) { // Launch a thread to perform IMessageConsumer.Receive(). // If it doesn't fail in less than three seconds, no exception was thrown. Thread receiveThread = new Thread(new ThreadStart(TimeoutConsumerThreadProc)); using (IConnection connection = CreateConnection()) { connection.Start(); using (ISession session = connection.CreateSession(ackMode)) { ITemporaryQueue queue = session.CreateTemporaryQueue(); using (this.timeoutConsumer = session.CreateConsumer(queue)) { receiveThread.Start(); if (receiveThread.Join(3000)) { Assert.Fail("IMessageConsumer.Receive() returned without blocking. Test failed."); } else { // Kill the thread - otherwise it'll sit in Receive() until a message arrives. this.timeoutConsumer.Close(); receiveThread.Join(10000); if (receiveThread.IsAlive) { // Kill the thread - otherwise it'll sit in Receive() until a message arrives. receiveThread.Interrupt(); Assert.Fail("IMessageConsumer.Receive() thread is still alive, Close should have killed it."); } } } } } } internal class ThreadArg { internal IConnection connection = null; internal ISession session = null; internal IDestination destination = null; } protected void DelayedProducerThreadProc(Object arg) { try { ThreadArg args = arg as ThreadArg; using(ISession session = args.connection.CreateSession()) { using(IMessageProducer producer = session.CreateProducer(args.destination)) { // Give the consumer time to enter the receive. Thread.Sleep(5000); producer.Send(args.session.CreateTextMessage("Hello World")); } } } catch(Exception e) { // Some other exception occurred. Assert.Fail("Test failed with exception: " + e.Message); } } [Test] public void TestDoChangeSentMessage( [Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge, AcknowledgementMode.DupsOkAcknowledge, AcknowledgementMode.Transactional)] AcknowledgementMode ackMode, [Values(true, false)] bool doClear) { using(IConnection connection = CreateConnection()) { connection.Start(); using(ISession session = connection.CreateSession(ackMode)) { ITemporaryQueue queue = session.CreateTemporaryQueue(); using(IMessageConsumer consumer = session.CreateConsumer(queue)) { IMessageProducer producer = session.CreateProducer(queue); ITextMessage message = session.CreateTextMessage(); string prefix = "ConsumerTest - TestDoChangeSentMessage: "; for(int i = 0; i < COUNT; i++) { message.Properties[VALUE_NAME] = i; message.Text = prefix + Convert.ToString(i); producer.Send(message); if(doClear) { message.ClearBody(); message.ClearProperties(); } } if(ackMode == AcknowledgementMode.Transactional) { session.Commit(); } for(int i = 0; i < COUNT; i++) { ITextMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(2000)) as ITextMessage; Assert.AreEqual(msg.Text, prefix + Convert.ToString(i)); Assert.AreEqual(msg.Properties.GetInt(VALUE_NAME), i); } if(ackMode == AcknowledgementMode.Transactional) { session.Commit(); } } } } } [Test] public void TestConsumerReceiveBeforeMessageDispatched( [Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge, AcknowledgementMode.DupsOkAcknowledge, AcknowledgementMode.Transactional)] AcknowledgementMode ackMode) { // Launch a thread to perform a delayed send. Thread sendThread = new Thread(DelayedProducerThreadProc); using(IConnection connection = CreateConnection()) { connection.Start(); using(ISession session = connection.CreateSession(ackMode)) { ITemporaryQueue queue = session.CreateTemporaryQueue(); using(IMessageConsumer consumer = session.CreateConsumer(queue)) { ThreadArg arg = new ThreadArg(); arg.connection = connection; arg.session = session; arg.destination = queue; sendThread.Start(arg); IMessage message = consumer.Receive(TimeSpan.FromMinutes(1)); Assert.IsNotNull(message); } } } } [Test] public void TestDontStart( [Values(MsgDeliveryMode.NonPersistent)] MsgDeliveryMode deliveryMode, [Values(DestinationType.Queue, DestinationType.Topic)] DestinationType destinationType ) { using(IConnection connection = CreateConnection()) { ISession session = connection.CreateSession(); IDestination destination = CreateDestination(session, destinationType); IMessageConsumer consumer = session.CreateConsumer(destination); // Send the messages SendMessages(session, destination, deliveryMode, 1); // Make sure no messages were delivered. Assert.IsNull(consumer.Receive(TimeSpan.FromMilliseconds(1000))); } } [Test] public void TestSendReceiveTransacted( [Values(MsgDeliveryMode.NonPersistent, MsgDeliveryMode.Persistent)] MsgDeliveryMode deliveryMode, [Values(DestinationType.Queue, DestinationType.Topic, DestinationType.TemporaryQueue, DestinationType.TemporaryTopic)] DestinationType destinationType) { using(IConnection connection = CreateConnection()) { // Send a message to the broker. connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.Transactional); IDestination destination = CreateDestination(session, destinationType); IMessageConsumer consumer = session.CreateConsumer(destination); IMessageProducer producer = session.CreateProducer(destination); producer.DeliveryMode = deliveryMode; producer.Send(session.CreateTextMessage("Test")); // Message should not be delivered until commit. Thread.Sleep(1000); Assert.IsNull(consumer.ReceiveNoWait()); session.Commit(); // Make sure only 1 message was delivered. IMessage message = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(message); Assert.IsFalse(message.NMSRedelivered); Assert.IsNull(consumer.ReceiveNoWait()); // Message should be redelivered is rollback is used. session.Rollback(); // Make sure only 1 message was delivered. message = consumer.Receive(TimeSpan.FromMilliseconds(2000)); Assert.IsNotNull(message); Assert.IsTrue(message.NMSRedelivered); Assert.IsNull(consumer.ReceiveNoWait()); // If we commit now, the message should not be redelivered. session.Commit(); Thread.Sleep(1000); Assert.IsNull(consumer.ReceiveNoWait()); } } [Test] public void TestAckedMessageAreConsumed() { using(IConnection connection = CreateConnection()) { connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IDestination destination = CreateDestination(session, DestinationType.Queue); IMessageProducer producer = session.CreateProducer(destination); producer.Send(session.CreateTextMessage("Hello")); // Consume the message... IMessageConsumer consumer = session.CreateConsumer(destination); IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); msg.Acknowledge(); // Reset the session. session.Close(); session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); // Attempt to Consume the message... consumer = session.CreateConsumer(destination); msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNull(msg); session.Close(); } } [Test] public void TestLastMessageAcked() { using(IConnection connection = CreateConnection()) { connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IDestination destination = CreateDestination(session, DestinationType.Queue); IMessageProducer producer = session.CreateProducer(destination); producer.Send(session.CreateTextMessage("Hello")); producer.Send(session.CreateTextMessage("Hello2")); producer.Send(session.CreateTextMessage("Hello3")); // Consume the message... IMessageConsumer consumer = session.CreateConsumer(destination); IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); msg.Acknowledge(); // Reset the session. session.Close(); session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); // Attempt to Consume the message... consumer = session.CreateConsumer(destination); msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNull(msg); session.Close(); } } [Test] public void TestUnAckedMessageAreNotConsumedOnSessionClose() { using(IConnection connection = CreateConnection()) { connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IDestination destination = CreateDestination(session, DestinationType.Queue); IMessageProducer producer = session.CreateProducer(destination); producer.Send(session.CreateTextMessage("Hello")); // Consume the message... IMessageConsumer consumer = session.CreateConsumer(destination); IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); // Don't ack the message. // Reset the session. This should cause the unacknowledged message to be re-delivered. session.Close(); session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); // Attempt to Consume the message... consumer = session.CreateConsumer(destination); msg = consumer.Receive(TimeSpan.FromMilliseconds(2000)); Assert.IsNotNull(msg); msg.Acknowledge(); session.Close(); } } [Test] public void TestAsyncAckedMessageAreConsumed() { using(IConnection connection = CreateConnection()) { connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IDestination destination = CreateDestination(session, DestinationType.Queue); IMessageProducer producer = session.CreateProducer(destination); producer.Send(session.CreateTextMessage("Hello")); // Consume the message... IMessageConsumer consumer = session.CreateConsumer(destination); consumer.Listener += new MessageListener(OnMessage); Thread.Sleep(5000); // Reset the session. session.Close(); session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); // Attempt to Consume the message... consumer = session.CreateConsumer(destination); IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNull(msg); session.Close(); } } [Test] public void TestAsyncUnAckedMessageAreNotConsumedOnSessionClose() { using(IConnection connection = CreateConnection()) { connection.Start(); // don't aknowledge message on onMessage() call dontAck = true; ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IDestination destination = CreateDestination(session, DestinationType.Queue); IMessageProducer producer = session.CreateProducer(destination); producer.Send(session.CreateTextMessage("Hello")); // Consume the message... IMessageConsumer consumer = session.CreateConsumer(destination); consumer.Listener += new MessageListener(OnMessage); // Don't ack the message. // Reset the session. This should cause the Unacked message to be // redelivered. session.Close(); Thread.Sleep(5000); session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); // Attempt to Consume the message... consumer = session.CreateConsumer(destination); IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(2000)); Assert.IsNotNull(msg); msg.Acknowledge(); session.Close(); } } [Test] public void TestAddRemoveAsnycMessageListener() { using(IConnection connection = CreateConnection()) { connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); ITemporaryTopic topic = session.CreateTemporaryTopic(); IMessageConsumer consumer = session.CreateConsumer(topic); consumer.Listener += OnMessage; consumer.Listener -= OnMessage; consumer.Listener += OnMessage; consumer.Close(); } } public void OnMessage(IMessage message) { Assert.IsNotNull(message); if(!dontAck) { try { message.Acknowledge(); } catch(Exception) { } } } [Test] public void TestReceiveNoWait( [Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge, AcknowledgementMode.DupsOkAcknowledge, AcknowledgementMode.Transactional)] AcknowledgementMode ackMode, [Values(MsgDeliveryMode.NonPersistent, MsgDeliveryMode.Persistent)] MsgDeliveryMode deliveryMode) { const int RETRIES = 20; using(IConnection connection = CreateConnection()) { connection.Start(); using(ISession session = connection.CreateSession(ackMode)) { IDestination destination = session.CreateTemporaryQueue(); using(IMessageProducer producer = session.CreateProducer(destination)) { producer.DeliveryMode = deliveryMode; ITextMessage message = session.CreateTextMessage("TEST"); producer.Send(message); if(AcknowledgementMode.Transactional == ackMode) { session.Commit(); } } using(IMessageConsumer consumer = session.CreateConsumer(destination)) { IMessage message = null; for(int i = 0; i < RETRIES && message == null; ++i) { message = consumer.ReceiveNoWait(); Thread.Sleep(100); } Assert.IsNotNull(message); message.Acknowledge(); if(AcknowledgementMode.Transactional == ackMode) { session.Commit(); } } } } } #endif } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// /// </summary> [DataContract] public partial class LowStock : IEquatable<LowStock> { /// <summary> /// Initializes a new instance of the <see cref="LowStock" /> class. /// Initializes a new instance of the <see cref="LowStock" />class. /// </summary> /// <param name="WarehouseId">WarehouseId (required).</param> /// <param name="CustomFields">CustomFields.</param> /// <param name="Sku">Sku.</param> public LowStock(int? WarehouseId = null, Dictionary<string, Object> CustomFields = null, string Sku = null) { // to ensure "WarehouseId" is required (not null) if (WarehouseId == null) { throw new InvalidDataException("WarehouseId is a required property for LowStock and cannot be null"); } else { this.WarehouseId = WarehouseId; } this.CustomFields = CustomFields; this.Sku = Sku; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets WarehouseId /// </summary> [DataMember(Name="warehouseId", EmitDefaultValue=false)] public int? WarehouseId { get; set; } /// <summary> /// Gets or Sets LowLevelDate /// </summary> [DataMember(Name="lowLevelDate", EmitDefaultValue=false)] public DateTime? LowLevelDate { get; private set; } /// <summary> /// Gets or Sets LowStockMessage /// </summary> [DataMember(Name="lowStockMessage", EmitDefaultValue=false)] public string LowStockMessage { get; private set; } /// <summary> /// Gets or Sets PrintFlag /// </summary> [DataMember(Name="printFlag", EmitDefaultValue=false)] public string PrintFlag { get; private set; } /// <summary> /// Gets or Sets IsDelayed /// </summary> [DataMember(Name="isDelayed", EmitDefaultValue=false)] public bool? IsDelayed { get; private set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="createDate", EmitDefaultValue=false)] public DateTime? CreateDate { get; private set; } /// <summary> /// Gets or Sets ModifyDate /// </summary> [DataMember(Name="modifyDate", EmitDefaultValue=false)] public DateTime? ModifyDate { get; private set; } /// <summary> /// Gets or Sets CustomFields /// </summary> [DataMember(Name="customFields", EmitDefaultValue=false)] public Dictionary<string, Object> CustomFields { get; set; } /// <summary> /// Gets or Sets Sku /// </summary> [DataMember(Name="sku", EmitDefaultValue=false)] public string Sku { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class LowStock {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" WarehouseId: ").Append(WarehouseId).Append("\n"); sb.Append(" LowLevelDate: ").Append(LowLevelDate).Append("\n"); sb.Append(" LowStockMessage: ").Append(LowStockMessage).Append("\n"); sb.Append(" PrintFlag: ").Append(PrintFlag).Append("\n"); sb.Append(" IsDelayed: ").Append(IsDelayed).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append(" CustomFields: ").Append(CustomFields).Append("\n"); sb.Append(" Sku: ").Append(Sku).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as LowStock); } /// <summary> /// Returns true if LowStock instances are equal /// </summary> /// <param name="other">Instance of LowStock to be compared</param> /// <returns>Boolean</returns> public bool Equals(LowStock other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.WarehouseId == other.WarehouseId || this.WarehouseId != null && this.WarehouseId.Equals(other.WarehouseId) ) && ( this.LowLevelDate == other.LowLevelDate || this.LowLevelDate != null && this.LowLevelDate.Equals(other.LowLevelDate) ) && ( this.LowStockMessage == other.LowStockMessage || this.LowStockMessage != null && this.LowStockMessage.Equals(other.LowStockMessage) ) && ( this.PrintFlag == other.PrintFlag || this.PrintFlag != null && this.PrintFlag.Equals(other.PrintFlag) ) && ( this.IsDelayed == other.IsDelayed || this.IsDelayed != null && this.IsDelayed.Equals(other.IsDelayed) ) && ( this.CreateDate == other.CreateDate || this.CreateDate != null && this.CreateDate.Equals(other.CreateDate) ) && ( this.ModifyDate == other.ModifyDate || this.ModifyDate != null && this.ModifyDate.Equals(other.ModifyDate) ) && ( this.CustomFields == other.CustomFields || this.CustomFields != null && this.CustomFields.SequenceEqual(other.CustomFields) ) && ( this.Sku == other.Sku || this.Sku != null && this.Sku.Equals(other.Sku) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.WarehouseId != null) hash = hash * 59 + this.WarehouseId.GetHashCode(); if (this.LowLevelDate != null) hash = hash * 59 + this.LowLevelDate.GetHashCode(); if (this.LowStockMessage != null) hash = hash * 59 + this.LowStockMessage.GetHashCode(); if (this.PrintFlag != null) hash = hash * 59 + this.PrintFlag.GetHashCode(); if (this.IsDelayed != null) hash = hash * 59 + this.IsDelayed.GetHashCode(); if (this.CreateDate != null) hash = hash * 59 + this.CreateDate.GetHashCode(); if (this.ModifyDate != null) hash = hash * 59 + this.ModifyDate.GetHashCode(); if (this.CustomFields != null) hash = hash * 59 + this.CustomFields.GetHashCode(); if (this.Sku != null) hash = hash * 59 + this.Sku.GetHashCode(); return hash; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using CslaGenerator.Util; using DBSchemaInfo.Base; namespace CslaGenerator.Controls { /// <summary> /// Summary description for DbTreeView. /// </summary> public class DbTreeView : UserControl { private Panel panelTop; private Panel panel2; private Panel panel3; private PaneCaption paneCaption1; private Panel panelBottom; private Panel panelTrim; private Panel panel4; private Panel panelBody; private TreeView treeViewSchema; private Splitter splitMiddle; private PropertyGrid propertyGridDbObjects; internal ImageList schemaImages; private IContainer components; public delegate void TreeViewAfterSelectEventHandler(object sender, TreeViewEventArgs e); public virtual event TreeViewAfterSelectEventHandler TreeViewAfterSelect; public delegate void TreeViewMouseUpEventHandler(object sender, MouseEventArgs e); public virtual event TreeViewMouseUpEventHandler TreeViewMouseUp; public DbTreeView() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DbTreeView)); this.panelTop = new System.Windows.Forms.Panel(); this.panel2 = new System.Windows.Forms.Panel(); this.panel3 = new System.Windows.Forms.Panel(); this.paneCaption1 = new CslaGenerator.Controls.PaneCaption(); this.panelBottom = new System.Windows.Forms.Panel(); this.panelTrim = new System.Windows.Forms.Panel(); this.panel4 = new System.Windows.Forms.Panel(); this.panelBody = new System.Windows.Forms.Panel(); this.propertyGridDbObjects = new System.Windows.Forms.PropertyGrid(); this.splitMiddle = new System.Windows.Forms.Splitter(); this.treeViewSchema = new System.Windows.Forms.TreeView(); this.schemaImages = new System.Windows.Forms.ImageList(this.components); this.panelTop.SuspendLayout(); this.panel2.SuspendLayout(); this.panel3.SuspendLayout(); this.panelBottom.SuspendLayout(); this.panelTrim.SuspendLayout(); this.panel4.SuspendLayout(); this.panelBody.SuspendLayout(); this.SuspendLayout(); // // panelTop // this.panelTop.Controls.Add(this.panel2); this.panelTop.Dock = System.Windows.Forms.DockStyle.Top; this.panelTop.Location = new System.Drawing.Point(0, 0); this.panelTop.Name = "panelTop"; this.panelTop.Padding = new System.Windows.Forms.Padding(3); this.panelTop.Size = new System.Drawing.Size(264, 32); this.panelTop.TabIndex = 12; // // panel2 // this.panel2.BackColor = System.Drawing.SystemColors.ControlDark; this.panel2.Controls.Add(this.panel3); this.panel2.Dock = System.Windows.Forms.DockStyle.Fill; this.panel2.Location = new System.Drawing.Point(3, 3); this.panel2.Name = "panel2"; this.panel2.Padding = new System.Windows.Forms.Padding(1); this.panel2.Size = new System.Drawing.Size(258, 26); this.panel2.TabIndex = 13; // // panel3 // this.panel3.BackColor = System.Drawing.SystemColors.Control; this.panel3.Controls.Add(this.paneCaption1); this.panel3.Dock = System.Windows.Forms.DockStyle.Fill; this.panel3.Location = new System.Drawing.Point(1, 1); this.panel3.Name = "panel3"; this.panel3.Padding = new System.Windows.Forms.Padding(3); this.panel3.Size = new System.Drawing.Size(256, 24); this.panel3.TabIndex = 13; // // paneCaption1 // this.paneCaption1.AllowActive = false; this.paneCaption1.AntiAlias = false; this.paneCaption1.Caption = "Schema Objects"; this.paneCaption1.Dock = System.Windows.Forms.DockStyle.Fill; this.paneCaption1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.paneCaption1.InactiveGradientHighColor = System.Drawing.Color.FromArgb(((int)(((byte)(149)))), ((int)(((byte)(184)))), ((int)(((byte)(245))))); this.paneCaption1.InactiveGradientLowColor = System.Drawing.Color.White; this.paneCaption1.Location = new System.Drawing.Point(3, 3); this.paneCaption1.Name = "paneCaption1"; this.paneCaption1.Size = new System.Drawing.Size(250, 18); this.paneCaption1.TabIndex = 11; // // panelBottom // this.panelBottom.Controls.Add(this.panelTrim); this.panelBottom.Dock = System.Windows.Forms.DockStyle.Fill; this.panelBottom.Location = new System.Drawing.Point(0, 32); this.panelBottom.Name = "panelBottom"; this.panelBottom.Padding = new System.Windows.Forms.Padding(3, 1, 3, 3); this.panelBottom.Size = new System.Drawing.Size(264, 384); this.panelBottom.TabIndex = 13; // // panelTrim // this.panelTrim.BackColor = System.Drawing.SystemColors.ControlDark; this.panelTrim.Controls.Add(this.panel4); this.panelTrim.Dock = System.Windows.Forms.DockStyle.Fill; this.panelTrim.Location = new System.Drawing.Point(3, 1); this.panelTrim.Name = "panelTrim"; this.panelTrim.Padding = new System.Windows.Forms.Padding(1); this.panelTrim.Size = new System.Drawing.Size(258, 380); this.panelTrim.TabIndex = 10; // // panel4 // this.panel4.BackColor = System.Drawing.SystemColors.Control; this.panel4.Controls.Add(this.panelBody); this.panel4.Dock = System.Windows.Forms.DockStyle.Fill; this.panel4.Location = new System.Drawing.Point(1, 1); this.panel4.Name = "panel4"; this.panel4.Padding = new System.Windows.Forms.Padding(3); this.panel4.Size = new System.Drawing.Size(256, 378); this.panel4.TabIndex = 11; // // panelBody // this.panelBody.BackColor = System.Drawing.SystemColors.Control; this.panelBody.Controls.Add(this.propertyGridDbObjects); this.panelBody.Controls.Add(this.splitMiddle); this.panelBody.Controls.Add(this.treeViewSchema); this.panelBody.Dock = System.Windows.Forms.DockStyle.Fill; this.panelBody.Location = new System.Drawing.Point(3, 3); this.panelBody.Name = "panelBody"; this.panelBody.Padding = new System.Windows.Forms.Padding(2); this.panelBody.Size = new System.Drawing.Size(250, 372); this.panelBody.TabIndex = 11; // // pgdDbObjects // this.propertyGridDbObjects.Dock = System.Windows.Forms.DockStyle.Fill; this.propertyGridDbObjects.HelpVisible = false; this.propertyGridDbObjects.LineColor = System.Drawing.SystemColors.ScrollBar; this.propertyGridDbObjects.Location = new System.Drawing.Point(2, 221); this.propertyGridDbObjects.Name = "pgdDbObjects"; this.propertyGridDbObjects.Size = new System.Drawing.Size(246, 149); this.propertyGridDbObjects.PropertySort = PropertySort.NoSort; this.propertyGridDbObjects.TabIndex = 5; // // splitMiddle // this.splitMiddle.Dock = System.Windows.Forms.DockStyle.Top; this.splitMiddle.Location = new System.Drawing.Point(2, 216); this.splitMiddle.Name = "splitMiddle"; this.splitMiddle.Size = new System.Drawing.Size(246, 5); this.splitMiddle.TabIndex = 6; this.splitMiddle.TabStop = false; // // treeViewSchema // this.treeViewSchema.Dock = System.Windows.Forms.DockStyle.Top; this.treeViewSchema.HideSelection = false; this.treeViewSchema.Location = new System.Drawing.Point(2, 2); this.treeViewSchema.Name = "treeViewSchema"; this.treeViewSchema.Size = new System.Drawing.Size(246, 214); this.treeViewSchema.TabIndex = 7; this.treeViewSchema.ControlAdded += new System.Windows.Forms.ControlEventHandler(this.treeViewSchema_ControlAdded); this.treeViewSchema.MouseUp += new System.Windows.Forms.MouseEventHandler(this.treeViewSchema_MouseUp); this.treeViewSchema.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeViewSchema_AfterSelect); // // schemaImages // this.schemaImages.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("schemaImages.ImageStream"))); this.schemaImages.TransparentColor = System.Drawing.Color.Black; this.schemaImages.Images.SetKeyName(0, "0db.png"); this.schemaImages.Images.SetKeyName(1, "1.png"); this.schemaImages.Images.SetKeyName(2, "2.png"); this.schemaImages.Images.SetKeyName(3, "3.png"); this.schemaImages.Images.SetKeyName(4, "4.png"); this.schemaImages.Images.SetKeyName(5, "5.png"); this.schemaImages.Images.SetKeyName(6, "6.png"); this.schemaImages.Images.SetKeyName(7, "7.png"); this.schemaImages.Images.SetKeyName(8, "8.png"); this.schemaImages.Images.SetKeyName(9, "9.png"); this.schemaImages.Images.SetKeyName(10, "field.png"); // // DbTreeView // this.Controls.Add(this.panelBottom); this.Controls.Add(this.panelTop); this.Name = "DbTreeView"; this.Size = new System.Drawing.Size(264, 416); this.Load += new System.EventHandler(this.DbTreeView_Load); this.panelTop.ResumeLayout(false); this.panel2.ResumeLayout(false); this.panel3.ResumeLayout(false); this.panelBottom.ResumeLayout(false); this.panelTrim.ResumeLayout(false); this.panel4.ResumeLayout(false); this.panelBody.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void DbTreeView_Load(object sender, EventArgs e) { treeViewSchema.Height = (int)((double)0.75 * (double)this.panelBody.Height); } Image Convert(Image orig) { Bitmap n = new Bitmap(16, 16, System.Drawing.Imaging.PixelFormat.Format32bppRgb); using (Graphics g = Graphics.FromImage(n)) { g.DrawImage(orig, 0, 0); } return n; } internal void SetDbTreeViewPctHeight(double pct) { if (pct > 0 && pct < 100) { treeViewSchema.Height = (int)((double)pct / 100 * (double)this.panelBody.Height); Invalidate(); } } private void treeViewSchema_AfterSelect(object sender, TreeViewEventArgs e) { PropertyGridDbObjects.SelectedObject = e.Node.Tag; if (TreeViewAfterSelect != null) TreeViewAfterSelect(sender, e); } private void treeViewSchema_MouseUp(object sender, MouseEventArgs e) { if (TreeViewMouseUp != null) TreeViewMouseUp(sender, e); } #region Properties internal TreeView TreeViewSchema { get { return treeViewSchema; } } internal PropertyGrid PropertyGridDbObjects { get { return propertyGridDbObjects; } } #endregion private void treeViewSchema_ControlAdded(object sender, ControlEventArgs e) { Console.Write(e.Control.Name + " " + e.Control.Text); } bool _showColumns; public void BuildSchemaTree(ICatalog catalog) { BuildSchemaTree(catalog, false); } public void BuildSchemaTree(ICatalog catalog, bool showColumns) { _showColumns = showColumns; TreeViewSchema.Nodes.Clear(); treeViewSchema.ImageList = schemaImages; if (showColumns) { TreeNode emptyNode = new TreeNode("None"); emptyNode.ImageIndex = (int)TreeViewIcons.field; emptyNode.SelectedImageIndex = (int)TreeViewIcons.field; TreeViewSchema.Nodes.Add(emptyNode); } TreeNode tableBaseNode = null; #region Add Tables TreeNode[] tableNodes = new TreeNode[catalog.Tables.Count]; TreeNode node; for (int i = 0; i < catalog.Tables.Count; i++) { node = new TreeNode(); tableNodes[i] = node; LoadTableNode(node, catalog.Tables[i]); } if (catalog.Tables.Count > 0) { Array.Sort(tableNodes, new TreeNodeComparer()); tableBaseNode = new TreeNode("Tables", tableNodes); } else { tableBaseNode = new TreeNode("Tables"); } tableBaseNode.ImageIndex = (int)TreeViewIcons.db; tableBaseNode.SelectedImageIndex = (int)TreeViewIcons.db; TreeViewSchema.Nodes.Add(tableBaseNode); #endregion #region Add Views TreeNode viewBaseNode; TreeNode[] viewNodes = new TreeNode[catalog.Views.Count]; for (int i = 0; i < catalog.Views.Count; i++) { node = new TreeNode(); viewNodes[i] = node; LoadViewNode(node, catalog.Views[i]); } if (catalog.Views.Count > 0) { Array.Sort(viewNodes, new TreeNodeComparer()); viewBaseNode = new TreeNode("Views", viewNodes); } else { viewBaseNode = new TreeNode("Views"); } viewBaseNode.ImageIndex = (int)TreeViewIcons.db; viewBaseNode.SelectedImageIndex = (int)TreeViewIcons.db; TreeViewSchema.Nodes.Add(viewBaseNode); #endregion #region Add Stored Procs TreeNode spBaseNode; List<TreeNode> spNodes = new List<TreeNode>(); for (int i = 0; i < catalog.Procedures.Count; i++) { node = new TreeNode(); LoadStoredProcedureNode(node, catalog.Procedures[i]); spNodes.Add(node); } if (catalog.Procedures.Count > 0) { spNodes.Sort(new TreeNodeComparer()); spBaseNode = new TreeNode("Stored Procedures", spNodes.ToArray()); } else { spBaseNode = new TreeNode("Stored Procedures"); } spBaseNode.ImageIndex = (int)TreeViewIcons.db; spBaseNode.SelectedImageIndex = (int)TreeViewIcons.db; TreeViewSchema.Nodes.Add(spBaseNode); #endregion } public void LoadNode(TreeNode node, IDataBaseObject obj) { if (obj is IStoredProcedureInfo) LoadStoredProcedureNode(node, (IStoredProcedureInfo)obj); else if (obj is IViewInfo) LoadViewNode(node, (IViewInfo)obj); else if (obj is ITableInfo) LoadTableNode(node, (ITableInfo)obj); } public void LoadTableNode(TreeNode node, ITableInfo obj) { node.Tag = obj; node.Text = GetObjectName(obj); node.ImageIndex = (int)TreeViewIcons.table; node.SelectedImageIndex = (int)TreeViewIcons.table; if (_showColumns) AddColumns(node, obj.Columns); } public void LoadViewNode(TreeNode node, IViewInfo obj) { node.Tag = obj; node.Text = GetObjectName(obj); node.ImageIndex = (int)TreeViewIcons.view; node.SelectedImageIndex = (int)TreeViewIcons.view; if (_showColumns) AddColumns(node, obj.Columns); } public void LoadStoredProcedureNode(TreeNode node, IStoredProcedureInfo obj) { var parameterNodes = new TreeNode[obj.Parameters.Count]; if (obj.Parameters.Count > 0) { // Add parameter nodes for (int j = 0; j < obj.Parameters.Count; j++) { var pNode = new TreeNode(obj.Parameters[j].ParameterName); parameterNodes[j] = pNode; pNode.Tag = obj.Parameters[j]; pNode.ImageIndex = (int)TreeViewIcons.resultset; pNode.SelectedImageIndex = (int)TreeViewIcons.resultset; } } var resultNodes = new TreeNode[obj.ResultSets.Count]; if (obj.ResultSets.Count > 0) { // Add result nodes for (int j = 0; j < obj.ResultSets.Count; j++) { var rNode = new TreeNode("Result Set " + (j + 1)); resultNodes[j] = rNode; rNode.Tag = obj.ResultSets[j]; rNode.ImageIndex = (int)TreeViewIcons.resultset; rNode.SelectedImageIndex = (int)TreeViewIcons.resultset; if (_showColumns) AddColumns(rNode, obj.ResultSets[j].Columns); } } var procName = string.Empty; node.Nodes.Clear(); node.Text = GetObjectName(obj); node.Tag = obj; node.ImageIndex = (int)TreeViewIcons.other; node.SelectedImageIndex = (int)TreeViewIcons.other; node.Nodes.AddRange(parameterNodes); node.Nodes.AddRange(resultNodes); } void AddColumns(TreeNode node, ColumnInfoCollection cols) { node.Nodes.Clear(); foreach (IColumnInfo c in cols) { TreeNode n = new TreeNode(c.ColumnName); n.Tag = c; n.SelectedImageIndex = (int)TreeViewIcons.field; n.ImageIndex = (int)TreeViewIcons.field; if (c.IsPrimaryKey) { n.SelectedImageIndex = (int)TreeViewIcons.goldkey; n.ImageIndex = (int)TreeViewIcons.goldkey; } node.Nodes.Add(n); } } private string GetObjectName(IDataBaseObject obj) { if (obj.ObjectCatalog != null && obj.ObjectSchema != null) return obj.ObjectSchema + "." + obj.ObjectName; return obj.ObjectName; } private enum TreeViewIcons { db = 0, dbx = 1, fldr = 2, table = 3, view = 4, sp = 5, resultset = 6, other = 7, goldkey = 8, silverkey = 9, field = 10 } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using gciv = Google.Cloud.Iam.V1; using gcscv = Google.Cloud.Spanner.Common.V1; using lro = Google.LongRunning; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Spanner.Admin.Database.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedDatabaseAdminClientTest { [xunit::FactAttribute] public void GetDatabaseRequestObject() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDatabaseRequest request = new GetDatabaseRequest { DatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; Database expectedResponse = new Database { DatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), State = Database.Types.State.Ready, CreateTime = new wkt::Timestamp(), RestoreInfo = new RestoreInfo(), EncryptionConfig = new EncryptionConfig(), VersionRetentionPeriod = "version_retention_periodbbfc8bf7", EarliestVersionTime = new wkt::Timestamp(), EncryptionInfo = { new EncryptionInfo(), }, DefaultLeader = "default_leader08a48e00", DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.GetDatabase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Database response = client.GetDatabase(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDatabaseRequestObjectAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDatabaseRequest request = new GetDatabaseRequest { DatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; Database expectedResponse = new Database { DatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), State = Database.Types.State.Ready, CreateTime = new wkt::Timestamp(), RestoreInfo = new RestoreInfo(), EncryptionConfig = new EncryptionConfig(), VersionRetentionPeriod = "version_retention_periodbbfc8bf7", EarliestVersionTime = new wkt::Timestamp(), EncryptionInfo = { new EncryptionInfo(), }, DefaultLeader = "default_leader08a48e00", DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.GetDatabaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Database>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Database responseCallSettings = await client.GetDatabaseAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Database responseCancellationToken = await client.GetDatabaseAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDatabase() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDatabaseRequest request = new GetDatabaseRequest { DatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; Database expectedResponse = new Database { DatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), State = Database.Types.State.Ready, CreateTime = new wkt::Timestamp(), RestoreInfo = new RestoreInfo(), EncryptionConfig = new EncryptionConfig(), VersionRetentionPeriod = "version_retention_periodbbfc8bf7", EarliestVersionTime = new wkt::Timestamp(), EncryptionInfo = { new EncryptionInfo(), }, DefaultLeader = "default_leader08a48e00", DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.GetDatabase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Database response = client.GetDatabase(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDatabaseAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDatabaseRequest request = new GetDatabaseRequest { DatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; Database expectedResponse = new Database { DatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), State = Database.Types.State.Ready, CreateTime = new wkt::Timestamp(), RestoreInfo = new RestoreInfo(), EncryptionConfig = new EncryptionConfig(), VersionRetentionPeriod = "version_retention_periodbbfc8bf7", EarliestVersionTime = new wkt::Timestamp(), EncryptionInfo = { new EncryptionInfo(), }, DefaultLeader = "default_leader08a48e00", DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.GetDatabaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Database>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Database responseCallSettings = await client.GetDatabaseAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Database responseCancellationToken = await client.GetDatabaseAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDatabaseResourceNames() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDatabaseRequest request = new GetDatabaseRequest { DatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; Database expectedResponse = new Database { DatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), State = Database.Types.State.Ready, CreateTime = new wkt::Timestamp(), RestoreInfo = new RestoreInfo(), EncryptionConfig = new EncryptionConfig(), VersionRetentionPeriod = "version_retention_periodbbfc8bf7", EarliestVersionTime = new wkt::Timestamp(), EncryptionInfo = { new EncryptionInfo(), }, DefaultLeader = "default_leader08a48e00", DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.GetDatabase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Database response = client.GetDatabase(request.DatabaseName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDatabaseResourceNamesAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDatabaseRequest request = new GetDatabaseRequest { DatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; Database expectedResponse = new Database { DatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), State = Database.Types.State.Ready, CreateTime = new wkt::Timestamp(), RestoreInfo = new RestoreInfo(), EncryptionConfig = new EncryptionConfig(), VersionRetentionPeriod = "version_retention_periodbbfc8bf7", EarliestVersionTime = new wkt::Timestamp(), EncryptionInfo = { new EncryptionInfo(), }, DefaultLeader = "default_leader08a48e00", DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.GetDatabaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Database>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Database responseCallSettings = await client.GetDatabaseAsync(request.DatabaseName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Database responseCancellationToken = await client.GetDatabaseAsync(request.DatabaseName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DropDatabaseRequestObject() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DropDatabaseRequest request = new DropDatabaseRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DropDatabase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); client.DropDatabase(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DropDatabaseRequestObjectAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DropDatabaseRequest request = new DropDatabaseRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DropDatabaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); await client.DropDatabaseAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DropDatabaseAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DropDatabase() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DropDatabaseRequest request = new DropDatabaseRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DropDatabase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); client.DropDatabase(request.Database); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DropDatabaseAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DropDatabaseRequest request = new DropDatabaseRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DropDatabaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); await client.DropDatabaseAsync(request.Database, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DropDatabaseAsync(request.Database, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DropDatabaseResourceNames() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DropDatabaseRequest request = new DropDatabaseRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DropDatabase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); client.DropDatabase(request.DatabaseAsDatabaseName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DropDatabaseResourceNamesAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DropDatabaseRequest request = new DropDatabaseRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DropDatabaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); await client.DropDatabaseAsync(request.DatabaseAsDatabaseName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DropDatabaseAsync(request.DatabaseAsDatabaseName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDatabaseDdlRequestObject() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDatabaseDdlRequest request = new GetDatabaseDdlRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; GetDatabaseDdlResponse expectedResponse = new GetDatabaseDdlResponse { Statements = { "statementsbaee2cf5", }, }; mockGrpcClient.Setup(x => x.GetDatabaseDdl(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); GetDatabaseDdlResponse response = client.GetDatabaseDdl(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDatabaseDdlRequestObjectAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDatabaseDdlRequest request = new GetDatabaseDdlRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; GetDatabaseDdlResponse expectedResponse = new GetDatabaseDdlResponse { Statements = { "statementsbaee2cf5", }, }; mockGrpcClient.Setup(x => x.GetDatabaseDdlAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GetDatabaseDdlResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); GetDatabaseDdlResponse responseCallSettings = await client.GetDatabaseDdlAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GetDatabaseDdlResponse responseCancellationToken = await client.GetDatabaseDdlAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDatabaseDdl() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDatabaseDdlRequest request = new GetDatabaseDdlRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; GetDatabaseDdlResponse expectedResponse = new GetDatabaseDdlResponse { Statements = { "statementsbaee2cf5", }, }; mockGrpcClient.Setup(x => x.GetDatabaseDdl(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); GetDatabaseDdlResponse response = client.GetDatabaseDdl(request.Database); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDatabaseDdlAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDatabaseDdlRequest request = new GetDatabaseDdlRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; GetDatabaseDdlResponse expectedResponse = new GetDatabaseDdlResponse { Statements = { "statementsbaee2cf5", }, }; mockGrpcClient.Setup(x => x.GetDatabaseDdlAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GetDatabaseDdlResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); GetDatabaseDdlResponse responseCallSettings = await client.GetDatabaseDdlAsync(request.Database, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GetDatabaseDdlResponse responseCancellationToken = await client.GetDatabaseDdlAsync(request.Database, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDatabaseDdlResourceNames() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDatabaseDdlRequest request = new GetDatabaseDdlRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; GetDatabaseDdlResponse expectedResponse = new GetDatabaseDdlResponse { Statements = { "statementsbaee2cf5", }, }; mockGrpcClient.Setup(x => x.GetDatabaseDdl(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); GetDatabaseDdlResponse response = client.GetDatabaseDdl(request.DatabaseAsDatabaseName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDatabaseDdlResourceNamesAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDatabaseDdlRequest request = new GetDatabaseDdlRequest { DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; GetDatabaseDdlResponse expectedResponse = new GetDatabaseDdlResponse { Statements = { "statementsbaee2cf5", }, }; mockGrpcClient.Setup(x => x.GetDatabaseDdlAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GetDatabaseDdlResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); GetDatabaseDdlResponse responseCallSettings = await client.GetDatabaseDdlAsync(request.DatabaseAsDatabaseName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GetDatabaseDdlResponse responseCancellationToken = await client.GetDatabaseDdlAsync(request.DatabaseAsDatabaseName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyRequestObject() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyRequestObjectAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicy() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request.Resource, request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.Resource, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Resource, request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyResourceNames() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request.ResourceAsResourceName, request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyResourceNamesAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyRequestObject() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Options = new gciv::GetPolicyOptions(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyRequestObjectAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Options = new gciv::GetPolicyOptions(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicy() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request.Resource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Resource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyResourceNames() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request.ResourceAsResourceName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyResourceNamesAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.ResourceAsResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.ResourceAsResourceName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.Resource, request.Permissions); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsResourceNames() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.ResourceAsResourceName, request.Permissions); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsResourceNamesAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetBackupRequestObject() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetBackupRequest request = new GetBackupRequest { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), ExpireTime = new wkt::Timestamp(), CreateTime = new wkt::Timestamp(), SizeBytes = 4628423819757039038L, State = Backup.Types.State.Unspecified, ReferencingDatabasesAsDatabaseNames = { gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }, EncryptionInfo = new EncryptionInfo(), VersionTime = new wkt::Timestamp(), DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.GetBackup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Backup response = client.GetBackup(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetBackupRequestObjectAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetBackupRequest request = new GetBackupRequest { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), ExpireTime = new wkt::Timestamp(), CreateTime = new wkt::Timestamp(), SizeBytes = 4628423819757039038L, State = Backup.Types.State.Unspecified, ReferencingDatabasesAsDatabaseNames = { gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }, EncryptionInfo = new EncryptionInfo(), VersionTime = new wkt::Timestamp(), DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.GetBackupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Backup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Backup responseCallSettings = await client.GetBackupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Backup responseCancellationToken = await client.GetBackupAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetBackup() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetBackupRequest request = new GetBackupRequest { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), ExpireTime = new wkt::Timestamp(), CreateTime = new wkt::Timestamp(), SizeBytes = 4628423819757039038L, State = Backup.Types.State.Unspecified, ReferencingDatabasesAsDatabaseNames = { gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }, EncryptionInfo = new EncryptionInfo(), VersionTime = new wkt::Timestamp(), DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.GetBackup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Backup response = client.GetBackup(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetBackupAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetBackupRequest request = new GetBackupRequest { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), ExpireTime = new wkt::Timestamp(), CreateTime = new wkt::Timestamp(), SizeBytes = 4628423819757039038L, State = Backup.Types.State.Unspecified, ReferencingDatabasesAsDatabaseNames = { gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }, EncryptionInfo = new EncryptionInfo(), VersionTime = new wkt::Timestamp(), DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.GetBackupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Backup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Backup responseCallSettings = await client.GetBackupAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Backup responseCancellationToken = await client.GetBackupAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetBackupResourceNames() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetBackupRequest request = new GetBackupRequest { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), ExpireTime = new wkt::Timestamp(), CreateTime = new wkt::Timestamp(), SizeBytes = 4628423819757039038L, State = Backup.Types.State.Unspecified, ReferencingDatabasesAsDatabaseNames = { gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }, EncryptionInfo = new EncryptionInfo(), VersionTime = new wkt::Timestamp(), DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.GetBackup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Backup response = client.GetBackup(request.BackupName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetBackupResourceNamesAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetBackupRequest request = new GetBackupRequest { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), ExpireTime = new wkt::Timestamp(), CreateTime = new wkt::Timestamp(), SizeBytes = 4628423819757039038L, State = Backup.Types.State.Unspecified, ReferencingDatabasesAsDatabaseNames = { gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }, EncryptionInfo = new EncryptionInfo(), VersionTime = new wkt::Timestamp(), DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.GetBackupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Backup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Backup responseCallSettings = await client.GetBackupAsync(request.BackupName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Backup responseCancellationToken = await client.GetBackupAsync(request.BackupName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateBackupRequestObject() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateBackupRequest request = new UpdateBackupRequest { Backup = new Backup(), UpdateMask = new wkt::FieldMask(), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), ExpireTime = new wkt::Timestamp(), CreateTime = new wkt::Timestamp(), SizeBytes = 4628423819757039038L, State = Backup.Types.State.Unspecified, ReferencingDatabasesAsDatabaseNames = { gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }, EncryptionInfo = new EncryptionInfo(), VersionTime = new wkt::Timestamp(), DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.UpdateBackup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Backup response = client.UpdateBackup(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateBackupRequestObjectAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateBackupRequest request = new UpdateBackupRequest { Backup = new Backup(), UpdateMask = new wkt::FieldMask(), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), ExpireTime = new wkt::Timestamp(), CreateTime = new wkt::Timestamp(), SizeBytes = 4628423819757039038L, State = Backup.Types.State.Unspecified, ReferencingDatabasesAsDatabaseNames = { gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }, EncryptionInfo = new EncryptionInfo(), VersionTime = new wkt::Timestamp(), DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.UpdateBackupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Backup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Backup responseCallSettings = await client.UpdateBackupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Backup responseCancellationToken = await client.UpdateBackupAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateBackup() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateBackupRequest request = new UpdateBackupRequest { Backup = new Backup(), UpdateMask = new wkt::FieldMask(), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), ExpireTime = new wkt::Timestamp(), CreateTime = new wkt::Timestamp(), SizeBytes = 4628423819757039038L, State = Backup.Types.State.Unspecified, ReferencingDatabasesAsDatabaseNames = { gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }, EncryptionInfo = new EncryptionInfo(), VersionTime = new wkt::Timestamp(), DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.UpdateBackup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Backup response = client.UpdateBackup(request.Backup, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateBackupAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateBackupRequest request = new UpdateBackupRequest { Backup = new Backup(), UpdateMask = new wkt::FieldMask(), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), DatabaseAsDatabaseName = gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), ExpireTime = new wkt::Timestamp(), CreateTime = new wkt::Timestamp(), SizeBytes = 4628423819757039038L, State = Backup.Types.State.Unspecified, ReferencingDatabasesAsDatabaseNames = { gcscv::DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }, EncryptionInfo = new EncryptionInfo(), VersionTime = new wkt::Timestamp(), DatabaseDialect = DatabaseDialect.GoogleStandardSql, }; mockGrpcClient.Setup(x => x.UpdateBackupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Backup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); Backup responseCallSettings = await client.UpdateBackupAsync(request.Backup, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Backup responseCancellationToken = await client.UpdateBackupAsync(request.Backup, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteBackupRequestObject() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteBackupRequest request = new DeleteBackupRequest { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteBackup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); client.DeleteBackup(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteBackupRequestObjectAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteBackupRequest request = new DeleteBackupRequest { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteBackupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); await client.DeleteBackupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteBackupAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteBackup() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteBackupRequest request = new DeleteBackupRequest { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteBackup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); client.DeleteBackup(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteBackupAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteBackupRequest request = new DeleteBackupRequest { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteBackupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); await client.DeleteBackupAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteBackupAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteBackupResourceNames() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteBackupRequest request = new DeleteBackupRequest { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteBackup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); client.DeleteBackup(request.BackupName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteBackupResourceNamesAsync() { moq::Mock<DatabaseAdmin.DatabaseAdminClient> mockGrpcClient = new moq::Mock<DatabaseAdmin.DatabaseAdminClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteBackupRequest request = new DeleteBackupRequest { BackupName = BackupName.FromProjectInstanceBackup("[PROJECT]", "[INSTANCE]", "[BACKUP]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteBackupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DatabaseAdminClient client = new DatabaseAdminClientImpl(mockGrpcClient.Object, null); await client.DeleteBackupAsync(request.BackupName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteBackupAsync(request.BackupName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
// The MIT License (MIT) // // Copyright (c) 2014-2016, 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 SafetySharp.Runtime { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using Modeling; using Serialization; using Utilities; /// <summary> /// Represents a stack that is used to resolve nondeterministic choices during state space enumeration. /// </summary> [NonSerializable] internal sealed class ChoiceResolver : DisposableObject { /// <summary> /// The number of nondeterministic choices that can be stored initially. /// </summary> private const int InitialCapacity = 64; /// <summary> /// The stack that indicates the chosen values for the current path. /// </summary> private readonly ChoiceStack _chosenValues = new ChoiceStack(InitialCapacity); /// <summary> /// The stack that stores the number of possible values of all encountered choices along the current path. /// </summary> private readonly ChoiceStack _valueCount = new ChoiceStack(InitialCapacity); /// <summary> /// The number of choices that have been encountered for the current path. /// </summary> private int _choiceIndex = -1; /// <summary> /// Indicates whether the next path is the first one of the current state. /// </summary> private bool _firstPath; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="objectTable">The object table containing all objects that potentially require access to the choice resolver.</param> public ChoiceResolver(ObjectTable objectTable) { foreach (var obj in objectTable.OfType<Choice>()) obj.Resolver = this; } /// <summary> /// Gets the index of the last choice that has been made. /// </summary> // ReSharper disable once ConvertToAutoPropertyWithPrivateSetter internal int LastChoiceIndex => _choiceIndex; /// <summary> /// Prepares the resolver for resolving the choices of the next state. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void PrepareNextState() { _firstPath = true; } /// <summary> /// Prepares the resolver for the next path. Returns <c>true</c> to indicate that all paths have been enumerated. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool PrepareNextPath() { if (_choiceIndex != _valueCount.Count - 1) throw new NondeterminismException(); // Reset the choice counter as each path starts from the beginning _choiceIndex = -1; // If this is the first path of the state, we definitely have to enumerate it if (_firstPath) { _firstPath = false; return true; } // Let's go through the entire stack to determine what we have to do next while (_chosenValues.Count > 0) { // Remove the value we've chosen last -- we've already chosen it, so we're done with it var chosenValue = _chosenValues.Remove(); // If we have at least one other value to choose, let's do that next if (_valueCount.Peek() > chosenValue + 1) { _chosenValues.Push(chosenValue + 1); return true; } // Otherwise, we've chosen all values of the last choice, so we're done with it _valueCount.Remove(); } // If we reach this point, we know that we've chosen all values of all choices, so there are no further paths return false; } /// <summary> /// Handles a nondeterministic choice that chooses between <paramref name="valueCount" /> values. /// </summary> /// <param name="valueCount">The number of values that can be chosen.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public int HandleChoice(int valueCount) { ++_choiceIndex; // If we have a preselected value that we should choose for the current path, return it if (_choiceIndex < _chosenValues.Count) return _chosenValues[_choiceIndex]; // We haven't encountered this choice before; store the value count and return the first value _valueCount.Push(valueCount); _chosenValues.Push(0); return 0; } /// <summary> /// Undoes the choice identified by the <paramref name="choiceIndex" />. /// </summary> /// <param name="choiceIndex">The index of the choice that should be undone.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void Undo(int choiceIndex) { // We disable a choice by setting the number of values that we have yet to choose to 0, effectively // turning the choice into a deterministic selection of the value at index 0 _valueCount[choiceIndex] = 0; } /// <summary> /// Sets the choices that should be made during the next step. /// </summary> /// <param name="choices">The choices that should be made.</param> internal void SetChoices(int[] choices) { Requires.NotNull(choices, nameof(choices)); foreach (var choice in choices) { _chosenValues.Push(choice); _valueCount.Push(0); } } /// <summary> /// Clears all choice information. /// </summary> internal void Clear() { _chosenValues.Clear(); _valueCount.Clear(); _choiceIndex = -1; } /// <summary> /// Gets the choices that were made to generate the last transitions. /// </summary> internal IEnumerable<int> GetChoices() { for (var i = 0; i < _chosenValues.Count; ++i) yield return _chosenValues[i]; } /// <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) { if (!disposing) return; _chosenValues.SafeDispose(); _valueCount.SafeDispose(); } } }
//------------------------------------------------------------------------------ // <copyright file="BulletedList.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Globalization; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Drawing.Design; using System.Web.Util; /// <devdoc> /// <para>Generates a bulleted list.</para> /// </devdoc> [DefaultProperty("BulletStyle")] [DefaultEvent("Click")] [Designer("System.Web.UI.Design.WebControls.BulletedListDesigner, " + AssemblyRef.SystemDesign)] [SupportsEventValidation] public class BulletedList : ListControl, IPostBackEventHandler { private static readonly object EventClick = new object(); private bool _cachedIsEnabled; private int _firstItem; private int _itemCount; /// <devdoc></devdoc> public BulletedList() { _firstItem = 0; _itemCount = -1; } /// <devdoc> /// <para>Gets the value of the base classes AutoPostBack propert. /// AutoPostBack is not applicable to the bulleted list control</para> /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] public override bool AutoPostBack { get { return base.AutoPostBack; } set { throw new NotSupportedException(SR.GetString(SR.Property_Set_Not_Supported, "AutoPostBack", this.GetType().ToString())); } } /// <devdoc> /// <para>Gets or sets a value indicating the style of bullet to be /// applied to the list.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(BulletStyle.NotSet), WebSysDescription(SR.BulletedList_BulletStyle) ] public virtual BulletStyle BulletStyle { get { object o = ViewState["BulletStyle"]; return((o == null) ? BulletStyle.NotSet : (BulletStyle)o); } set { if (value < BulletStyle.NotSet || value > BulletStyle.CustomImage) { throw new ArgumentOutOfRangeException("value"); } ViewState["BulletStyle"] = value; } } /// <devdoc> /// <para>Gets or sets the source of the image used for an /// Image styled bulleted list.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), Editor("System.Web.UI.Design.ImageUrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), UrlProperty(), WebSysDescription(SR.BulletedList_BulletImageUrl) ] public virtual string BulletImageUrl { get { object o = ViewState["BulletImageUrl"]; return((o == null) ? string.Empty : (string)o); } set { ViewState["BulletImageUrl"] = value; } } /// <devdoc> /// <para>Gets the EmptyControlCollection.</para> /// </devdoc> public override ControlCollection Controls { get { return new EmptyControlCollection(this); } } /// <devdoc> /// <para>Gets or sets the display mode of the bulleted list.</para> /// </devdoc> [ WebCategory("Behavior"), DefaultValue(BulletedListDisplayMode.Text), WebSysDescription(SR.BulletedList_BulletedListDisplayMode) // ] public virtual BulletedListDisplayMode DisplayMode { get { object o = ViewState["DisplayMode"]; return ((o == null) ? BulletedListDisplayMode.Text : (BulletedListDisplayMode)o); } set { if (value < BulletedListDisplayMode.Text || value > BulletedListDisplayMode.LinkButton) { throw new ArgumentOutOfRangeException("value"); } ViewState["DisplayMode"] = value; } } /// <devdoc> /// <para>Gets or sets the value at which an ordered list should /// begin its numbering.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(1), WebSysDescription(SR.BulletedList_FirstBulletNumber) ] public virtual int FirstBulletNumber { get { object o = ViewState["FirstBulletNumber"]; return((o == null) ? 1 : (int)o); } set { ViewState["FirstBulletNumber"] = value; } } /// <summary> /// <para>Indicates whether the control will be rendered when the data source has no items.</para> /// </summary> [DefaultValue(false)] [Themeable(true)] [WebCategory("Behavior")] [WebSysDescription(SR.ListControl_RenderWhenDataEmpty)] public virtual bool RenderWhenDataEmpty { get { object o = ViewState["RenderWhenDataEmpty"]; return ((o == null) ? false : (bool)o); } set { ViewState["RenderWhenDataEmpty"] = value; } } /// <devdoc> /// <para>Gets the value of selected index. Not applicable to the /// bulleted list control.</para> /// </devdoc> [ Bindable(false), EditorBrowsable(EditorBrowsableState.Never) ] public override int SelectedIndex { get { return base.SelectedIndex; } set { throw new NotSupportedException(SR.GetString(SR.BulletedList_SelectionNotSupported)); } } /// <devdoc> /// <para>Gets the selected item. Not applicable to the /// bulleted list control.</para> /// </devdoc> [ EditorBrowsable(EditorBrowsableState.Never) ] public override ListItem SelectedItem { get { return base.SelectedItem; } } [ Bindable(false), EditorBrowsable(EditorBrowsableState.Never) ] public override string SelectedValue { get { return base.SelectedValue; } set { throw new NotSupportedException(SR.GetString(SR.BulletedList_SelectionNotSupported)); } } /// <devdoc> /// <para>Gets the HtmlTextWriterTag value that corresponds /// to the particular bulleted list.</para> /// </devdoc> protected override HtmlTextWriterTag TagKey { get { return TagKeyInternal; } } internal HtmlTextWriterTag TagKeyInternal { get { switch (BulletStyle) { // Ordered Lists case BulletStyle.LowerAlpha: case BulletStyle.UpperAlpha: case BulletStyle.LowerRoman: case BulletStyle.UpperRoman: case BulletStyle.Numbered: return HtmlTextWriterTag.Ol; // Unordered Lists case BulletStyle.Square: case BulletStyle.Circle: case BulletStyle.Disc: return HtmlTextWriterTag.Ul; // Image Lists case BulletStyle.CustomImage: return HtmlTextWriterTag.Ul; // Not Set case BulletStyle.NotSet: // NotSet is specified as an unordered list. return HtmlTextWriterTag.Ul; default: Debug.Assert(false, "Invalid BulletStyle"); return HtmlTextWriterTag.Ol; } } } /// <devdoc> /// <para>Gets or sets the Target window when the /// list is displayed as Hyperlinks.</para> /// </devdoc> [ WebCategory("Behavior"), DefaultValue(""), WebSysDescription(SR.BulletedList_Target), TypeConverter(typeof(TargetConverter)) ] public virtual string Target { get { object o = ViewState["Target"]; return ((o == null) ? string.Empty : (string)o); } set { ViewState["Target"] = value; } } [ EditorBrowsable(EditorBrowsableState.Never) ] public override string Text { get { return base.Text; } set { throw new NotSupportedException(SR.GetString(SR.BulletedList_TextNotSupported)); } } /// <devdoc> /// <para>Occurs when the a link button is clicked.</para> /// </devdoc> [ WebCategory("Action"), WebSysDescription(SR.BulletedList_OnClick) ] public event BulletedListEventHandler Click { add { Events.AddHandler(EventClick, value); } remove { Events.RemoveHandler(EventClick, value); } } /// <devdoc> /// <para>Adds HTML attributes that need to be rendered.</para> /// </devdoc> protected override void AddAttributesToRender(HtmlTextWriter writer) { bool addBulletNumber = false; switch (BulletStyle) { case BulletStyle.NotSet: break; case BulletStyle.Numbered: writer.AddStyleAttribute(HtmlTextWriterStyle.ListStyleType, "decimal"); addBulletNumber = true; break; case BulletStyle.LowerAlpha: writer.AddStyleAttribute(HtmlTextWriterStyle.ListStyleType, "lower-alpha"); addBulletNumber = true; break; case BulletStyle.UpperAlpha: writer.AddStyleAttribute(HtmlTextWriterStyle.ListStyleType, "upper-alpha"); addBulletNumber = true; break; case BulletStyle.LowerRoman: writer.AddStyleAttribute(HtmlTextWriterStyle.ListStyleType, "lower-roman"); addBulletNumber = true; break; case BulletStyle.UpperRoman: writer.AddStyleAttribute(HtmlTextWriterStyle.ListStyleType, "upper-roman"); addBulletNumber = true; break; case BulletStyle.Disc: writer.AddStyleAttribute(HtmlTextWriterStyle.ListStyleType, "disc"); break; case BulletStyle.Circle: writer.AddStyleAttribute(HtmlTextWriterStyle.ListStyleType, "circle"); break; case BulletStyle.Square: writer.AddStyleAttribute(HtmlTextWriterStyle.ListStyleType, "square"); break; case BulletStyle.CustomImage: String url = ResolveClientUrl(BulletImageUrl); writer.AddStyleAttribute(HtmlTextWriterStyle.ListStyleImage, "url(" + HttpUtility.UrlPathEncode(url) + ")"); break; default: Debug.Assert(false, "Invalid BulletStyle"); break; } int firstBulletNumber = FirstBulletNumber; if ((addBulletNumber == true) && (firstBulletNumber != 1)) { writer.AddAttribute("start", firstBulletNumber.ToString(CultureInfo.InvariantCulture)); } base.AddAttributesToRender(writer); } private string GetPostBackEventReference(string eventArgument) { if (CausesValidation && Page.GetValidators(ValidationGroup).Count > 0) { return ClientScriptManager.JscriptPrefix + Util.GetClientValidatedPostback(this, ValidationGroup, eventArgument); } else { return Page.ClientScript.GetPostBackClientHyperlink(this, eventArgument, true); } } /// <devdoc> /// <para>Raises the Click event.</para> /// </devdoc> protected virtual void OnClick(BulletedListEventArgs e) { BulletedListEventHandler onClickHandler = (BulletedListEventHandler)Events[EventClick]; if (onClickHandler != null) onClickHandler(this, e); } /// <devdoc> /// <para>Writes the text of each bullet according to the list's display mode.</para> /// </devdoc> protected virtual void RenderBulletText(ListItem item, int index, HtmlTextWriter writer) { switch (DisplayMode) { case BulletedListDisplayMode.Text: if (!item.Enabled) { RenderDisabledAttributeHelper(writer, false); writer.RenderBeginTag(HtmlTextWriterTag.Span); } HttpUtility.HtmlEncode(item.Text, writer); if (!item.Enabled) { writer.RenderEndTag(); } break; case BulletedListDisplayMode.HyperLink: if (_cachedIsEnabled && item.Enabled) { writer.AddAttribute(HtmlTextWriterAttribute.Href, ResolveClientUrl(item.Value)); string target = Target; if (!String.IsNullOrEmpty(target)) { writer.AddAttribute(HtmlTextWriterAttribute.Target, Target); } } else { RenderDisabledAttributeHelper(writer, item.Enabled); } RenderAccessKey(writer, AccessKey); writer.RenderBeginTag(HtmlTextWriterTag.A); HttpUtility.HtmlEncode(item.Text, writer); writer.RenderEndTag(); break; case BulletedListDisplayMode.LinkButton: if (_cachedIsEnabled && item.Enabled) { writer.AddAttribute(HtmlTextWriterAttribute.Href, GetPostBackEventReference(index.ToString(CultureInfo.InvariantCulture))); } else { RenderDisabledAttributeHelper(writer, item.Enabled); } RenderAccessKey(writer, AccessKey); writer.RenderBeginTag(HtmlTextWriterTag.A); HttpUtility.HtmlEncode(item.Text, writer); writer.RenderEndTag(); break; default: Debug.Assert(false, "Invalid BulletedListDisplayMode"); break; } } private void RenderDisabledAttributeHelper(HtmlTextWriter writer, bool isItemEnabled) { if (SupportsDisabledAttribute) { writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled"); } else if (!isItemEnabled && !String.IsNullOrEmpty(DisabledCssClass)) { writer.AddAttribute(HtmlTextWriterAttribute.Class, DisabledCssClass); } } internal void RenderAccessKey(HtmlTextWriter writer, string AccessKey) { string s = AccessKey; if (s.Length > 0) { writer.AddAttribute(HtmlTextWriterAttribute.Accesskey, s); } } protected internal override void Render(HtmlTextWriter writer) { // Don't render anything if the control is empty (unless the developer opts in) if (Items.Count == 0 && !RenderWhenDataEmpty) { return; } base.Render(writer); } /// <devdoc> /// <para>Renders the ListItems as bullets in the bulleted list.</para> /// </devdoc> protected internal override void RenderContents(HtmlTextWriter writer) { _cachedIsEnabled = IsEnabled; if (_itemCount == -1) { for (int i = 0; i < Items.Count; i++) { Items[i].RenderAttributes(writer); writer.RenderBeginTag(HtmlTextWriterTag.Li); RenderBulletText(Items[i], i, writer); writer.RenderEndTag(); } } else { for (int i = _firstItem; i < _firstItem + _itemCount; i++) { Items[i].RenderAttributes(writer); writer.RenderBeginTag(HtmlTextWriterTag.Li); RenderBulletText(Items[i], i, writer); writer.RenderEndTag(); } } } protected virtual void RaisePostBackEvent(string eventArgument) { ValidateEvent(this.UniqueID, eventArgument); if (CausesValidation) { Page.Validate(ValidationGroup); } OnClick(new BulletedListEventArgs(Int32.Parse(eventArgument, CultureInfo.InvariantCulture))); } void IPostBackEventHandler.RaisePostBackEvent(string eventArgument) { RaisePostBackEvent(eventArgument); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.Testing; using Xunit; namespace Microsoft.AspNetCore.Mvc.FunctionalTests { public class HtmlGenerationTest : IClassFixture<MvcTestFixture<HtmlGenerationWebSite.Startup>>, IClassFixture<MvcEncodedTestFixture<HtmlGenerationWebSite.Startup>> { private static readonly Assembly _resourcesAssembly = typeof(HtmlGenerationTest).GetTypeInfo().Assembly; public HtmlGenerationTest( MvcTestFixture<HtmlGenerationWebSite.Startup> fixture, MvcEncodedTestFixture<HtmlGenerationWebSite.Startup> encodedFixture) { Factory = fixture.Factories.FirstOrDefault() ?? fixture.WithWebHostBuilder(ConfigureWebHostBuilder); Client = fixture.CreateDefaultClient(); EncodedClient = encodedFixture.CreateDefaultClient(); } private static void ConfigureWebHostBuilder(IWebHostBuilder builder) => builder.UseStartup<HtmlGenerationWebSite.Startup>(); public HttpClient Client { get; } public HttpClient EncodedClient { get; } public WebApplicationFactory<HtmlGenerationWebSite.Startup> Factory { get; } public static TheoryData<string, string> WebPagesData { get { var data = new TheoryData<string, string> { { "Customer", "/Customer/HtmlGeneration_Customer" }, { "Index", null }, { "Product", null }, { "Link", null }, { "Script", null }, // Testing attribute values with boolean and null values { "AttributesWithBooleanValues", null }, // Testing SelectTagHelper with Html.BeginForm { "CreateWarehouse", "/HtmlGeneration_Home/CreateWarehouse" }, // Testing the HTML helpers with FormTagHelper { "EditWarehouse", null }, { "Form", "/HtmlGeneration_Home/Form" }, // Testing MVC tag helpers invoked in the editor templates from HTML helpers { "EmployeeList", "/HtmlGeneration_Home/EmployeeList" }, // Testing the EnvironmentTagHelper { "Environment", null }, // Testing InputTagHelper with File { "Input", null }, // Test ability to generate nearly identical HTML with MVC tag and HTML helpers. // Only attribute order should differ. { "Order", "/HtmlGeneration_Order/Submit" }, { "OrderUsingHtmlHelpers", "/HtmlGeneration_Order/Submit" }, // Testing PartialTagHelper { "PartialTagHelperWithoutModel", null }, { "Warehouse", null }, // Testing InputTagHelpers invoked in the partial views { "ProductList", "/HtmlGeneration_Product" }, { "ProductListUsingTagHelpers", "/HtmlGeneration_Product" }, { "ProductListUsingTagHelpersWithNullModel", "/HtmlGeneration_Product" }, }; return data; } } [Fact] public async Task EnumValues_SerializeCorrectly() { // Arrange & Act var response = await Client.GetStringAsync("http://localhost/HtmlGeneration_Home/Enum"); // Assert Assert.Equal($"Vrijdag{Environment.NewLine}Month: FirstOne", response, ignoreLineEndingDifferences: true); } [Theory(Skip = "https://github.com/dotnet/aspnetcore/issues/34599")] [MemberData(nameof(WebPagesData))] public async Task HtmlGenerationWebSite_GeneratesExpectedResults(string action, string antiforgeryPath) { // Arrange var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home." + action + ".html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act // The host is not important as everything runs in memory and tests are isolated from each other. var response = await Client.GetAsync("http://localhost/HtmlGeneration_Home/" + action); var responseContent = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedMediaType, response.Content.Headers.ContentType); responseContent = responseContent.Trim(); if (antiforgeryPath == null) { ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); Assert.Equal(expectedContent.Trim(), responseContent, ignoreLineEndingDifferences: true); } else { var forgeryToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseContent, antiforgeryPath); if (ResourceFile.GenerateBaselines) { // Reverse usual substitution and insert a format item into the new file content. responseContent = responseContent.Replace(forgeryToken, "{0}"); ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); } else { expectedContent = string.Format(CultureInfo.InvariantCulture, expectedContent, forgeryToken); Assert.Equal(expectedContent.Trim(), responseContent, ignoreLineEndingDifferences: true); } } } [Fact(Skip = "https://github.com/dotnet/aspnetcore/issues/34599")] public async Task HtmlGenerationWebSite_GeneratesExpectedResults_WithImageData() { await HtmlGenerationWebSite_GeneratesExpectedResults("Image", antiforgeryPath: null); } [Fact] public async Task HtmlGenerationWebSite_LinkGeneration_With21CompatibilityBehavior() { // Arrange var client = Factory .WithWebHostBuilder(builder => builder.UseStartup<HtmlGenerationWebSite.StartupWithoutEndpointRouting>()) .CreateDefaultClient(); var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home.Index21Compat.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act // The host is not important as everything runs in memory and tests are isolated from each other. var response = await client.GetAsync("http://localhost/HtmlGeneration_Home/"); var responseContent = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedMediaType, response.Content.Headers.ContentType); responseContent = responseContent.Trim(); ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent); } public static TheoryData<string, string> EncodedPagesData { get { return new TheoryData<string, string> { { "AttributesWithBooleanValues", null }, { "EditWarehouse", null }, { "Index", null }, { "Order", "/HtmlGeneration_Order/Submit" }, { "OrderUsingHtmlHelpers", "/HtmlGeneration_Order/Submit" }, { "Product", null }, }; } } [Theory] [MemberData(nameof(EncodedPagesData))] public async Task HtmlGenerationWebSite_GenerateEncodedResults(string action, string antiforgeryPath) { // Arrange var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home." + action + ".Encoded.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act // The host is not important as everything runs in memory and tests are isolated from each other. var response = await EncodedClient.GetAsync("http://localhost/HtmlGeneration_Home/" + action); var responseContent = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedMediaType, response.Content.Headers.ContentType); responseContent = responseContent.Trim(); if (antiforgeryPath == null) { ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent); } else { ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent, token: AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseContent, antiforgeryPath)); } } [ConditionalTheory] [InlineData("Link", null)] [InlineData("Script", null)] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/10423")] public Task HtmlGenerationWebSite_GenerateEncodedResultsNotReadyForHelix(string action, string antiforgeryPath) => HtmlGenerationWebSite_GenerateEncodedResults(action, antiforgeryPath); // Testing how ModelMetadata is handled as ViewDataDictionary instances are created. [Theory] [InlineData("AtViewModel")] [InlineData("NullViewModel")] [InlineData("ViewModel")] public async Task CheckViewData_GeneratesExpectedResults(string action) { // Arrange var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/HtmlGenerationWebSite.CheckViewData." + action + ".html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act var response = await Client.GetAsync("http://localhost/CheckViewData/" + action); var responseContent = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedMediaType, response.Content.Headers.ContentType); responseContent = responseContent.Trim(); ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent); } [Fact] public async Task ValidationTagHelpers_GeneratesExpectedSpansAndDivs() { // Arrange var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Customer.Index.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Customer/HtmlGeneration_Customer"); var nameValueCollection = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("Number", string.Empty), new KeyValuePair<string,string>("Name", string.Empty), new KeyValuePair<string,string>("Email", string.Empty), new KeyValuePair<string,string>("PhoneNumber", string.Empty), new KeyValuePair<string,string>("Password", string.Empty) }; request.Content = new FormUrlEncodedContent(nameValueCollection); // Act var response = await Client.SendAsync(request); var responseContent = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); responseContent = responseContent.Trim(); ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent, token: AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseContent, "Customer/HtmlGeneration_Customer")); } [Fact] public async Task ClientValidators_AreGeneratedDuringInitialRender() { // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customer/HtmlGeneration_Customer/CustomerWithRecords"); // Act var response = await Client.SendAsync(request); // Assert var document = await response.GetHtmlDocumentAsync(); var numberInput = document.RequiredQuerySelector("input[id=Number]"); Assert.Equal("true", numberInput.GetAttribute("data-val")); Assert.Equal("The field Number must be between 1 and 100.", numberInput.GetAttribute("data-val-range")); Assert.Equal("The Number field is required.", numberInput.GetAttribute("data-val-required")); var passwordInput = document.RequiredQuerySelector("input[id=Password]"); Assert.Equal("true", passwordInput.GetAttribute("data-val")); Assert.Equal("The Password field is required.", passwordInput.GetAttribute("data-val-required")); var addressInput = document.RequiredQuerySelector("input[id=Address]"); Assert.Equal("true", addressInput.GetAttribute("data-val")); Assert.Equal("The Address field is required.", addressInput.GetAttribute("data-val-required")); } [Fact] public async Task ValidationTagHelpers_UsingRecords() { // Arrange var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Customer/HtmlGeneration_Customer/CustomerWithRecords"); var nameValueCollection = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("Number", string.Empty), new KeyValuePair<string,string>("Name", string.Empty), new KeyValuePair<string,string>("Email", string.Empty), new KeyValuePair<string,string>("PhoneNumber", string.Empty), new KeyValuePair<string,string>("Password", string.Empty), new KeyValuePair<string,string>("Address", string.Empty), }; request.Content = new FormUrlEncodedContent(nameValueCollection); // Act var response = await Client.SendAsync(request); // Assert var document = await response.GetHtmlDocumentAsync(); var validation = document.RequiredQuerySelector("span[data-valmsg-for=Number]"); Assert.Equal("The value '' is invalid.", validation.TextContent); validation = document.QuerySelector("span[data-valmsg-for=Name]"); Assert.Null(validation); validation = document.QuerySelector("span[data-valmsg-for=Email]"); Assert.Equal("field-validation-valid", validation.ClassName); validation = document.QuerySelector("span[data-valmsg-for=Password]"); Assert.Equal("The Password field is required.", validation.TextContent); validation = document.QuerySelector("span[data-valmsg-for=Address]"); Assert.Equal("The Address field is required.", validation.TextContent); } [Fact] public async Task CacheTagHelper_CanCachePortionsOfViewsPartialViewsAndViewComponents() { // Arrange var assertFile = "compiler/resources/CacheTagHelper_CanCachePortionsOfViewsPartialViewsAndViewComponents.Assert"; var outputFile1 = assertFile + "1.txt"; var expected1 = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile1, sourceFile: false); var outputFile2 = assertFile + "2.txt"; var expected2 = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile2, sourceFile: false); var outputFile3 = assertFile + "3.txt"; var expected3 = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile3, sourceFile: false); // Act - 1 // Verify that content gets cached based on vary-by-params var targetUrl = "/catalog?categoryId=1&correlationid=1"; var request = RequestWithLocale(targetUrl, "North"); var response1 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync(); request = RequestWithLocale(targetUrl, "North"); var response2 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync(); // Assert - 1 ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile1, expected1, response1.Trim()); if (!ResourceFile.GenerateBaselines) { Assert.Equal(expected1, response2.Trim(), ignoreLineEndingDifferences: true); } // Act - 2 // Verify content gets changed in partials when one of the vary by parameters is changed targetUrl = "/catalog?categoryId=3&correlationid=2"; request = RequestWithLocale(targetUrl, "North"); var response3 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync(); request = RequestWithLocale(targetUrl, "North"); var response4 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync(); // Assert - 2 ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile2, expected2, response3.Trim()); if (!ResourceFile.GenerateBaselines) { Assert.Equal(expected2, response4.Trim(), ignoreLineEndingDifferences: true); } // Act - 3 // Verify content gets changed in a View Component when the Vary-by-header parameters is changed targetUrl = "/catalog?categoryId=3&correlationid=3"; request = RequestWithLocale(targetUrl, "East"); var response5 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync(); request = RequestWithLocale(targetUrl, "East"); var response6 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync(); // Assert - 3 ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile3, expected3, response5.Trim()); if (!ResourceFile.GenerateBaselines) { Assert.Equal(expected3, response6.Trim(), ignoreLineEndingDifferences: true); } } [Fact] public async Task CacheTagHelper_ExpiresContent_BasedOnExpiresParameter() { // Arrange & Act - 1 var response1 = await Client.GetStringAsync("/catalog/2"); // Assert - 1 var expected1 = "Cached content for 2"; Assert.Equal(expected1, response1.Trim()); // Act - 2 await Task.Delay(TimeSpan.FromSeconds(2)); var response2 = await Client.GetStringAsync("/catalog/3"); // Assert - 2 var expected2 = "Cached content for 3"; Assert.Equal(expected2, response2.Trim()); } [Fact] public async Task CacheTagHelper_UsesVaryByCookie_ToVaryContent() { // Arrange & Act - 1 var response1 = await Client.GetStringAsync("/catalog/cart?correlationid=1"); // Assert - 1 var expected1 = "Cart content for 1"; Assert.Equal(expected1, response1.Trim()); // Act - 2 var request = new HttpRequestMessage(HttpMethod.Get, "/catalog/cart?correlationid=2"); request.Headers.Add("Cookie", "CartId=10"); var response2 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync(); // Assert - 2 var expected2 = "Cart content for 2"; Assert.Equal(expected2, response2.Trim()); // Act - 3 // Resend the cookieless request and cached result from the first response. var response3 = await Client.GetStringAsync("/catalog/cart?correlationid=3"); // Assert - 3 Assert.Equal(expected1, response3.Trim()); } [Fact] public async Task CacheTagHelper_VariesByRoute() { // Arrange & Act - 1 var response1 = await Client.GetStringAsync( "/catalog/north-west/confirm-payment?confirmationId=1"); // Assert - 1 var expected1 = "Welcome Guest. Your confirmation id is 1. (Region north-west)"; Assert.Equal(expected1, response1.Trim()); // Act - 2 var response2 = await Client.GetStringAsync( "/catalog/south-central/confirm-payment?confirmationId=2"); // Assert - 2 var expected2 = "Welcome Guest. Your confirmation id is 2. (Region south-central)"; Assert.Equal(expected2, response2.Trim()); // Act 3 var response3 = await Client.GetStringAsync( "/catalog/north-west/Silver/confirm-payment?confirmationId=4"); var expected3 = "Welcome Silver member. Your confirmation id is 4. (Region north-west)"; Assert.Equal(expected3, response3.Trim()); // Act 4 var response4 = await Client.GetStringAsync( "/catalog/north-west/Gold/confirm-payment?confirmationId=5"); var expected4 = "Welcome Gold member. Your confirmation id is 5. (Region north-west)"; Assert.Equal(expected4, response4.Trim()); // Act - 4 // Resend the responses and expect cached results. response1 = await Client.GetStringAsync( "/catalog/north-west/confirm-payment?confirmationId=301"); response2 = await Client.GetStringAsync( "/catalog/south-central/confirm-payment?confirmationId=402"); response3 = await Client.GetStringAsync( "/catalog/north-west/Silver/confirm-payment?confirmationId=503"); response4 = await Client.GetStringAsync( "/catalog/north-west/Gold/confirm-payment?confirmationId=608"); // Assert - 4 Assert.Equal(expected1, response1.Trim()); Assert.Equal(expected2, response2.Trim()); Assert.Equal(expected3, response3.Trim()); Assert.Equal(expected4, response4.Trim()); } [Fact] public async Task CacheTagHelper_VariesByUserId() { // Arrange & Act - 1 var response1 = await Client.GetStringAsync("/catalog/past-purchases/test1?correlationid=1"); var response2 = await Client.GetStringAsync("/catalog/past-purchases/test1?correlationid=2"); // Assert - 1 var expected1 = "Past purchases for user test1 (1)"; Assert.Equal(expected1, response1.Trim()); Assert.Equal(expected1, response2.Trim()); // Act - 2 var response3 = await Client.GetStringAsync("/catalog/past-purchases/test2?correlationid=3"); var response4 = await Client.GetStringAsync("/catalog/past-purchases/test2?correlationid=4"); // Assert - 2 var expected2 = "Past purchases for user test2 (3)"; Assert.Equal(expected2, response3.Trim()); Assert.Equal(expected2, response4.Trim()); } [Fact] [QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/36765")] public async Task CacheTagHelper_BubblesExpirationOfNestedTagHelpers() { // Arrange & Act - 1 var response1 = await Client.GetStringAsync("/categories/Books?correlationId=1"); // Assert - 1 var expected1 = @"Category: Books Products: Book1, Book2 (1)"; Assert.Equal(expected1, response1.Trim(), ignoreLineEndingDifferences: true); // Act - 2 var response2 = await Client.GetStringAsync("/categories/Electronics?correlationId=2"); // Assert - 2 var expected2 = @"Category: Electronics Products: Book1, Book2 (1)"; Assert.Equal(expected2, response2.Trim(), ignoreLineEndingDifferences: true); // Act - 3 // Trigger an expiration of the nested content. var content = @"[{ ""productName"": ""Music Systems"" },{ ""productName"": ""Televisions"" }]"; var requestMessage = new HttpRequestMessage(HttpMethod.Post, "/categories/Electronics"); requestMessage.Content = new StringContent(content, Encoding.UTF8, "application/json"); (await Client.SendAsync(requestMessage)).EnsureSuccessStatusCode(); var response3 = await Client.GetStringAsync("/categories/Electronics?correlationId=3"); // Assert - 3 var expected3 = @"Category: Electronics Products: Music Systems, Televisions (3)"; Assert.Equal(expected3, response3.Trim(), ignoreLineEndingDifferences: true); } [Fact] public async Task CacheTagHelper_DoesNotCacheIfDisabled() { // Arrange & Act var response1 = await Client.GetStringAsync("/catalog/GetDealPercentage/20?isEnabled=true"); var response2 = await Client.GetStringAsync("/catalog/GetDealPercentage/40?isEnabled=true"); var response3 = await Client.GetStringAsync("/catalog/GetDealPercentage/30?isEnabled=false"); // Assert Assert.Equal("Deal percentage is 20", response1.Trim()); Assert.Equal("Deal percentage is 20", response2.Trim()); Assert.Equal("Deal percentage is 30", response3.Trim()); } [Fact] public async Task EditorTemplateWithNoModel_RendersWithCorrectMetadata() { // Arrange var expected = "<label class=\"control-label col-md-2\" for=\"Name\">ItemName</label>" + Environment.NewLine + "<input id=\"Name\" name=\"Name\" type=\"text\" value=\"\" />" + Environment.NewLine + Environment.NewLine + "<label class=\"control-label col-md-2\" for=\"Id\">ItemNo</label>" + Environment.NewLine + "<input data-val=\"true\" data-val-required=\"The ItemNo field is required.\" id=\"Id\" name=\"Id\" type=\"text\" value=\"\" />" + Environment.NewLine + Environment.NewLine; // Act var response = await Client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingSharedEditorTemplate"); // Assert Assert.Equal(expected, response, ignoreLineEndingDifferences: true); } [Fact] public async Task EditorTemplateWithSpecificModel_RendersWithCorrectMetadata() { // Arrange var expected = "<label for=\"Description\">ItemDesc</label>" + Environment.NewLine + "<input id=\"Description\" name=\"Description\" type=\"text\" value=\"\" />" + Environment.NewLine + Environment.NewLine; // Act var response = await Client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingModelSpecificEditorTemplate"); // Assert Assert.Equal(expected, response, ignoreLineEndingDifferences: true); } // We want to make sure that for 'weird' model expressions involving: // - fields // - statics // - private // // These tests verify that we don't throw, and can evaluate the expression to get the model // value. One quirk of behavior for these cases is that we can't return a correct model metadata // instance (this is true for anything other than a public instance property). We're not overly // concerned with that, and so the accuracy of the model metadata is not verified by the test. [Theory] [InlineData("GetWeirdWithHtmlHelpers")] [InlineData("GetWeirdWithTagHelpers")] public async Task WeirdModelExpressions_CanAccessModelValues(string action) { // Arrange var url = "http://localhost/HtmlGeneration_WeirdExpressions/" + action; // Act var response = await Client.GetStringAsync(url); // Assert Assert.Contains("Hello, Field World!", response); Assert.Contains("Hello, Static World!", response); Assert.Contains("Hello, Private World!", response); } [Fact] public async Task PartialTagHelper_AllowsPassingModelValue() { // Arrange var url = "/HtmlGeneration_Home/StatusMessage"; // Act var document = await Client.GetHtmlDocumentAsync(url); // Assert var banner = document.RequiredQuerySelector(".banner"); Assert.Equal("Some status message", banner.TextContent); } [Fact] public async Task PartialTagHelper_AllowsPassingNullModelValue() { // Regression test for https://github.com/aspnet/Mvc/issues/7667. // Arrange var url = "/HtmlGeneration_Home/NullStatusMessage"; // Act var document = await Client.GetHtmlDocumentAsync(url); // Assert var banner = document.RequiredQuerySelector(".banner"); Assert.Empty(banner.TextContent); } [Fact] public async Task PartialTagHelper_AllowsUsingFallback() { // Arrange var url = "/Customer/PartialWithFallback"; // Act var document = await Client.GetHtmlDocumentAsync(url); // Assert var content = document.RequiredQuerySelector("#content"); Assert.Equal("Hello from fallback", content.TextContent); } [Fact] public async Task PartialTagHelper_AllowsUsingOptional() { // Arrange var url = "/Customer/PartialWithOptional"; // Act var document = await Client.GetHtmlDocumentAsync(url); // Assert var content = document.RequiredQuerySelector("#content"); Assert.Empty(content.TextContent); } [Fact] public async Task ValidationProviderAttribute_ValidationTagHelpers_GeneratesExpectedDataAttributes() { // Act var document = await Client.GetHtmlDocumentAsync("HtmlGeneration_Home/ValidationProviderAttribute"); // Assert var firstName = document.RequiredQuerySelector("#FirstName"); Assert.Equal("true", firstName.GetAttribute("data-val")); Assert.Equal("The FirstName field is required.", firstName.GetAttribute("data-val-required")); Assert.Equal("The field FirstName must be a string with a maximum length of 5.", firstName.GetAttribute("data-val-length")); Assert.Equal("5", firstName.GetAttribute("data-val-length-max")); Assert.Equal("The field FirstName must match the regular expression '[A-Za-z]*'.", firstName.GetAttribute("data-val-regex")); Assert.Equal("[A-Za-z]*", firstName.GetAttribute("data-val-regex-pattern")); var lastName = document.RequiredQuerySelector("#LastName"); Assert.Equal("true", lastName.GetAttribute("data-val")); Assert.Equal("The LastName field is required.", lastName.GetAttribute("data-val-required")); Assert.Equal("The field LastName must be a string with a maximum length of 6.", lastName.GetAttribute("data-val-length")); Assert.Equal("6", lastName.GetAttribute("data-val-length-max")); Assert.False(lastName.HasAttribute("data-val-regex")); } [Fact] public async Task ValidationProviderAttribute_ValidationTagHelpers_GeneratesExpectedSpansAndDivsOnValidationError() { // Arrange var request = new HttpRequestMessage(HttpMethod.Post, "HtmlGeneration_Home/ValidationProviderAttribute"); request.Content = new FormUrlEncodedContent(new Dictionary<string, string> { { "FirstName", "TestFirstName" }, }); // Act var response = await Client.SendAsync(request); // Assert await response.AssertStatusCodeAsync(HttpStatusCode.OK); var document = await response.GetHtmlDocumentAsync(); Assert.Collection( document.QuerySelectorAll("div.validation-summary-errors ul li"), item => Assert.Equal("The field FirstName must be a string with a maximum length of 5.", item.TextContent), item => Assert.Equal("The LastName field is required.", item.TextContent)); } private static HttpRequestMessage RequestWithLocale(string url, string locale) { var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Add("Locale", locale); return request; } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// User /// </summary> [DataContract(Name = "User")] public partial class User : IEquatable<User>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="User" /> class. /// </summary> /// <param name="_class">_class.</param> /// <param name="id">id.</param> /// <param name="fullName">fullName.</param> /// <param name="email">email.</param> /// <param name="name">name.</param> public User(string _class = default(string), string id = default(string), string fullName = default(string), string email = default(string), string name = default(string)) { this.Class = _class; this.Id = id; this.FullName = fullName; this.Email = email; this.Name = name; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name = "_class", EmitDefaultValue = false)] public string Class { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name = "id", EmitDefaultValue = false)] public string Id { get; set; } /// <summary> /// Gets or Sets FullName /// </summary> [DataMember(Name = "fullName", EmitDefaultValue = false)] public string FullName { get; set; } /// <summary> /// Gets or Sets Email /// </summary> [DataMember(Name = "email", EmitDefaultValue = false)] public string Email { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name = "name", EmitDefaultValue = false)] public string Name { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" FullName: ").Append(FullName).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as User); } /// <summary> /// Returns true if User instances are equal /// </summary> /// <param name="input">Instance of User to be compared</param> /// <returns>Boolean</returns> public bool Equals(User input) { if (input == null) { return false; } return ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ) && ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.FullName == input.FullName || (this.FullName != null && this.FullName.Equals(input.FullName)) ) && ( this.Email == input.Email || (this.Email != null && this.Email.Equals(input.Email)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Class != null) { hashCode = (hashCode * 59) + this.Class.GetHashCode(); } if (this.Id != null) { hashCode = (hashCode * 59) + this.Id.GetHashCode(); } if (this.FullName != null) { hashCode = (hashCode * 59) + this.FullName.GetHashCode(); } if (this.Email != null) { hashCode = (hashCode * 59) + this.Email.GetHashCode(); } if (this.Name != null) { hashCode = (hashCode * 59) + this.Name.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Net.ChunkStream // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // (C) 2003 Ximian, Inc (http://www.ximian.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace System.Net { internal sealed class ChunkStream { private enum State { None, PartialSize, Body, BodyFinished, Trailer } private class Chunk { public byte[] Bytes; public int Offset; public Chunk(byte[] chunk) { Bytes = chunk; } public int Read(byte[] buffer, int offset, int size) { int nread = (size > Bytes.Length - Offset) ? Bytes.Length - Offset : size; Buffer.BlockCopy(Bytes, Offset, buffer, offset, nread); Offset += nread; return nread; } } internal WebHeaderCollection _headers; private int _chunkSize; private int _chunkRead; private int _totalWritten; private State _state; private StringBuilder _saved; private bool _sawCR; private bool _gotit; private int _trailerState; private List<Chunk> _chunks; public ChunkStream(byte[] buffer, int offset, int size, WebHeaderCollection headers) : this(headers) { Write(buffer, offset, size); } public ChunkStream(WebHeaderCollection headers) { _headers = headers; _saved = new StringBuilder(); _chunks = new List<Chunk>(); _chunkSize = -1; _totalWritten = 0; } public void ResetBuffer() { _chunkSize = -1; _chunkRead = 0; _totalWritten = 0; _chunks.Clear(); } public void WriteAndReadBack(byte[] buffer, int offset, int size, ref int read) { if (offset + read > 0) Write(buffer, offset, offset + read); read = Read(buffer, offset, size); } public int Read(byte[] buffer, int offset, int size) { return ReadFromChunks(buffer, offset, size); } private int ReadFromChunks(byte[] buffer, int offset, int size) { int count = _chunks.Count; int nread = 0; var chunksForRemoving = new List<Chunk>(count); for (int i = 0; i < count; i++) { Chunk chunk = _chunks[i]; if (chunk.Offset == chunk.Bytes.Length) { chunksForRemoving.Add(chunk); continue; } nread += chunk.Read(buffer, offset + nread, size - nread); if (nread == size) break; } foreach (var chunk in chunksForRemoving) _chunks.Remove(chunk); return nread; } public void Write(byte[] buffer, int offset, int size) { if (offset < size) InternalWrite(buffer, ref offset, size); } private void InternalWrite(byte[] buffer, ref int offset, int size) { if (_state == State.None || _state == State.PartialSize) { _state = GetChunkSize(buffer, ref offset, size); if (_state == State.PartialSize) return; _saved.Length = 0; _sawCR = false; _gotit = false; } if (_state == State.Body && offset < size) { _state = ReadBody(buffer, ref offset, size); if (_state == State.Body) return; } if (_state == State.BodyFinished && offset < size) { _state = ReadCRLF(buffer, ref offset, size); if (_state == State.BodyFinished) return; _sawCR = false; } if (_state == State.Trailer && offset < size) { _state = ReadTrailer(buffer, ref offset, size); if (_state == State.Trailer) return; _saved.Length = 0; _sawCR = false; _gotit = false; } if (offset < size) InternalWrite(buffer, ref offset, size); } public bool WantMore { get { return (_chunkRead != _chunkSize || _chunkSize != 0 || _state != State.None); } } public bool DataAvailable { get { int count = _chunks.Count; for (int i = 0; i < count; i++) { Chunk ch = _chunks[i]; if (ch == null || ch.Bytes == null) continue; if (ch.Bytes.Length > 0 && ch.Offset < ch.Bytes.Length) return (_state != State.Body); } return false; } } public int TotalDataSize { get { return _totalWritten; } } public int ChunkLeft { get { return _chunkSize - _chunkRead; } } private State ReadBody(byte[] buffer, ref int offset, int size) { if (_chunkSize == 0) return State.BodyFinished; int diff = size - offset; if (diff + _chunkRead > _chunkSize) diff = _chunkSize - _chunkRead; byte[] chunk = new byte[diff]; Buffer.BlockCopy(buffer, offset, chunk, 0, diff); _chunks.Add(new Chunk(chunk)); offset += diff; _chunkRead += diff; _totalWritten += diff; return (_chunkRead == _chunkSize) ? State.BodyFinished : State.Body; } private State GetChunkSize(byte[] buffer, ref int offset, int size) { _chunkRead = 0; _chunkSize = 0; char c = '\0'; while (offset < size) { c = (char)buffer[offset++]; if (c == '\r') { if (_sawCR) ThrowProtocolViolation("2 CR found"); _sawCR = true; continue; } if (_sawCR && c == '\n') break; if (c == ' ') _gotit = true; if (!_gotit) _saved.Append(c); if (_saved.Length > 20) ThrowProtocolViolation("chunk size too long."); } if (!_sawCR || c != '\n') { if (offset < size) ThrowProtocolViolation("Missing \\n"); try { if (_saved.Length > 0) { _chunkSize = Int32.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber); } } catch (Exception) { ThrowProtocolViolation("Cannot parse chunk size."); } return State.PartialSize; } _chunkRead = 0; try { _chunkSize = Int32.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber); } catch (Exception) { ThrowProtocolViolation("Cannot parse chunk size."); } if (_chunkSize == 0) { _trailerState = 2; return State.Trailer; } return State.Body; } private static string RemoveChunkExtension(string input) { int idx = input.IndexOf(';'); if (idx == -1) return input; return input.Substring(0, idx); } private State ReadCRLF(byte[] buffer, ref int offset, int size) { if (!_sawCR) { if ((char)buffer[offset++] != '\r') ThrowProtocolViolation("Expecting \\r"); _sawCR = true; if (offset == size) return State.BodyFinished; } if (_sawCR && (char)buffer[offset++] != '\n') ThrowProtocolViolation("Expecting \\n"); return State.None; } private State ReadTrailer(byte[] buffer, ref int offset, int size) { char c = '\0'; // short path if (_trailerState == 2 && (char)buffer[offset] == '\r' && _saved.Length == 0) { offset++; if (offset < size && (char)buffer[offset] == '\n') { offset++; return State.None; } offset--; } int st = _trailerState; string stString = "\r\n\r"; while (offset < size && st < 4) { c = (char)buffer[offset++]; if ((st == 0 || st == 2) && c == '\r') { st++; continue; } if ((st == 1 || st == 3) && c == '\n') { st++; continue; } if (st > 0) { _saved.Append(stString.Substring(0, _saved.Length == 0 ? st - 2 : st)); st = 0; if (_saved.Length > 4196) ThrowProtocolViolation("Error reading trailer (too long)."); } } if (st < 4) { _trailerState = st; if (offset < size) ThrowProtocolViolation("Error reading trailer."); return State.Trailer; } StringReader reader = new StringReader(_saved.ToString()); string line; while ((line = reader.ReadLine()) != null && line != "") _headers.Add(line); return State.None; } private static void ThrowProtocolViolation(string message) { WebException we = new WebException(message, null, WebExceptionStatus.ServerProtocolViolation, null); throw we; } } }
// // Arbiter.cs // // Author: // Trent McPheron <twilightinzero@gmail.com> // // Copyright (c) 2009-2011 Trent McPheron // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.IO; using System.Collections.Generic; using System.Reflection; using Gtk; namespace Arbiter { // This class stores properties and methods that are used // throughout the entire program. static class Arbiter { /////////////////// // Fields / Props /////////////////// // List of duels. private static List<string> fightNightSwords; private static List<string> fightNightFists; private static List<string> fightNightMagic; private static List<string> normalDuelList; // Saves date when app was started. private static DateTime today; private static string currentDate; // Newline, for convenience. private static string n = Environment.NewLine; // Sports. public static Sport DuelOfSwords { get; private set; } public static Sport DuelOfFists { get; private set; } public static Sport DuelOfMagic { get; private set; } // Settings. public static int WindowWidth { get; set; } public static int WindowHeight { get; set; } public static string TabPosition { get; set; } public static string LogDirectory { get; set; } public static bool HideIcons { get; set; } public static bool HideClose { get; set; } public static bool HideButtons { get; set; } public static bool SmallScore { get; set; } public static bool VertTabs { get; set; } public static ListStore Duelists { get; set; } public static ListStore Rings { get; set; } // Internal shift state stuff. public static TextBuffer ShiftReport { get; set; } public static bool FightNight { get; set; } public static int NumDuels { get; set; } // Returns the current subdirectory for the night's duels. public static string CurrentDir { get { return Path.Combine(LogDirectory, currentDate); } } /////////////////// // Entry Point /////////////////// public static void Main (string[] args) { Application.Init(); // Make the program look less out of place on Windows. int p = (int) Environment.OSVersion.Platform; if (p != 4 && p != 128) { Rc.ParseString(@" gtk-icon-sizes = 'panel=16,16 : gtk-menu=16,16' gtk-button-images = 0 gtk-menu-images = 0 style 'default' { GtkWidget::focus-line-width = 0 } style 'tabs' = 'default' { GtkWidget::focus-padding = 0 } style 'lists' = 'default' { GtkWidget::focus-line-width = 1 } class 'GtkWidget' style 'default' class 'GtkNotebook' style 'tabs' class 'GtkTreeView' style 'lists' "); } // Create ListStores for the duelists and rings. Duelists = new ListStore(typeof(string)); Rings = new ListStore(typeof(string)); Duelists.SetSortColumnId(0, SortType.Ascending); // Default settings. TabPosition = "LeftVert"; LogDirectory = ""; WindowWidth = 300; WindowHeight = 300; HideIcons = false; HideClose = false; HideButtons = false; SmallScore = false; // Load basic settings file. try { string path = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location); path = Path.Combine(path, "settings.cfg"); // The using block will close the stream reader if an exception // occurs. using (StreamReader sr = new StreamReader(path)) { WindowWidth = Int32.Parse(sr.ReadLine()); WindowHeight = Int32.Parse(sr.ReadLine()); TabPosition = String.Copy(sr.ReadLine()); LogDirectory = String.Copy(sr.ReadLine()); HideIcons = Boolean.Parse(sr.ReadLine()); HideClose = Boolean.Parse(sr.ReadLine()); HideButtons = Boolean.Parse(sr.ReadLine()); SmallScore = Boolean.Parse(sr.ReadLine()); } } catch {} if (LogDirectory == "") { // Prompt the user to pick a directory to store duels in. FileChooserDialog fc = new FileChooserDialog( "Select Log Directory", null, FileChooserAction.SelectFolder, new object[] {Stock.Open, ResponseType.Accept}); fc.Icon = Gdk.Pixbuf.LoadFromResource("RoH.png"); // Keep running the dialog until we get OK. int r = 0; while (r != (int)ResponseType.Accept) { r = fc.Run(); } LogDirectory = fc.Filename; fc.Destroy(); } // Load duelist list from file or embedded resource. try { string path = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location); path = Path.Combine(path, "duelists.cfg"); StreamReader sr = new StreamReader(path); while (!sr.EndOfStream) { Duelists.AppendValues(sr.ReadLine()); } sr.Close(); } catch { StreamReader sr = new StreamReader( Assembly.GetExecutingAssembly(). GetManifestResourceStream("duelists.cfg")); while (!sr.EndOfStream) Duelists.AppendValues(sr.ReadLine()); sr.Close(); } // Load ring list from file or embedded resource. try { string path = Path.GetDirectoryName(Assembly. GetExecutingAssembly().Location); path = Path.Combine(path, "rings.cfg"); StreamReader sr = new StreamReader(path); while (!sr.EndOfStream) { Rings.AppendValues(sr.ReadLine()); } sr.Close(); } catch { StreamReader sr = new StreamReader(Assembly.GetExecutingAssembly(). GetManifestResourceStream("rings.cfg")); while (!sr.EndOfStream) { Rings.AppendValues(sr.ReadLine()); } sr.Close(); } // Set date now so that it doesn't change at midnight, then get it // as a string. today = DateTime.Now; if (today.Hour < 3) { today = DateTime.Now.Subtract(TimeSpan.FromDays(1)); } currentDate = today.Year.ToString("0000") + "-" + today.Month.ToString("00") + "-" + today.Day.ToString("00"); // Load the sports. DuelOfSwords = new Sport("swords"); DuelOfFists = new Sport("fists"); DuelOfMagic = new Sport("magic"); // Initialize Fight Night switch and duel lists. FightNight = false; fightNightSwords = new List<string>(); fightNightFists = new List<string>(); fightNightMagic = new List<string>(); normalDuelList = new List<string>(); NumDuels = 0; // Detect if a shift report already exists, and if so, load it. ShiftReport = new TextBuffer(null); DetectShiftReport(); // Create the main window and go. MainWindow mw = new MainWindow(); mw.ShowAll(); Application.Run(); } /////////////////// // Other Methods /////////////////// // Save settings to the settings files. public static void SaveSettings () { // First, the basic settings. string path = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location); path = Path.Combine(path, "settings.cfg"); StreamWriter sw = new StreamWriter(path); sw.WriteLine(WindowWidth.ToString()); sw.WriteLine(WindowHeight.ToString()); sw.WriteLine(TabPosition); sw.WriteLine(LogDirectory); sw.WriteLine(HideIcons.ToString()); sw.WriteLine(HideClose.ToString()); sw.WriteLine(HideButtons.ToString()); sw.WriteLine(SmallScore.ToString()); sw.Close(); // Now the duelist list. path = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location); path = Path.Combine(path, "duelists.cfg"); sw = new StreamWriter(path); foreach(object[] s in Duelists) { sw.WriteLine((string)s[0]); } sw.Close(); // Now the ring list. path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); path = Path.Combine(path, "rings.cfg"); sw = new StreamWriter(path); foreach(object[] s in Rings) { sw.WriteLine((string)s[0]); } sw.Close(); } // Creates a bare-bones shift report and also makes sure the folder exists. public static void CreateShiftReport () { // Create the subdirectory if it doesn't exist. if (!File.Exists(CurrentDir)) { Directory.CreateDirectory(CurrentDir); } // Write the first few lines. StreamWriter sr = new StreamWriter( Path.Combine(CurrentDir, "00. Shift Report.txt"), false); ShiftReport.Text = today.ToLongDateString() + n + n + "[Insert comments here.]"; sr.Write(ShiftReport.Text); sr.Close(); } // Write a duel result to the shift report. This remakes the entire shift // report each time so that Fight Night duels can be sorted. public static void UpdateShiftReport (string final, bool delete) { // Open the file and write the first few lines. StreamWriter sr = new StreamWriter( Path.Combine(CurrentDir, "00. Shift Report.txt"), false); ShiftReport.Text = today.ToLongDateString() + n + n + "[Insert comments here.]"; // Normal dueling. if (!FightNight) { // Add or delete the final line to the list of duels. if (!delete) { normalDuelList.Add(final); } else { normalDuelList.Remove(final); } // Write them to the report. ShiftReport.Text += n; foreach (string s in normalDuelList) { ShiftReport.Text += n + s; } } // It's more complicated for Fight Night. else { // Determine duel type from last three characters of final line. if (!delete) { switch (final.Substring(final.Length - 3, 3)) { case "DoS": fightNightSwords.Add(final); break; case "DoF": fightNightFists.Add(final); break; case "DoM": fightNightMagic.Add(final); break; } } else { switch (final.Substring(final.Length - 3, 3)) { case "DoS": fightNightSwords.Remove(final); break; case "DoF": fightNightFists.Remove(final); break; case "DoM": fightNightMagic.Remove(final); break; } } // Write each list to the shift report buffer. List<string>[] lists = new List<string>[3] {fightNightSwords, fightNightFists, fightNightMagic}; foreach (List<string> l in lists) { if (l.Count > 0) { ShiftReport.Text += n; foreach (string s in l) { ShiftReport.Text += n + s; } } } } // Write the text in the buffer to the file. sr.Write(ShiftReport.Text); sr.Close(); } // Detect if a shift report already exists, and if so, ask what to do. public static void DetectShiftReport () { if (File.Exists(Path.Combine(CurrentDir, "00. Shift Report.txt"))) { Dialog dialog = new Dialog("Shift report detected", null, DialogFlags.NoSeparator | DialogFlags.Modal, new object[] {Stock.No, ResponseType.No, Stock.Yes, ResponseType.Yes}); dialog.Icon = Gdk.Pixbuf.LoadFromResource("RoH.png"); Label label = new Label( "An existing shift report for today has\n" + "been detected. Would you like to load it?\n" + "if not, it will be overwritten when you\n" + "start a duel."); dialog.VBox.PackStart(label); dialog.Default = dialog.ActionArea.Children[0]; dialog.VBox.ShowAll(); bool load = dialog.Run() == (int)ResponseType.Yes; dialog.Destroy(); // The list of duels completed will be loaded. if (load) { StreamReader sr = new StreamReader( Path.Combine(CurrentDir, "00. Shift Report.txt")); ShiftReport.Text += sr.ReadLine() + n; // The first three ShiftReport.Text += sr.ReadLine() + n; // lines don't matter. ShiftReport.Text += sr.ReadLine() + n; while (!sr.EndOfStream) { string s = sr.ReadLine(); ShiftReport.Text += s + n; if (s != "") { // Can't do anything with blank lines. switch (s.Substring(s.Length - 3, 3)) { case "DoS": fightNightSwords.Add(s); FightNight = true; break; case "DoF": fightNightFists.Add(s); FightNight = true; break; case "DoM": fightNightMagic.Add(s); FightNight = true; break; default: normalDuelList.Add(s); FightNight = false; break; } NumDuels++; } } } } } } }
using System; using System.Text; using System.Collections.Generic; namespace SillyWidgets.Gizmos { public enum States { Begin, Start, Declaration, Doctype, Comment, Element, Name, Attributes, TagDone, Code, End } public class HtmlStateMachineGizmo : IStateMachineGizmo<States, Token> { private Dictionary<States, HtmlState> StateLookup = new Dictionary<States, HtmlState>() { { States.Begin, new BEGIN() }, { States.Start, new START() }, { States.End, new END() }, { States.Declaration, new DECL() }, { States.Comment, new COM() }, { States.Doctype, new DOC() }, { States.Element, new ELEMENT() }, { States.Attributes, new ATTR() }, { States.TagDone, new TAGDONE() }, { States.Name, new NAME() }, { States.Code, new CODE() } }; private HtmlState Current = null; public HtmlTreeBuilder TreeBuilder = new HtmlTreeBuilder(); public HtmlStateMachineGizmo() { Current = StateLookup[States.Begin]; } public void Transition(States toState, Token token) { Current = StateLookup[toState]; Current.Enter(token, this); } public void Accept(Token token) { Current.Accept(token, this); } } internal abstract class HtmlState : IStateGizmo<Token, HtmlStateMachineGizmo> { public HtmlState() { } public abstract void Enter(Token token, HtmlStateMachineGizmo context); public abstract void Accept(Token token, HtmlStateMachineGizmo context); } internal class BEGIN : HtmlState { public BEGIN() { } public override void Enter(Token token, HtmlStateMachineGizmo context) { } public override void Accept(Token token, HtmlStateMachineGizmo context) { if (token.Type == TokenType.BeginDoc) { context.TreeBuilder.CreateRoot(); context.Transition(States.Start, token); return; } if (token.Type == TokenType.EndDoc) { context.Transition(States.End, token); return; } throw new Exception("Unexpected token: " + token.Type); } } internal class END : HtmlState { public END() { } public override void Enter(Token token, HtmlStateMachineGizmo context) { } public override void Accept(Token token, HtmlStateMachineGizmo context) { throw new Exception("This is the end of the document, you're supposed to be done, yet you keep trying to feed me tokens?? WTF?"); } } internal class START : HtmlState { public START() { } public override void Enter(Token token, HtmlStateMachineGizmo context) { } public override void Accept(Token token, HtmlStateMachineGizmo context) { if (token.Type == TokenType.MarkupDecl) { context.Transition(States.Declaration, token); return; } if (token.Type == TokenType.OpenTag) { context.Transition(States.Element, token); return; } if (token.Type == TokenType.Text) { context.TreeBuilder.AddChildText(token.Value); return; } if (token.Type == TokenType.CloseTag) { context.Transition(States.TagDone, token); return; } if (token.Type == TokenType.Code) { context.Transition(States.Code, token); return; } if (token.Type == TokenType.EndDoc) { context.Transition(States.End, token); return; } throw new Exception("I was expecting either a Markup Delcaration or Open Tag, but I got: " + token.Type); } } internal class DECL : HtmlState { public DECL() { } public override void Enter(Token token, HtmlStateMachineGizmo context) { } public override void Accept(Token token, HtmlStateMachineGizmo context) { if (token.Type == TokenType.Doctype) { context.Transition(States.Doctype, token); return; } if (token.Type == TokenType.BeginComment) { context.Transition(States.Comment, token); return; } if (token.Type == TokenType.EndDoc) { context.Transition(States.End, token); return; } throw new Exception("Hmm, looks like you started declaring something cool then decided not to: " + token.Type); } } internal class DOC : HtmlState { public DOC() { } public override void Enter(Token token, HtmlStateMachineGizmo context) { } public override void Accept(Token token, HtmlStateMachineGizmo context) { if (token.Type == TokenType.EndTag) { context.Transition(States.Start, token); return; } if (token.Type == TokenType.EndDoc) { context.Transition(States.End, token); return; } throw new Exception("Well, you started declaring a Doctype then decided not to? " + token.Type); } } internal class COM : HtmlState { public COM() { } public override void Enter(Token token, HtmlStateMachineGizmo context) { } public override void Accept(Token token, HtmlStateMachineGizmo context) { if (token.Type == TokenType.EndComment) { context.Transition(States.Start, token); return; } if (token.Type == TokenType.EndDoc) { context.Transition(States.End, token); return; } throw new Exception("You were making a comment, some profound statement about life or whatever, but then got distracted by fart videos? " + token.Type); } } internal class ELEMENT : HtmlState { public ELEMENT() { } public override void Enter(Token token, HtmlStateMachineGizmo context) { } public override void Accept(Token token, HtmlStateMachineGizmo context) { if (token.Type == TokenType.TagName) { context.Transition(States.Name, token); return; } throw new Exception("I expected to get a Tag Name, but instead I got " + token.Type); } } internal class NAME : HtmlState { public NAME() { } public override void Enter(Token token, HtmlStateMachineGizmo context) { context.TreeBuilder.AddChildElement(token.Value); } public override void Accept(Token token, HtmlStateMachineGizmo context) { if (token.Type == TokenType.AttributeName) { context.Transition(States.Attributes, token); return; } if (token.Type == TokenType.EndTag) { context.Transition(States.Start, token); return; } if (token.Type == TokenType.SelfCloseTag) { context.TreeBuilder.CompleteCurrentElement(); context.Transition(States.Start, token); return; } throw new Exception("I'm sitting here thinking you were going to define a tag, but instead you're doing this: " + token.Type); } } internal class ATTR : HtmlState { private string Name = string.Empty; public ATTR() { } public override void Enter(Token token, HtmlStateMachineGizmo context) { Name = token.Value; context.TreeBuilder.AddAttribute(Name, string.Empty); } public override void Accept(Token token, HtmlStateMachineGizmo context) { if (token.Type == TokenType.AttributeName) { Name = token.Value; context.TreeBuilder.AddAttribute(Name, string.Empty); return; } if (token.Type == TokenType.AttributeValue) { if (Name.Length == 0) { throw new Exception("I think you should try assigning a name to Attribute before giving me a value: " + token.Value); } context.TreeBuilder.AddAttribute(Name, token.Value); Name = string.Empty; return; } if (token.Type == TokenType.EndTag) { context.Transition(States.Start, token); return; } if (token.Type == TokenType.SelfCloseTag) { context.TreeBuilder.CompleteCurrentElement(); context.Transition(States.Start, token); return; } throw new Exception("I was thinking I'd get some Attribute stuff and eventually an End Tag, but instead I got this: " + token.Type); } } internal class TAGDONE : HtmlState { private bool GotTagName = false; private string TagName = string.Empty; public TAGDONE() { } public override void Enter(Token token, HtmlStateMachineGizmo context) { GotTagName= false; TagName = string.Empty; } public override void Accept(Token token, HtmlStateMachineGizmo context) { if (!GotTagName) { if (token.Type == TokenType.TagName) { TagName = token.Value; GotTagName = true; return; } throw new Exception("I was expecting a Tag Name, but I got: " + token.Type); } if (token.Type == TokenType.EndTag) { context.TreeBuilder.CompleteCurrentElement(TagName); context.Transition(States.Start, token); return; } throw new Exception("Are you not going to end your tags properly, with a '>', because, whatever: " + token.Type); } } internal class CODE : HtmlState { public CODE() { } public override void Enter(Token token, HtmlStateMachineGizmo context) { context.TreeBuilder.AddChildText(token.Value); } public override void Accept(Token token, HtmlStateMachineGizmo context) { if (token.Type == TokenType.Code) { context.TreeBuilder.AddChildText(token.Value); return; } if (token.Type == TokenType.EndCode) { context.TreeBuilder.CompleteCurrentElement("script"); context.Transition(States.Start, token); return; } throw new Exception("I was waiting for some Code stuff, but got this crap: " + token.Type); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using CURLcode = Interop.Http.CURLcode; using CURLINFO = Interop.Http.CURLINFO; namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { private static class SslProvider { private static readonly Interop.Http.SslCtxCallback s_sslCtxCallback = SslCtxCallback; private static readonly Interop.Ssl.AppVerifyCallback s_sslVerifyCallback = VerifyCertChain; private static readonly Oid s_serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1"); private static string _sslCaPath; private static string _sslCaInfo; internal static void SetSslOptions(EasyRequest easy, ClientCertificateOption clientCertOption) { EventSourceTrace("ClientCertificateOption: {0}", clientCertOption, easy:easy); Debug.Assert(clientCertOption == ClientCertificateOption.Automatic || clientCertOption == ClientCertificateOption.Manual); // Create a client certificate provider if client certs may be used. X509Certificate2Collection clientCertificates = easy._handler._clientCertificates; ClientCertificateProvider certProvider = clientCertOption == ClientCertificateOption.Automatic ? new ClientCertificateProvider(null) : // automatic clientCertificates?.Count > 0 ? new ClientCertificateProvider(clientCertificates) : // manual with certs null; // manual without certs IntPtr userPointer = IntPtr.Zero; if (certProvider != null) { EventSourceTrace("Created certificate provider", easy:easy); // The client cert provider needs to be passed through to the callback, and thus // we create a GCHandle to keep it rooted. This handle needs to be cleaned up // when the request has completed, and a simple and pay-for-play way to do that // is by cleaning it up in a continuation off of the request. userPointer = GCHandle.ToIntPtr(certProvider._gcHandle); easy.Task.ContinueWith((_, state) => ((IDisposable)state).Dispose(), certProvider, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } // Configure the options. Our best support is when targeting OpenSSL/1.0. For other backends, // we fall back to a minimal amount of support, and may throw a PNSE based on the options requested. if (Interop.Http.HasMatchingOpenSslVersion) { // Register the callback with libcurl. We need to register even if there's no user-provided // server callback and even if there are no client certificates, because we support verifying // server certificates against more than those known to OpenSSL. SetSslOptionsForSupportedBackend(easy, certProvider, userPointer); } else { // Newer versions of OpenSSL, and other non-OpenSSL backends, do not currently support callbacks. // That means we'll throw a PNSE if a callback is required. SetSslOptionsForUnsupportedBackend(easy, certProvider); } } private static void SetSslOptionsForSupportedBackend(EasyRequest easy, ClientCertificateProvider certProvider, IntPtr userPointer) { CURLcode answer = easy.SetSslCtxCallback(s_sslCtxCallback, userPointer); EventSourceTrace("Callback registration result: {0}", answer, easy: easy); switch (answer) { case CURLcode.CURLE_OK: // We successfully registered. If we'll be invoking a user-provided callback to verify the server // certificate as part of that, disable libcurl's verification of the host name; we need to get // the callback from libcurl even if the host name doesn't match, so we take on the responsibility // of doing the host name match in the callback prior to invoking the user's delegate. if (easy._handler.ServerCertificateCustomValidationCallback != null) { easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYHOST, 0); // But don't change the CURLOPT_SSL_VERIFYPEER setting, as setting it to 0 will // cause SSL and libcurl to ignore the result of the server callback. } SetSslOptionsForCertificateStore(easy); // The allowed SSL protocols will be set in the configuration callback. break; case CURLcode.CURLE_UNKNOWN_OPTION: // Curl 7.38 and prior case CURLcode.CURLE_NOT_BUILT_IN: // Curl 7.39 and later SetSslOptionsForUnsupportedBackend(easy, certProvider); break; default: ThrowIfCURLEError(answer); break; } } private static void GetSslCaLocations(out string path, out string info) { // We only provide curl option values when SSL_CERT_FILE or SSL_CERT_DIR is set. // When that is the case, we set the options so curl ends up using the same certificates as the // X509 machine store. path = _sslCaPath; info = _sslCaInfo; if (path == null || info == null) { bool hasEnvironmentVariables = Environment.GetEnvironmentVariable("SSL_CERT_FILE") != null || Environment.GetEnvironmentVariable("SSL_CERT_DIR") != null; if (hasEnvironmentVariables) { path = Interop.Crypto.GetX509RootStorePath(); if (!Directory.Exists(path)) { // X509 store ignores non-existing. path = string.Empty; } info = Interop.Crypto.GetX509RootStoreFile(); if (!File.Exists(info)) { // X509 store ignores non-existing. info = string.Empty; } } else { path = string.Empty; info = string.Empty; } _sslCaPath = path; _sslCaInfo = info; } } private static void SetSslOptionsForCertificateStore(EasyRequest easy) { // Support specifying certificate directory/bundle via environment variables: SSL_CERT_DIR, SSL_CERT_FILE. GetSslCaLocations(out string sslCaPath, out string sslCaInfo); if (sslCaPath != string.Empty) { easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_CAPATH, sslCaPath); // https proxy support requires libcurl 7.52.0+ easy.TrySetCurlOption(Interop.Http.CURLoption.CURLOPT_PROXY_CAPATH, sslCaPath); } if (sslCaInfo != string.Empty) { easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_CAINFO, sslCaInfo); // https proxy support requires libcurl 7.52.0+ easy.TrySetCurlOption(Interop.Http.CURLoption.CURLOPT_PROXY_CAINFO, sslCaInfo); } } private static void SetSslOptionsForUnsupportedBackend(EasyRequest easy, ClientCertificateProvider certProvider) { if (certProvider != null) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_libcurl_clientcerts_notsupported_sslbackend, CurlVersionDescription, CurlSslVersionDescription, Interop.Http.RequiredOpenSslDescription)); } if (easy._handler.CheckCertificateRevocationList) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_libcurl_revocation_notsupported_sslbackend, CurlVersionDescription, CurlSslVersionDescription, Interop.Http.RequiredOpenSslDescription)); } if (easy._handler.ServerCertificateCustomValidationCallback != null) { if (easy.ServerCertificateValidationCallbackAcceptsAll) { EventSourceTrace("Warning: Disabling peer and host verification per {0}", nameof(HttpClientHandler.DangerousAcceptAnyServerCertificateValidator), easy: easy); easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYPEER, 0); easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYHOST, 0); } else { throw new PlatformNotSupportedException(SR.Format(SR.net_http_libcurl_callback_notsupported_sslbackend, CurlVersionDescription, CurlSslVersionDescription, Interop.Http.RequiredOpenSslDescription)); } } else { SetSslOptionsForCertificateStore(easy); } // In case of defaults configure the allowed SSL protocols. SetSslVersion(easy); } private static void SetSslVersion(EasyRequest easy, IntPtr sslCtx = default(IntPtr)) { // Get the requested protocols. SslProtocols protocols = easy._handler.SslProtocols; if (protocols == SslProtocols.None) { // Let libcurl use its defaults if None is set. return; } // libcurl supports options for either enabling all of the TLS1.* protocols or enabling // just one protocol; it doesn't currently support enabling two of the three, e.g. you can't // pick TLS1.1 and TLS1.2 but not TLS1.0, but you can select just TLS1.2. Interop.Http.CurlSslVersion curlSslVersion; switch (protocols) { #pragma warning disable 0618 // SSL2/3 are deprecated case SslProtocols.Ssl2: curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_SSLv2; break; case SslProtocols.Ssl3: curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_SSLv3; break; #pragma warning restore 0618 case SslProtocols.Tls: curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_0; break; case SslProtocols.Tls11: curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_1; break; case SslProtocols.Tls12: curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_2; break; case SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12: curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1; break; default: throw new NotSupportedException(SR.net_securityprotocolnotsupported); } try { easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSLVERSION, (long)curlSslVersion); } catch (CurlException e) when (e.HResult == (int)CURLcode.CURLE_UNKNOWN_OPTION) { throw new NotSupportedException(SR.net_securityprotocolnotsupported, e); } } private static CURLcode SslCtxCallback(IntPtr curl, IntPtr sslCtx, IntPtr userPointer) { EasyRequest easy; if (!TryGetEasyRequest(curl, out easy)) { return CURLcode.CURLE_ABORTED_BY_CALLBACK; } EventSourceTrace(null, easy: easy); // Configure the SSL protocols allowed. SslProtocols protocols = easy._handler.SslProtocols; if (protocols == SslProtocols.None) { // If None is selected, let OpenSSL use its defaults, but with SSL2/3 explicitly disabled. // Since the shim/OpenSSL work on a disabling system, where any protocols for which bits aren't // set are disabled, we set all of the bits other than those we want disabled. #pragma warning disable 0618 // the enum values are obsolete protocols = ~(SslProtocols.Ssl2 | SslProtocols.Ssl3); #pragma warning restore 0618 } Interop.Ssl.SetProtocolOptions(sslCtx, protocols); // Configure the SSL server certificate verification callback. Interop.Ssl.SslCtxSetCertVerifyCallback(sslCtx, s_sslVerifyCallback, curl); // If a client certificate provider was provided, also configure the client certificate callback. if (userPointer != IntPtr.Zero) { try { // Provider is passed in via a GCHandle. Get the provider, which contains // the client certificate callback delegate. GCHandle handle = GCHandle.FromIntPtr(userPointer); ClientCertificateProvider provider = (ClientCertificateProvider)handle.Target; if (provider == null) { Debug.Fail($"Expected non-null provider in {nameof(SslCtxCallback)}"); return CURLcode.CURLE_ABORTED_BY_CALLBACK; } // Register the callback. Interop.Ssl.SslCtxSetClientCertCallback(sslCtx, provider._callback); EventSourceTrace("Registered client certificate callback.", easy: easy); } catch (Exception e) { Debug.Fail($"Exception in {nameof(SslCtxCallback)}", e.ToString()); return CURLcode.CURLE_ABORTED_BY_CALLBACK; } } return CURLcode.CURLE_OK; } private static bool TryGetEasyRequest(IntPtr curlPtr, out EasyRequest easy) { Debug.Assert(curlPtr != IntPtr.Zero, "curlPtr is not null"); IntPtr gcHandlePtr; CURLcode getInfoResult = Interop.Http.EasyGetInfoPointer(curlPtr, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr); if (getInfoResult == CURLcode.CURLE_OK) { return MultiAgent.TryGetEasyRequestFromGCHandle(gcHandlePtr, out easy); } Debug.Fail($"Failed to get info on a completing easy handle: {getInfoResult}"); easy = null; return false; } private static int VerifyCertChain(IntPtr storeCtxPtr, IntPtr curlPtr) { const int SuccessResult = 1, FailureResult = 0; EasyRequest easy; if (!TryGetEasyRequest(curlPtr, out easy)) { EventSourceTrace("Could not find associated easy request: {0}", curlPtr); return FailureResult; } var storeCtx = new SafeX509StoreCtxHandle(storeCtxPtr, ownsHandle: false); try { return VerifyCertChain(storeCtx, easy) ? SuccessResult : FailureResult; } catch (Exception exc) { EventSourceTrace("Unexpected exception: {0}", exc, easy: easy); easy.FailRequest(CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_ABORTED_BY_CALLBACK, exc))); return FailureResult; } finally { storeCtx.Dispose(); } } private static bool VerifyCertChain(SafeX509StoreCtxHandle storeCtx, EasyRequest easy) { IntPtr leafCertPtr = Interop.Crypto.X509StoreCtxGetTargetCert(storeCtx); if (leafCertPtr == IntPtr.Zero) { EventSourceTrace("Invalid certificate pointer", easy: easy); return false; } X509Certificate2[] otherCerts = null; int otherCertsCount = 0; var leafCert = new X509Certificate2(leafCertPtr); try { // We need to respect the user's server validation callback if there is one. If there isn't one, // we can start by first trying to use OpenSSL's verification, though only if CRL checking is disabled, // as OpenSSL doesn't do that. if (easy._handler.ServerCertificateCustomValidationCallback == null && !easy._handler.CheckCertificateRevocationList) { // Start by using the default verification provided directly by OpenSSL. // If it succeeds in verifying the cert chain, we're done. Employing this instead of // our custom implementation will need to be revisited if we ever decide to introduce a // "disallowed" store that enables users to "untrust" certs the system trusts. int sslResult = Interop.Crypto.X509VerifyCert(storeCtx); if (sslResult == 1) { return true; } // X509_verify_cert can return < 0 in the case of programmer error Debug.Assert(sslResult == 0, "Unexpected error from X509_verify_cert: " + sslResult); } // Either OpenSSL verification failed, or there was a server validation callback // or certificate revocation checking was enabled. Either way, fall back to manual // and more expensive verification that includes checking the user's certs (not // just the system store ones as OpenSSL does). using (var chain = new X509Chain()) { chain.ChainPolicy.RevocationMode = easy._handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; using (SafeSharedX509StackHandle extraStack = Interop.Crypto.X509StoreCtxGetSharedUntrusted(storeCtx)) { if (extraStack.IsInvalid) { otherCerts = Array.Empty<X509Certificate2>(); } else { int extraSize = Interop.Crypto.GetX509StackFieldCount(extraStack); otherCerts = new X509Certificate2[extraSize]; for (int i = 0; i < extraSize; i++) { IntPtr certPtr = Interop.Crypto.GetX509StackField(extraStack, i); if (certPtr != IntPtr.Zero) { X509Certificate2 cert = new X509Certificate2(certPtr); otherCerts[otherCertsCount++] = cert; chain.ChainPolicy.ExtraStore.Add(cert); } } } } var serverCallback = easy._handler._serverCertificateValidationCallback; if (serverCallback == null) { SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert, checkCertName: false, hostName: null); // libcurl already verifies the host name return errors == SslPolicyErrors.None; } else { // Authenticate the remote party: (e.g. when operating in client mode, authenticate the server). chain.ChainPolicy.ApplicationPolicy.Add(s_serverAuthOid); SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert, checkCertName: true, hostName: easy._requestMessage.RequestUri.Host); // we disabled automatic host verification, so we do it here return serverCallback(easy._requestMessage, leafCert, chain, errors); } } } finally { for (int i = 0; i < otherCertsCount; i++) { otherCerts[i].Dispose(); } leafCert.Dispose(); } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.WebSites { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for TopLevelDomainsOperations. /// </summary> public static partial class TopLevelDomainsOperationsExtensions { /// <summary> /// Get all top-level domains supported for registration. /// </summary> /// <remarks> /// Get all top-level domains supported for registration. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<TopLevelDomain> List(this ITopLevelDomainsOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Get all top-level domains supported for registration. /// </summary> /// <remarks> /// Get all top-level domains supported for registration. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<TopLevelDomain>> ListAsync(this ITopLevelDomainsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get details of a top-level domain. /// </summary> /// <remarks> /// Get details of a top-level domain. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='name'> /// Name of the top-level domain. /// </param> public static TopLevelDomain Get(this ITopLevelDomainsOperations operations, string name) { return operations.GetAsync(name).GetAwaiter().GetResult(); } /// <summary> /// Get details of a top-level domain. /// </summary> /// <remarks> /// Get details of a top-level domain. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='name'> /// Name of the top-level domain. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<TopLevelDomain> GetAsync(this ITopLevelDomainsOperations operations, string name, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all legal agreements that user needs to accept before purchasing a /// domain. /// </summary> /// <remarks> /// Gets all legal agreements that user needs to accept before purchasing a /// domain. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='name'> /// Name of the top-level domain. /// </param> /// <param name='agreementOption'> /// Domain agreement options. /// </param> public static IPage<TldLegalAgreement> ListAgreements(this ITopLevelDomainsOperations operations, string name, TopLevelDomainAgreementOption agreementOption) { return operations.ListAgreementsAsync(name, agreementOption).GetAwaiter().GetResult(); } /// <summary> /// Gets all legal agreements that user needs to accept before purchasing a /// domain. /// </summary> /// <remarks> /// Gets all legal agreements that user needs to accept before purchasing a /// domain. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='name'> /// Name of the top-level domain. /// </param> /// <param name='agreementOption'> /// Domain agreement options. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<TldLegalAgreement>> ListAgreementsAsync(this ITopLevelDomainsOperations operations, string name, TopLevelDomainAgreementOption agreementOption, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAgreementsWithHttpMessagesAsync(name, agreementOption, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get all top-level domains supported for registration. /// </summary> /// <remarks> /// Get all top-level domains supported for registration. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<TopLevelDomain> ListNext(this ITopLevelDomainsOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Get all top-level domains supported for registration. /// </summary> /// <remarks> /// Get all top-level domains supported for registration. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<TopLevelDomain>> ListNextAsync(this ITopLevelDomainsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all legal agreements that user needs to accept before purchasing a /// domain. /// </summary> /// <remarks> /// Gets all legal agreements that user needs to accept before purchasing a /// domain. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<TldLegalAgreement> ListAgreementsNext(this ITopLevelDomainsOperations operations, string nextPageLink) { return operations.ListAgreementsNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all legal agreements that user needs to accept before purchasing a /// domain. /// </summary> /// <remarks> /// Gets all legal agreements that user needs to accept before purchasing a /// domain. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<TldLegalAgreement>> ListAgreementsNextAsync(this ITopLevelDomainsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAgreementsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using System.Threading; using System.Globalization; /// <summary> /// System.DateTime.Kind /// </summary> public class DateTimeKind { public static int Main(string[] args) { DateTimeKind kind = new DateTimeKind(); TestLibrary.TestFramework.BeginScenario("Testing System.DateTime.Kind property..."); if (kind.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Check Kind property when create an instance using Utc..."); try { TestLibrary.Utilities.CurrentCulture = new CultureInfo(""); DateTime myDateTime = new DateTime(1978, 08, 29, 03, 00, 00, System.DateTimeKind.Utc); if (myDateTime.Kind != System.DateTimeKind.Utc) { TestLibrary.TestFramework.LogError("001", "The kind is wrong!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception occurs: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Check Kind property when create an instance using local..."); try { TestLibrary.Utilities.CurrentCulture = new CultureInfo(""); DateTime myDateTime = new DateTime(1978, 08, 29, 03, 00, 00, System.DateTimeKind.Local); if (myDateTime.Kind != System.DateTimeKind.Local) { TestLibrary.TestFramework.LogError("003", "The kind is wrong!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception occurs: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Check Kind property when create an instance using Unspecified..."); try { TestLibrary.Utilities.CurrentCulture = new CultureInfo(""); DateTime myDateTime = new DateTime(1978, 08, 29, 03, 00, 00, System.DateTimeKind.Unspecified); if (myDateTime.Kind != System.DateTimeKind.Unspecified) { TestLibrary.TestFramework.LogError("005", "The kind is wrong!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception occurs: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Check toUniversalTime is equal to original when create an instance using Utc..."); try { TestLibrary.Utilities.CurrentCulture = new CultureInfo(""); DateTime myDateTime = new DateTime(1978, 08, 29, 03, 00, 00, System.DateTimeKind.Utc); DateTime toUniversal = myDateTime.ToUniversalTime(); if (myDateTime != toUniversal) { TestLibrary.TestFramework.LogError("007", "The two instances are not equal!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception occurs: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Check toLocalTime is equal to original when create an instance using local..."); try { TestLibrary.Utilities.CurrentCulture = new CultureInfo(""); DateTime myDateTime = new DateTime(1978, 08, 29, 03, 00, 00, System.DateTimeKind.Local); DateTime toLocal = myDateTime.ToLocalTime(); if (myDateTime != toLocal) { TestLibrary.TestFramework.LogError("009", "The kind is wrong!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception occurs: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Check an instance created by Unspecified, then compare to local and universal..."); try { if (TimeZoneInfo.Local.BaseUtcOffset == TimeSpan.Zero) // any TZ has same alignment with UTC { // if we are on UTC zone, then the following test wil not make sense because all date conversion will produce the same original date value return retVal; } TestLibrary.Utilities.CurrentCulture = new CultureInfo(""); DateTime myDateTime = new DateTime(1978, 08, 29, 03, 00, 00, System.DateTimeKind.Unspecified); DateTime toLocal = myDateTime.ToLocalTime(); DateTime toUniversal = myDateTime.ToUniversalTime(); if (myDateTime == toLocal) { string errorMessage = String.Format("The Unspecified myDateTime is regard as local by default!\nTZ: '{0}'\nmyDateTime: '{1}'\ntoLocal: '{2}'", TimeZoneInfo.Local.DisplayName, myDateTime, toLocal); TestLibrary.TestFramework.LogError("011", errorMessage); retVal = false; } else if (myDateTime == toUniversal) { string errorMessage = String.Format("Unexpected exception occurs!\nTZ: '{0}'\nmyDateTime: '{1}'\ntoUniversal: '{2}'", TimeZoneInfo.Local.DisplayName, myDateTime, toUniversal); TestLibrary.TestFramework.LogError("012", errorMessage); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("013", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } }
// Images.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using System.Collections.Generic; using System.Text; // - Using using System.Collections; using System.Diagnostics; using System.Xml.Serialization; using System.IO; using System.Windows.Forms; using System.Drawing; using System.ComponentModel; using System.Globalization; using System.ComponentModel.Design.Serialization; using System.Text.RegularExpressions; using System.Data; using System.Reflection; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using System.Drawing.Text; namespace CoreUtilities { public static partial class General { //////////////////////////////////////////////////////////////////// // // Image Handling // //////////////////////////////////////////////////////////////////// /// <summary> /// returns true if the extension for sFile matches a list of possible file names /// </summary> /// <param name="sFile"></param> /// <returns></returns> static public bool IsGraphicFile(string sFile) { if (sFile == null) { throw new Exception("You are attempting to test IsGraphicFile but you passed null to it."); } sFile = sFile.ToLower(); if (sFile.IndexOf(".png") > -1 || sFile.IndexOf(".jpg") > -1 || sFile.IndexOf(".jpeg") > -1 || sFile.IndexOf(".bmp") > -1 || sFile.IndexOf(".gif") > -1) { return true; } return false; } /// <summary> /// Return the available image encoders /// http://www.codeproject.com/KB/cs/BuildWatermarkUtility.aspx /// </summary> /// <param name="mimeType"></param> /// <returns></returns> private static ImageCodecInfo GetEncoderInfo(String mimeType) { int j; ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; } /// <summary> /// for use with IdeaRiver, a collection of smartpoints so /// we know where we are clicking /// </summary> public struct smartpoint { public int x; public int width; public int y; public int height; public string sLink; public bool bExtra; // extra info, like for usage in Idea Flow brainstorming public int nSpeed; //extra for idea flow } /// <summary> /// /// </summary> /// <param name="sSource"></param> /// <param name="nWidth"></param> /// <param name="nLines"></param> /// <returns></returns> public static string ReformatStringForWidth(string sSource, int nWidth) { return ReformatStringForWidth(sSource, nWidth, -1); } /// <summary> /// Goes through sSource and inserts \r\n at the specified widht. Every nWidth /// characters. This iwll allow it to be passed into CreateBitMapImageFromText with nicer results /// </summary> /// <param name="sSource"></param> /// <param name="nLines">if not -1 will only parse this many lines</param> /// /// <returns></returns> public static string ReformatStringForWidth(string sSource, int nWidth, int nLines) { string sNew = ""; if (sSource == null) { throw new Exception("ReformatStringForWidth sSource was null"); } int nCount = 0; for (int i = 0; i < sSource.Length; i++) { nCount++; if (nCount == nWidth) { sNew = sNew + "\r\n"; nCount = 0; } sNew = sNew + sSource[i]; if (nLines != -1 && nCount >= nLines) { break; } } return sNew; } /// <summary> /// Creates a bitmap from text /// http://chiragrdarji.wordpress.com/2008/05/09/generate-image-from-text-using-c-or-convert-text-in-to-image-using-c/ /// </summary> /// <param name="sImageText"></param> /// <param name="sTitle"></param> /// <param name="style">What should it look like?</param> /// <param name="nLength">How much text to show, -1 means full length</param> /// <returns></returns> public static Bitmap CreateBitmapImageFromText(string sTitle, string sImageText, FromTextStyles style, int nLength, TextToImageAppearance appearance, Image backImage) { if (sTitle == null || sImageText == null) { throw new Exception("Create Bitmap IMage from text You must supply both text and a title"); } // truncate text based on limit if (nLength != -1) { if (nLength > sImageText.Length) { nLength = sImageText.Length; } sImageText = sImageText.Substring(0, nLength); } Bitmap objBmpImage = new Bitmap(1, 1); int intWidth = 0; int intHeight = 0; Color background = Color.Black; Color textcolor = Color.Black; Font objFont = null; Font titleFont = null; // appearance is passed in if (appearance == null) { appearance = new TextToImageAppearance(); } appearance.Set(style); objFont = new Font(appearance.MainTextFont, appearance.MainTextFont.Style); titleFont = new Font(appearance.TitleFont, appearance.TitleFont.Style); background = appearance.BackgroundColor; textcolor = appearance.TextColor; if (objFont == null || titleFont == null) { //Logs.Line("GeneralImage.CreateBitmapImageFromText", "FromText font null","", Logs.CRITICAL); lg.Instance.Line("CreateBitMapImageFromText", ProblemType.WARNING, "FromText font null"); return null; } // Create the Font object for the image text drawing. // Create a graphics object to measure the text's width and height. Graphics objGraphics = Graphics.FromImage(objBmpImage); // This is where the bitmap size is determined. intWidth = Math.Max((int)objGraphics.MeasureString(sImageText, objFont).Width, ((int)objGraphics.MeasureString(sTitle, titleFont).Width)); intHeight = ((int)objGraphics.MeasureString(sImageText, objFont).Height) + ((int)objGraphics.MeasureString(sTitle, titleFont).Height); // Create the bmpImage again with the correct size for the text and font. objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight)); // Add the colors to the new bitmap. objGraphics = Graphics.FromImage(objBmpImage); // Set Background color objGraphics.Clear(background); /* Gradient Test */ if (backImage != null) { // ImageAttributes attr = new ImageAttributes(); // attr. objGraphics.DrawImage(backImage, 0, 0, intWidth, intHeight); } else //back image is mutually exclusive with gradient if (appearance.IsGradient == true) { // Create a diagonal linear gradient with four stops. Rectangle rect = new Rectangle(0, 0, intWidth, intHeight); Color gradientColorOne = appearance.GradientColor1; Color gradientColorTwo = appearance.GradientColor2; // Dispose of brush resources after use using (LinearGradientBrush lgb = new LinearGradientBrush(rect, gradientColorOne, gradientColorTwo, appearance.mLinearGradientMode)) objGraphics.FillRectangle(lgb, rect); } /* end gradient test*/ objGraphics.SmoothingMode = SmoothingMode.AntiAlias; objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias; objGraphics.DrawString(sTitle, titleFont, new SolidBrush(appearance.TitleColor), 0, 0); // put the body of the text below the title objGraphics.DrawString(sImageText, objFont, new SolidBrush(textcolor), 0, ((int)objGraphics.MeasureString(sTitle, titleFont).Height)); objGraphics.Flush(); return (objBmpImage); } /// <summary> /// simpler wrapper /// </summary> /// <param name="imageSource"></param> /// <param name="frameColor"></param> /// <param name="nFramewidth"></param> /// <returns></returns> public static Image AddFrameToImage(Image imageSource, Color frameColor, int nFramewidth) { return AddFrameToImage(imageSource, frameColor, nFramewidth, nFramewidth, nFramewidth, nFramewidth, false, Color.White); } /// <summary> /// Returns am odified image with the Frame specified around it /// </summary> /// <param name="imageSource"></param> /// <returns></returns> public static Image AddFrameToImage(Image imageSource, Color frameColor, int nTopWidth, int nLeftWidth, int nRightWidth, int nBottomWidth, bool bGradient, Color gradientColor) { if (imageSource == null) { throw new Exception("AddFrame - imageSource was null"); } Bitmap bmp = new Bitmap(imageSource); Graphics frame = Graphics.FromImage(bmp); try { LinearGradientBrush lgb = null; Pen pen = null; if (bGradient == true) { lgb = new LinearGradientBrush( new Rectangle(0, 0, nLeftWidth * 2, bmp.Height), frameColor, gradientColor, LinearGradientMode.ForwardDiagonal); pen = new Pen(lgb, nLeftWidth * 2); } else { pen = new Pen(frameColor, nLeftWidth * 2); } frame.DrawLine(pen, 0, 0, 0, bmp.Height); // LEFT if (bGradient == true) { lgb = new LinearGradientBrush( new Rectangle(0, 0, bmp.Width, nTopWidth * 2), frameColor, gradientColor, LinearGradientMode.ForwardDiagonal); pen = new Pen(lgb, nTopWidth * 2); } else { pen = new Pen(frameColor, nTopWidth * 2); } frame.DrawLine(pen, 0, 0, bmp.Width, 0); // BOTTOM if (bGradient == true) { lgb = new LinearGradientBrush( new Rectangle(bmp.Width - nRightWidth, 0, bmp.Width-nRightWidth, bmp.Height), frameColor, gradientColor, LinearGradientMode.ForwardDiagonal); pen = new Pen(lgb,nRightWidth * 2); } else { pen = new Pen(frameColor, nRightWidth * 2); } //pen = new Pen(frameColor, nRightWidth * 2); frame.DrawLine(pen, bmp.Width, 0, bmp.Width, bmp.Height); // RIGHT if (bGradient == true) { lgb = new LinearGradientBrush( new Rectangle(0, bmp.Height-nBottomWidth, bmp.Width, bmp.Height), frameColor, gradientColor, LinearGradientMode.ForwardDiagonal); pen = new Pen(lgb, nBottomWidth * 2); } else { pen = new Pen(frameColor, nBottomWidth * 2); } frame.DrawLine(pen, 0, bmp.Height, bmp.Width, bmp.Height); // TOP } catch (Exception ex) { CoreUtilities.NewMessage.Show(ex.ToString()); } frame.Dispose(); return bmp; } /// <summary> /// Resize with no padding /// </summary> /// <param name="img"></param> /// <param name="percentage"></param> /// <returns></returns> public static Image ResizeImage(Image img, float percentage) { // resize with no padding return ResizeImage(img, percentage,percentage, 0,0,0,0,Color.White); } /// <summary> /// method for resizing an image /// </summary> /// <param name="img">the image to resize</param> /// <param name="percentage">Percentage of change (i.e for 105% of the original provide 105)</param> /// <param name="nPadding">padding is for frames</param> /// <returns></returns> public static Image ResizeImage(Image img, float widthpercentage, float heighpercentage, /*int nPadding, */ int nLeftPad, int nTopPad, int nBottomPad, int nRightPad, Color backColor) { //get the height and width of the image int originalW = img.Width; int originalH = img.Height; //get the new size based on the percentage change /* int resizedW = (int)(originalW * percentage);// +(nPadding * 2); int resizedH = (int)(originalH * percentage);// +(nPadding * 2); */ int resizedW = (int)(originalW * widthpercentage);// +(nPadding * 2); int resizedH = (int)(originalH * heighpercentage);// +(nPadding * 2); //create a new Bitmap the size of the new image Bitmap bmp = new Bitmap(resizedW, resizedH); //create a new graphic from the Bitmap Graphics graphic = Graphics.FromImage((Image)bmp); graphic.InterpolationMode = InterpolationMode.HighQualityBilinear; //draw the newly resized image // Brent added this to introduce padding for the frame graphic.Clear(Color.Pink); /* graphic.DrawImage(img, nPadding / 2, nPadding / 2, resizedW - nPadding, resizedH - nPadding);*/ /* int nLeftPad = 100; int nTopPad = 10; int nRightPad = 20; int nBottomPad = 30;*/ graphic.DrawImage(img, nLeftPad, nTopPad, originalW/* - ((nLeftPad + nRightPad)/2)*/, originalH /*- ((nTopPad + nBottomPad)/2*/ ); /* resizedW - nLeftPad - nRightPad, resizedH - nTopPad - nBottomPad); */ //dispose and free up the resources graphic.Dispose(); //return the image return (Image)bmp; } /// <summary> /// Creates a new Image containing the same image only rotated /// /// http://www.opensource.org/licenses/bsd-license.php /// /// </summary> /// <param name="image">The <see cref="System.Drawing.Image"/> to rotate</param> /// <param name="angle">The amount to rotate the image, clockwise, in degrees</param> /// <returns>A new <see cref="System.Drawing.Bitmap"/> that is just large enough /// to contain the rotated image without cutting any corners off.</returns> /// <exception cref="System.ArgumentNullException">Thrown if <see cref="image"/> is null.</exception> public static Bitmap RotateImageImproved(Image image, float angle) { if (image == null) throw new ArgumentNullException("image"); const double pi2 = Math.PI / 2.0; // Why can't C# allow these to be const, or at least readonly // *sigh* I'm starting to talk like Christian Graus :omg: double oldWidth = (double)image.Width; double oldHeight = (double)image.Height; // Convert degrees to radians double theta = ((double)angle) * Math.PI / 180.0; double locked_theta = theta; // Ensure theta is now [0, 2pi) while (locked_theta < 0.0) locked_theta += 2 * Math.PI; double newWidth, newHeight; int nWidth, nHeight; // The newWidth/newHeight expressed as ints #region Explaination of the calculations /* * The trig involved in calculating the new width and height * is fairly simple; the hard part was remembering that when * PI/2 <= theta <= PI and 3PI/2 <= theta < 2PI the width and * height are switched. * * When you rotate a rectangle, r, the bounding box surrounding r * contains for right-triangles of empty space. Each of the * triangles hypotenuse's are a known length, either the width or * the height of r. Because we know the length of the hypotenuse * and we have a known angle of rotation, we can use the trig * function identities to find the length of the other two sides. * * sine = opposite/hypotenuse * cosine = adjacent/hypotenuse * * solving for the unknown we get * * opposite = sine * hypotenuse * adjacent = cosine * hypotenuse * * Another interesting point about these triangles is that there * are only two different triangles. The proof for which is easy * to see, but its been too long since I've written a proof that * I can't explain it well enough to want to publish it. * * Just trust me when I say the triangles formed by the lengths * width are always the same (for a given theta) and the same * goes for the height of r. * * Rather than associate the opposite/adjacent sides with the * width and height of the original bitmap, I'll associate them * based on their position. * * adjacent/oppositeTop will refer to the triangles making up the * upper right and lower left corners * * adjacent/oppositeBottom will refer to the triangles making up * the upper left and lower right corners * * The names are based on the right side corners, because thats * where I did my work on paper (the right side). * * Now if you draw this out, you will see that the width of the * bounding box is calculated by adding together adjacentTop and * oppositeBottom while the height is calculate by adding * together adjacentBottom and oppositeTop. */ #endregion double adjacentTop, oppositeTop; double adjacentBottom, oppositeBottom; // We need to calculate the sides of the triangles based // on how much rotation is being done to the bitmap. // Refer to the first paragraph in the explaination above for // reasons why. if ((locked_theta >= 0.0 && locked_theta < pi2) || (locked_theta >= Math.PI && locked_theta < (Math.PI + pi2))) { adjacentTop = Math.Abs(Math.Cos(locked_theta)) * oldWidth; oppositeTop = Math.Abs(Math.Sin(locked_theta)) * oldWidth; adjacentBottom = Math.Abs(Math.Cos(locked_theta)) * oldHeight; oppositeBottom = Math.Abs(Math.Sin(locked_theta)) * oldHeight; } else { adjacentTop = Math.Abs(Math.Sin(locked_theta)) * oldHeight; oppositeTop = Math.Abs(Math.Cos(locked_theta)) * oldHeight; adjacentBottom = Math.Abs(Math.Sin(locked_theta)) * oldWidth; oppositeBottom = Math.Abs(Math.Cos(locked_theta)) * oldWidth; } newWidth = adjacentTop + oppositeBottom; newHeight = adjacentBottom + oppositeTop; nWidth = (int)Math.Ceiling(newWidth); nHeight = (int)Math.Ceiling(newHeight); Bitmap rotatedBmp = new Bitmap(nWidth, nHeight); using (Graphics g = Graphics.FromImage(rotatedBmp)) { // This array will be used to pass in the three points that // make up the rotated image Point[] points; /* * The values of opposite/adjacentTop/Bottom are referring to * fixed locations instead of in relation to the * rotating image so I need to change which values are used * based on the how much the image is rotating. * * For each point, one of the coordinates will always be 0, * nWidth, or nHeight. This because the Bitmap we are drawing on * is the bounding box for the rotated bitmap. If both of the * corrdinates for any of the given points wasn't in the set above * then the bitmap we are drawing on WOULDN'T be the bounding box * as required. */ if (locked_theta >= 0.0 && locked_theta < pi2) { points = new Point[] { new Point( (int) oppositeBottom, 0 ), new Point( nWidth, (int) oppositeTop ), new Point( 0, (int) adjacentBottom ) }; } else if (locked_theta >= pi2 && locked_theta < Math.PI) { points = new Point[] { new Point( nWidth, (int) oppositeTop ), new Point( (int) adjacentTop, nHeight ), new Point( (int) oppositeBottom, 0 ) }; } else if (locked_theta >= Math.PI && locked_theta < (Math.PI + pi2)) { points = new Point[] { new Point( (int) adjacentTop, nHeight ), new Point( 0, (int) adjacentBottom ), new Point( nWidth, (int) oppositeTop ) }; } else { points = new Point[] { new Point( 0, (int) adjacentBottom ), new Point( (int) oppositeBottom, 0 ), new Point( (int) adjacentTop, nHeight ) }; } g.DrawImage(image, points); } if (image.Tag != null) { rotatedBmp.Tag = image.Tag; } return rotatedBmp; } /// <summary> /// Retrieves an embedded resource /// </summary> /// <param name="sResourceID">i.e., "MyNamespace.Resources.MyImage.bmp" /// General.GetImageFromResource("CoreUtilities.Resources.corksource5.jpg");</param> /// <returns></returns> public static Image GetImageFromResource(Assembly _assembly, string sResourceID) { if (sResourceID == null || sResourceID == "") { throw new Exception("GetImageFromResource sResourceID was null or blank."); } // Assembly _assembly; Stream _imageStream; lg.Instance.Line("GeneralImages.GetImageFromResource", ProblemType.MESSAGE,String.Format (" retrieve image {0}", sResourceID)); try { // _assembly = Assembly.GetExecutingAssembly(); if (_assembly != null) { _imageStream = _assembly.GetManifestResourceStream(sResourceID); if (_imageStream != null) { Image i = new Bitmap(_imageStream); if (i != null) { return i; } else { lg.Instance.Line("GeneralImages.GetImageFromResource", ProblemType.WARNING,"image was null"); } } else { lg.Instance.Line("GeneralImages.GetImageFromResource",ProblemType.WARNING, String.Format (" _imageStream was null for >< {0}", sResourceID)); } } } catch (Exception ex) { lg.Instance.Line("GetImageFromResource", ProblemType.EXCEPTION, ex.ToString()); } return null; } //////////////////////////////////////////////////////////////////////// // // TextToImageAPpearance // // //////////////////////////////////////////////////////////////////////// /// <summary> /// Predefined styles. Each will correspond to an embedded Appearance Object (eventually) /// </summary> public enum FromTextStyles { NEWSPAPER = 0, NOTEPAD = 1, CUSTOM = 2, PAPER = 3, BLUETAG = 4, POLAROID =5, JUSTGRADIENT=6, CORK=7 } /// <summary> /// this class defines the parameters that can be used to tweak the look /// for text that is converted into an image. /// /// Original usage: IdeaRiver /// - /// </summary> public class TextToImageAppearance : Object { private Font titleFont; private Font mainTextFont; // main text font private Color backgroundColor; private Color textcolor; private int leftWidth, topWidth, bottomWidth, rightWidth, resizeWidth; private Color frameColor; private bool isGradient; private Color gradientColor1; private Color gradientColor2; private LinearGradientMode mlinearGradientMode; private Color frameGradient; private string backImageResourceName; /// <summary> /// sets up some default values /// </summary> public TextToImageAppearance() { titleFont = new Font("Times", 12); mainTextFont = new Font("Times", 10); backgroundColor = Color.Blue; textcolor = Color.BlanchedAlmond; frameColor = Color.DarkGray; leftWidth = 10; topWidth = 10; bottomWidth = 10; rightWidth = 10; resizeWidth = 10; isGradient = false; backImageResourceName = ""; } /// <summary> /// If defined represents an internal ID to an embedded graphics resource /// </summary> public string BackImageResourceName { get { return backImageResourceName; } set { backImageResourceName = value; } } /// <summary> /// if gradient set to true frame can have gradient too /// </summary> public Color FrameGradient { get { return frameGradient; } set { frameGradient = value; } } /// <summary> /// if true will attempt to paint a linear gradient /// </summary> public bool IsGradient { get { return isGradient; } set { isGradient = value; } } public LinearGradientMode mLinearGradientMode { get { return mlinearGradientMode; } set { mlinearGradientMode = value; } } public Color GradientColor1 { get { return gradientColor1; } set { gradientColor1 = value; } } public Color GradientColor2 { get { return gradientColor2; } set { gradientColor2 = value; } } /// <summary> /// the color of the frame around the image /// </summary> public Color FrameColor { get { return frameColor; } set {frameColor = value;} } /// <summary> /// rectangle defining the thicnkness of a the frame /// </summary> public int LeftWidth { get {return leftWidth;} set { leftWidth = value; } } /// <summary> /// rectangle defining the thicnkness of a the frame /// </summary> public int RightWidth { get { return rightWidth; } set { rightWidth = value; } } /// <summary> /// rectangle defining the thicnkness of a the frame /// </summary> public int TopWidth { get { return topWidth; } set { topWidth = value; } } /// <summary> /// rectangle defining the thicnkness of a the frame /// </summary> public int BottomWidth { get { return bottomWidth; } set { bottomWidth = value; } } /// <summary> /// This is the width of the resizing to use when creating /// panning in the image before applying the frame. /// /// To-Do: This may need seperate x,y,width,height params (CANT WE JUST USE OTHER DIMS?) /// </summary> public int ResizeWidth { get { return resizeWidth; } set { resizeWidth = value; } } public Font TitleFont { get { return titleFont; } set { titleFont = new Font(value, value.Style); } } public Font MainTextFont { get { return mainTextFont; } set { mainTextFont = new Font(value, value.Style); } } public Color BackgroundColor { get { return backgroundColor; } set { backgroundColor = (value); } } public Color TextColor { get { return textcolor; } set { textcolor = (value); } } private Color titleColor; public Color TitleColor { get { return titleColor; } set { titleColor = value; } } /// <summary> /// override ToString for this object type /// </summary> /// <returns></returns> public override string ToString() { string sOut = "this.TitleFont = new Font(\"{0}\", 24, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);\r\n" + "this.BackgroundColor = Color.FromArgb({1});\r\n" + "this.TextColor = Color.FromArgb({2});\r\n" + "this.MainTextFont = new Font(\"{3}\", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);\r\n" + "this.TitleColor = Color.FromArgb({4});\r\n" + "this.FrameColor = Color.FromArgb({5});\r\n" + "this.LeftWidth = {6};\r\n" +"this.TopWidth = {7};\r\n" +"this.BottomWidth = {8};\r\n" +"this.RightWidth = {9};\r\n" +"this.ResizeWidth = {10};\r\n" + "this.IsGradient = {11};\r\n" + "this.GradientColor1 = Color.FromArgb({12});\r\n" + "this.GradientColor2 = Color.FromArgb({13});\r\n" + "this.mLinearGradientMode = LinearGradientMode.{14};\r\n" + "this.frameGradient = Color.FromArgb({15});\r\n" ; sOut = String.Format(sOut, this.TitleFont.Name, backgroundColor.ToArgb().ToString(), textcolor.ToArgb().ToString(), this.MainTextFont.Name, titleColor.ToArgb(), FrameColor.ToArgb(), leftWidth, topWidth, bottomWidth, rightWidth, resizeWidth, IsGradient.ToString().ToLower(), GradientColor1.ToArgb(), GradientColor2.ToArgb(), mLinearGradientMode.ToString(), frameGradient.ToArgb()); return sOut; } /// <summary> /// Creates a text image box, for IdeaRiver, and returns an image /// /// Assumes that formatting setup has already occured /// i.e., app = new General.TextToImageAppearance( /// (General.TextToImageAppearance)propertyGrid1.SelectedObject); /// </summary> /// <param name="sTitle"></param> /// <param name="sText"></param> /// <param name="nWidth"></param> /// <param name="nHeight"></param> /// <param name="AffectText">if true it will try to format text pretty</param> /// <returns></returns> public Image CreateFancyImage(string sTitle, string sText, int nWidth, int nHeight, Image backImage, bool AffectText) { if (true == AffectText) { sText = General.ReformatStringForWidth(sText, nWidth, nHeight); } Image i = null; if (backImage != null) { //overriding background image with user passed in i = backImage; } else if (BackImageResourceName != "") { // some appearance types like Cork pull an embedded resource // to display it i = General.GetImageFromResource(Assembly.GetExecutingAssembly(), BackImageResourceName); } try { i = CoreUtilities.General.CreateBitmapImageFromText(sTitle, sText, (CoreUtilities.General.FromTextStyles.CUSTOM), nHeight, this, i); // now resize to prepare for adding a frame // we need to calculate teh area difference between the old image and // the new image. /* float OriginalArea = i.Height * i.Width; float ModifiedArea = (i.Width + (this.LeftWidth + this.RightWidth)) * (i.Height + (this.TopWidth + this.BottomWidth)); float fPercentWidthDifference = (ModifiedArea / OriginalArea); * Logs.LineF("CreateFancyImage {0} percent difference between new/old areas {1}/{2}", fPercentDifference, ModifiedArea, OriginalArea); */ float fPercentWidthDifference = (float)(i.Width + this.LeftWidth + this.RightWidth) / (float)i.Width; if (fPercentWidthDifference < 1.0f) fPercentWidthDifference = 1.0f; float fPercentHeighDifference = (float)(i.Height + this.TopWidth + this.BottomWidth) / (float)i.Height; if (fPercentHeighDifference < 1.0f) fPercentHeighDifference = 1.0f; i = CoreUtilities.General.ResizeImage(i, fPercentWidthDifference, fPercentHeighDifference/*1.10f*/, leftWidth, topWidth, bottomWidth, rightWidth, frameColor); // Padding should match the padding of the frame, likewise the colors i = CoreUtilities.General.AddFrameToImage(i, frameColor, topWidth, leftWidth, rightWidth, bottomWidth, IsGradient, frameGradient); } catch (Exception) { lg.Instance.Line("GeneralImages.CreateFancyImage", ProblemType.EXCEPTION, "CreateFancyImage ERROR with creating image"); } return i; } /// <summary> /// sets the appearance to a predefined style /// </summary> /// <param name="style"></param> public TextToImageAppearance Set(FromTextStyles style) { try { switch (style) { case FromTextStyles.NEWSPAPER: { this.TitleFont = new Font("Arial", 24, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel); this.BackgroundColor = Color.FromArgb(-2302756); this.TextColor = Color.FromArgb(-10066330); this.MainTextFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel); this.TitleColor = Color.FromArgb(-10066330); this.FrameColor = Color.FromArgb(-657931); this.LeftWidth = 5; this.TopWidth = 5; this.BottomWidth = 5; this.RightWidth = 5; this.ResizeWidth = 5; this.IsGradient = true; this.GradientColor1 = Color.FromArgb(-657931); this.GradientColor2 = Color.FromArgb(-2302756); this.mLinearGradientMode = LinearGradientMode.ForwardDiagonal; this.frameGradient = Color.FromArgb(-2039584); } break; case FromTextStyles.NOTEPAD: { this.TitleFont = new Font("Arial", 24, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel); this.BackgroundColor = Color.FromArgb(-256); this.TextColor = Color.FromArgb(-16777216); this.MainTextFont = new Font("Microsoft Sans Serif", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel); this.TitleColor = Color.FromArgb(-16777216); this.FrameColor = Color.FromArgb(-256); this.LeftWidth = 1; this.TopWidth = 1; this.BottomWidth = 1; this.RightWidth = 1; this.ResizeWidth = 1; this.IsGradient = true; this.GradientColor1 = Color.FromArgb(-32); this.GradientColor2 = Color.FromArgb(-256); this.mLinearGradientMode = LinearGradientMode.ForwardDiagonal; } break; case FromTextStyles.PAPER: { BackImageResourceName = "CoreUtilities.Resources.lined4.jpg"; this.TitleFont = new Font("Monotype Corsiva", 24, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Pixel); this.BackgroundColor = Color.FromArgb(16777215); this.TextColor = Color.FromArgb(-12490271); this.MainTextFont = new Font("Monotype Corsiva", 20, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Pixel); this.TitleColor = Color.FromArgb(-16777088); this.FrameColor = Color.FromArgb(-16777216); this.LeftWidth = 1; this.TopWidth = 1; this.BottomWidth = 1; this.RightWidth = 1; this.ResizeWidth = 10; this.IsGradient = false; this.GradientColor1 = Color.FromArgb(0); this.GradientColor2 = Color.FromArgb(0); this.mLinearGradientMode = LinearGradientMode.Horizontal; this.frameGradient = Color.FromArgb(0); } break; case FromTextStyles.BLUETAG: { this.TitleFont = new Font("Arial", 24, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel); this.BackgroundColor = Color.FromArgb(-657931); this.TextColor = Color.FromArgb(-657931); this.MainTextFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel); this.TitleColor = Color.FromArgb(-7876885); this.FrameColor = Color.FromArgb(-15132304); this.LeftWidth = 30; this.TopWidth = 1; this.BottomWidth = 1; this.RightWidth = 1; this.ResizeWidth = 1; this.IsGradient = true; this.GradientColor1 = Color.FromArgb(-16777216); this.GradientColor2 = Color.FromArgb(-15132304); this.mLinearGradientMode = LinearGradientMode.Horizontal; this.frameGradient = Color.FromArgb(-10185235); } break; case FromTextStyles.POLAROID: { this.TitleFont = new Font("Arial", 24, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel); this.BackgroundColor = Color.FromArgb(-1); this.TextColor = Color.FromArgb(-657931); this.MainTextFont = new Font("Times New Roman", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel); this.TitleColor = Color.FromArgb(-657931); this.FrameColor = Color.FromArgb(-657931); this.LeftWidth = 5; this.TopWidth = 10; this.BottomWidth = 50; this.RightWidth = 5; this.ResizeWidth = 10; this.IsGradient = true; this.GradientColor1 = Color.FromArgb(-16777216); this.GradientColor2 = Color.FromArgb(-9868951); this.mLinearGradientMode = LinearGradientMode.Horizontal; this.frameGradient = Color.FromArgb(-657931); } break; case FromTextStyles.JUSTGRADIENT: { this.TitleFont = new Font("Arial", 24, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel); this.BackgroundColor = Color.FromArgb(-657931); this.TextColor = Color.FromArgb(-657931); this.MainTextFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel); this.TitleColor = Color.FromArgb(-7876885); this.FrameColor = Color.FromArgb(-15132304); this.LeftWidth = 40; this.TopWidth = 10; this.BottomWidth = 10; this.RightWidth = 10; this.ResizeWidth = 1; this.IsGradient = true; this.GradientColor1 = Color.FromArgb(-16777216); this.GradientColor2 = Color.FromArgb(-15132304); this.mLinearGradientMode = LinearGradientMode.Horizontal; this.frameGradient = Color.FromArgb(-32640); } break; case FromTextStyles.CORK: { this.TitleFont = new Font("Times New Roman", 24, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel); this.BackgroundColor = Color.FromArgb(-16776961); this.TextColor = Color.FromArgb(-5171); this.MainTextFont = new Font("Trebuchet MS", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel); this.TitleColor = Color.FromArgb(-2039584); this.FrameColor = Color.FromArgb(-16777216); this.LeftWidth = 1; this.TopWidth = 1; this.BottomWidth = 1; this.RightWidth = 1; this.ResizeWidth = 10; this.IsGradient = false; this.GradientColor1 = Color.FromArgb(0); this.GradientColor2 = Color.FromArgb(0); this.mLinearGradientMode = LinearGradientMode.Horizontal; this.frameGradient = Color.FromArgb(0); BackImageResourceName = "CoreUtilities.Resources.corksource5.jpg"; } break; case FromTextStyles.CUSTOM: { // do nothing, will be assumed that the user has done something with this. } break; } } catch (Exception ex) { lg.Instance.Line("GeneralImages.Set", ProblemType.EXCEPTION, ex.ToString()); } return this; } } //TextToImageAPpearance /// <summary> /// Generates an appropriate point based on the specified dockstyle. Used when drawing custom RICHTEXT controls /// </summary> /// <param name="pos"></param> /// <param name="dockStyle"></param> public static Point BuildLocationForOverlayText(Point pos, DockStyle dockStyle, string Text) { switch (dockStyle) { case DockStyle.Fill: // basicallY ONTOP of the text return new Point(pos.X, pos.Y + 10); case DockStyle.Right: return new Point(pos.X + (Text.Length * 15), pos.Y + 10); case DockStyle.Bottom: return new Point(pos.X, pos.Y + 25); case DockStyle.Top: return new Point(pos.X, pos.Y - 15); } return new Point(0, 0); } } // - generalimages }
// *********************************************************************** // Copyright (c) 2009 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.Collections; namespace NUnit.Framework.Constraints { /// <summary> /// Helper class with properties and methods that supply /// a number of constraints used in Asserts. /// </summary> public class ConstraintFactory { #region Not /// <summary> /// Returns a ConstraintExpression that negates any /// following constraint. /// </summary> public ConstraintExpression Not { get { return Is.Not; } } /// <summary> /// Returns a ConstraintExpression that negates any /// following constraint. /// </summary> public ConstraintExpression No { get { return Has.No; } } #endregion #region All /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if all of them succeed. /// </summary> public ConstraintExpression All { get { return Is.All; } } #endregion #region Some /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if at least one of them succeeds. /// </summary> public ConstraintExpression Some { get { return Has.Some; } } #endregion #region None /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if all of them fail. /// </summary> public ConstraintExpression None { get { return Has.None; } } #endregion #region Exactly(n) /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding only if a specified number of them succeed. /// </summary> public static ConstraintExpression Exactly(int expectedCount) { return Has.Exactly(expectedCount); } #endregion #region Property /// <summary> /// Returns a new PropertyConstraintExpression, which will either /// test for the existence of the named property on the object /// being tested or apply any following constraint to that property. /// </summary> public ResolvableConstraintExpression Property(string name) { return Has.Property(name); } #endregion #region Length /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Length property of the object being tested. /// </summary> public ResolvableConstraintExpression Length { get { return Has.Length; } } #endregion #region Count /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Count property of the object being tested. /// </summary> public ResolvableConstraintExpression Count { get { return Has.Count; } } #endregion #region Message /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Message property of the object being tested. /// </summary> public ResolvableConstraintExpression Message { get { return Has.Message; } } #endregion #region InnerException /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the InnerException property of the object being tested. /// </summary> public ResolvableConstraintExpression InnerException { get { return Has.InnerException; } } #endregion #region Attribute /// <summary> /// Returns a new AttributeConstraint checking for the /// presence of a particular attribute on an object. /// </summary> public ResolvableConstraintExpression Attribute(Type expectedType) { return Has.Attribute(expectedType); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a new AttributeConstraint checking for the /// presence of a particular attribute on an object. /// </summary> public ResolvableConstraintExpression Attribute<T>() { return Attribute(typeof(T)); } #endif #endregion #region Null /// <summary> /// Returns a constraint that tests for null /// </summary> public NullConstraint Null { get { return new NullConstraint(); } } #endregion #region True /// <summary> /// Returns a constraint that tests for True /// </summary> public TrueConstraint True { get { return new TrueConstraint(); } } #endregion #region False /// <summary> /// Returns a constraint that tests for False /// </summary> public FalseConstraint False { get { return new FalseConstraint(); } } #endregion #region Positive /// <summary> /// Returns a constraint that tests for a positive value /// </summary> public GreaterThanConstraint Positive { get { return new GreaterThanConstraint(0); } } #endregion #region Negative /// <summary> /// Returns a constraint that tests for a negative value /// </summary> public LessThanConstraint Negative { get { return new LessThanConstraint(0); } } #endregion #region NaN /// <summary> /// Returns a constraint that tests for NaN /// </summary> public NaNConstraint NaN { get { return new NaNConstraint(); } } #endregion #region Empty /// <summary> /// Returns a constraint that tests for empty /// </summary> public EmptyConstraint Empty { get { return new EmptyConstraint(); } } #endregion #region Unique /// <summary> /// Returns a constraint that tests whether a collection /// contains all unique items. /// </summary> public UniqueItemsConstraint Unique { get { return new UniqueItemsConstraint(); } } #endregion #region BinarySerializable #if !NETCF && !SILVERLIGHT /// <summary> /// Returns a constraint that tests whether an object graph is serializable in binary format. /// </summary> public BinarySerializableConstraint BinarySerializable { get { return new BinarySerializableConstraint(); } } #endif #endregion #region XmlSerializable #if !SILVERLIGHT /// <summary> /// Returns a constraint that tests whether an object graph is serializable in xml format. /// </summary> public XmlSerializableConstraint XmlSerializable { get { return new XmlSerializableConstraint(); } } #endif #endregion #region EqualTo /// <summary> /// Returns a constraint that tests two items for equality /// </summary> public EqualConstraint EqualTo(object expected) { return new EqualConstraint(expected); } #endregion #region SameAs /// <summary> /// Returns a constraint that tests that two references are the same object /// </summary> public SameAsConstraint SameAs(object expected) { return new SameAsConstraint(expected); } #endregion #region GreaterThan /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than the suppled argument /// </summary> public GreaterThanConstraint GreaterThan(object expected) { return new GreaterThanConstraint(expected); } #endregion #region GreaterThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the suppled argument /// </summary> public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected) { return new GreaterThanOrEqualConstraint(expected); } /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the suppled argument /// </summary> public GreaterThanOrEqualConstraint AtLeast(object expected) { return new GreaterThanOrEqualConstraint(expected); } #endregion #region LessThan /// <summary> /// Returns a constraint that tests whether the /// actual value is less than the suppled argument /// </summary> public LessThanConstraint LessThan(object expected) { return new LessThanConstraint(expected); } #endregion #region LessThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the suppled argument /// </summary> public LessThanOrEqualConstraint LessThanOrEqualTo(object expected) { return new LessThanOrEqualConstraint(expected); } /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the suppled argument /// </summary> public LessThanOrEqualConstraint AtMost(object expected) { return new LessThanOrEqualConstraint(expected); } #endregion #region TypeOf /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public ExactTypeConstraint TypeOf(Type expectedType) { return new ExactTypeConstraint(expectedType); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public ExactTypeConstraint TypeOf<T>() { return new ExactTypeConstraint(typeof(T)); } #endif #endregion #region InstanceOf /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public InstanceOfTypeConstraint InstanceOf(Type expectedType) { return new InstanceOfTypeConstraint(expectedType); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public InstanceOfTypeConstraint InstanceOf<T>() { return new InstanceOfTypeConstraint(typeof(T)); } #endif #endregion #region AssignableFrom /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableFromConstraint AssignableFrom(Type expectedType) { return new AssignableFromConstraint(expectedType); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableFromConstraint AssignableFrom<T>() { return new AssignableFromConstraint(typeof(T)); } #endif #endregion #region AssignableTo /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableToConstraint AssignableTo(Type expectedType) { return new AssignableToConstraint(expectedType); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableToConstraint AssignableTo<T>() { return new AssignableToConstraint(typeof(T)); } #endif #endregion #region EquivalentTo /// <summary> /// Returns a constraint that tests whether the actual value /// is a collection containing the same elements as the /// collection supplied as an argument. /// </summary> public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected) { return new CollectionEquivalentConstraint(expected); } #endregion #region SubsetOf /// <summary> /// Returns a constraint that tests whether the actual value /// is a subset of the collection supplied as an argument. /// </summary> public CollectionSubsetConstraint SubsetOf(IEnumerable expected) { return new CollectionSubsetConstraint(expected); } #endregion #region Ordered /// <summary> /// Returns a constraint that tests whether a collection is ordered /// </summary> public CollectionOrderedConstraint Ordered { get { return new CollectionOrderedConstraint(); } } #endregion #region Member /// <summary> /// Returns a new CollectionContainsConstraint checking for the /// presence of a particular object in the collection. /// </summary> public CollectionContainsConstraint Member(object expected) { return new CollectionContainsConstraint(expected); } /// <summary> /// Returns a new CollectionContainsConstraint checking for the /// presence of a particular object in the collection. /// </summary> public CollectionContainsConstraint Contains(object expected) { return new CollectionContainsConstraint(expected); } #endregion #region Contains /// <summary> /// Returns a new ContainsConstraint. This constraint /// will, in turn, make use of the appropriate second-level /// constraint, depending on the type of the actual argument. /// This overload is only used if the item sought is a string, /// since any other type implies that we are looking for a /// collection member. /// </summary> public ContainsConstraint Contains(string expected) { return new ContainsConstraint(expected); } #endregion #region StringContaining /// <summary> /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// </summary> public SubstringConstraint StringContaining(string expected) { return new SubstringConstraint(expected); } /// <summary> /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// </summary> public SubstringConstraint ContainsSubstring(string expected) { return new SubstringConstraint(expected); } #endregion #region DoesNotContain /// <summary> /// Returns a constraint that fails if the actual /// value contains the substring supplied as an argument. /// </summary> public SubstringConstraint DoesNotContain(string expected) { return new ConstraintExpression().Not.ContainsSubstring(expected); } #endregion #region StartsWith /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> public StartsWithConstraint StartsWith(string expected) { return new StartsWithConstraint(expected); } /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> public StartsWithConstraint StringStarting(string expected) { return new StartsWithConstraint(expected); } #endregion #region DoesNotStartWith /// <summary> /// Returns a constraint that fails if the actual /// value starts with the substring supplied as an argument. /// </summary> public StartsWithConstraint DoesNotStartWith(string expected) { return new ConstraintExpression().Not.StartsWith(expected); } #endregion #region EndsWith /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> public EndsWithConstraint EndsWith(string expected) { return new EndsWithConstraint(expected); } /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> public EndsWithConstraint StringEnding(string expected) { return new EndsWithConstraint(expected); } #endregion #region DoesNotEndWith /// <summary> /// Returns a constraint that fails if the actual /// value ends with the substring supplied as an argument. /// </summary> public EndsWithConstraint DoesNotEndWith(string expected) { return new ConstraintExpression().Not.EndsWith(expected); } #endregion #region Matches #if !NETCF /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> public RegexConstraint Matches(string pattern) { return new RegexConstraint(pattern); } /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> public RegexConstraint StringMatching(string pattern) { return new RegexConstraint(pattern); } #endif #endregion #region DoesNotMatch #if !NETCF /// <summary> /// Returns a constraint that fails if the actual /// value matches the pattern supplied as an argument. /// </summary> public RegexConstraint DoesNotMatch(string pattern) { return new ConstraintExpression().Not.Matches(pattern); } #endif #endregion #region SamePath /// <summary> /// Returns a constraint that tests whether the path provided /// is the same as an expected path after canonicalization. /// </summary> public SamePathConstraint SamePath(string expected) { return new SamePathConstraint(expected); } #endregion #region SubPath /// <summary> /// Returns a constraint that tests whether the path provided /// is the same path or under an expected path after canonicalization. /// </summary> public SubPathConstraint SubPath(string expected) { return new SubPathConstraint(expected); } #endregion #region SamePathOrUnder /// <summary> /// Returns a constraint that tests whether the path provided /// is the same path or under an expected path after canonicalization. /// </summary> public SamePathOrUnderConstraint SamePathOrUnder(string expected) { return new SamePathOrUnderConstraint(expected); } #endregion #region InRange #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual value falls /// within a specified range. /// </summary> public RangeConstraint<T> InRange<T>(T from, T to) where T : IComparable<T> { return new RangeConstraint<T>(from, to); } #else /// <summary> /// Returns a constraint that tests whether the actual value falls /// within a specified range. /// </summary> public RangeConstraint InRange(IComparable from, IComparable to) { return new RangeConstraint(from, to); } #endif #endregion } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Graph.RBAC.Version1_6 { using Microsoft.Azure; using Microsoft.Azure.Graph; using Microsoft.Azure.Graph.RBAC; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ApplicationsOperations. /// </summary> public static partial class ApplicationsOperationsExtensions { /// <summary> /// Create a new application. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='parameters'> /// The parameters for creating an application. /// </param> public static Application Create(this IApplicationsOperations operations, ApplicationCreateParameters parameters) { return operations.CreateAsync(parameters).GetAwaiter().GetResult(); } /// <summary> /// Create a new application. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='parameters'> /// The parameters for creating an application. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Application> CreateAsync(this IApplicationsOperations operations, ApplicationCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists applications by filter parameters. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<Application> List(this IApplicationsOperations operations, ODataQuery<Application> odataQuery = default(ODataQuery<Application>)) { return ((IApplicationsOperations)operations).ListAsync(odataQuery).GetAwaiter().GetResult(); } /// <summary> /// Lists applications by filter parameters. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Application>> ListAsync(this IApplicationsOperations operations, ODataQuery<Application> odataQuery = default(ODataQuery<Application>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete an application. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='applicationObjectId'> /// Application object ID. /// </param> public static void Delete(this IApplicationsOperations operations, string applicationObjectId) { operations.DeleteAsync(applicationObjectId).GetAwaiter().GetResult(); } /// <summary> /// Delete an application. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IApplicationsOperations operations, string applicationObjectId, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(applicationObjectId, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get an application by object ID. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='applicationObjectId'> /// Application object ID. /// </param> public static Application Get(this IApplicationsOperations operations, string applicationObjectId) { return operations.GetAsync(applicationObjectId).GetAwaiter().GetResult(); } /// <summary> /// Get an application by object ID. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Application> GetAsync(this IApplicationsOperations operations, string applicationObjectId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(applicationObjectId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update an existing application. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='parameters'> /// Parameters to update an existing application. /// </param> public static void Patch(this IApplicationsOperations operations, string applicationObjectId, ApplicationUpdateParameters parameters) { operations.PatchAsync(applicationObjectId, parameters).GetAwaiter().GetResult(); } /// <summary> /// Update an existing application. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='parameters'> /// Parameters to update an existing application. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PatchAsync(this IApplicationsOperations operations, string applicationObjectId, ApplicationUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PatchWithHttpMessagesAsync(applicationObjectId, parameters, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get the keyCredentials associated with an application. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='applicationObjectId'> /// Application object ID. /// </param> public static IEnumerable<KeyCredential> ListKeyCredentials(this IApplicationsOperations operations, string applicationObjectId) { return operations.ListKeyCredentialsAsync(applicationObjectId).GetAwaiter().GetResult(); } /// <summary> /// Get the keyCredentials associated with an application. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<KeyCredential>> ListKeyCredentialsAsync(this IApplicationsOperations operations, string applicationObjectId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeyCredentialsWithHttpMessagesAsync(applicationObjectId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update the keyCredentials associated with an application. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='parameters'> /// Parameters to update the keyCredentials of an existing application. /// </param> public static void UpdateKeyCredentials(this IApplicationsOperations operations, string applicationObjectId, KeyCredentialsUpdateParameters parameters) { operations.UpdateKeyCredentialsAsync(applicationObjectId, parameters).GetAwaiter().GetResult(); } /// <summary> /// Update the keyCredentials associated with an application. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='parameters'> /// Parameters to update the keyCredentials of an existing application. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateKeyCredentialsAsync(this IApplicationsOperations operations, string applicationObjectId, KeyCredentialsUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateKeyCredentialsWithHttpMessagesAsync(applicationObjectId, parameters, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get the passwordCredentials associated with an application. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='applicationObjectId'> /// Application object ID. /// </param> public static IEnumerable<PasswordCredential> ListPasswordCredentials(this IApplicationsOperations operations, string applicationObjectId) { return operations.ListPasswordCredentialsAsync(applicationObjectId).GetAwaiter().GetResult(); } /// <summary> /// Get the passwordCredentials associated with an application. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<PasswordCredential>> ListPasswordCredentialsAsync(this IApplicationsOperations operations, string applicationObjectId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListPasswordCredentialsWithHttpMessagesAsync(applicationObjectId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update passwordCredentials associated with an application. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='parameters'> /// Parameters to update passwordCredentials of an existing application. /// </param> public static void UpdatePasswordCredentials(this IApplicationsOperations operations, string applicationObjectId, PasswordCredentialsUpdateParameters parameters) { operations.UpdatePasswordCredentialsAsync(applicationObjectId, parameters).GetAwaiter().GetResult(); } /// <summary> /// Update passwordCredentials associated with an application. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='parameters'> /// Parameters to update passwordCredentials of an existing application. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePasswordCredentialsAsync(this IApplicationsOperations operations, string applicationObjectId, PasswordCredentialsUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdatePasswordCredentialsWithHttpMessagesAsync(applicationObjectId, parameters, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets a list of applications from the current tenant. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextLink'> /// Next link for the list operation. /// </param> public static IPage<Application> ListNext(this IApplicationsOperations operations, string nextLink) { return operations.ListNextAsync(nextLink).GetAwaiter().GetResult(); } /// <summary> /// Gets a list of applications from the current tenant. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextLink'> /// Next link for the list operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Application>> ListNextAsync(this IApplicationsOperations operations, string nextLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using SharpDX; using SharpDX.Direct3D11; using SharpDX.DXGI; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Windows; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; using Device = SharpDX.Direct3D11.Device; using MapFlags = SharpDX.Direct3D11.MapFlags; /** * Menu view reads from the menu model and visualizes its state to a texture. * * Rendering is done on a background thread to ensure it doesn't impact framerate. To avoid data-races, message passing is used: * 1) The MenuViewMessageAuthor authors a message describing the current view state. * 2) This message is passed to the rendering thread. * 3) The MenuViewMessageInterpreter interprets the message into WPF UI elements. * 4) These elements are rendered to a texture. */ public class MenuView : IDisposable { private const int StagingTextureCount = 3; private const int WpfSize = 1024; private const int ResolutionMultiplier = 2; private const int PixelSize = WpfSize * ResolutionMultiplier; static MenuView() { RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly; } private class StagingTexture { public readonly Texture2D texture; public DataBox dataBox; private StagingTexture(Texture2D texture) { this.texture = texture; dataBox = new DataBox(); } public void Dispose() { texture.Dispose(); } public void UnmapAndCopy(DeviceContext context, Texture2D target) { dataBox = new DataBox(); context.UnmapSubresource(texture, 0); context.CopySubresourceRegion(texture, 0, null, target, 0); } public bool TryMap(DeviceContext context) { dataBox = context.MapSubresource(texture, 0, 0, MapMode.ReadWrite, MapFlags.DoNotWait, out var stream); return !dataBox.IsEmpty; } public static StagingTexture Make(Device device) { var texture = new Texture2D(device, new Texture2DDescription { Width = PixelSize, Height = PixelSize, ArraySize = 1, MipLevels = 1, Format = Format.B8G8R8A8_UNorm_SRgb, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Staging, BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read | CpuAccessFlags.Write }); return new StagingTexture(texture); } } private readonly MenuModel model; private readonly Texture2D texture; private readonly ShaderResourceView textureView; private readonly MenuViewMessageAuthor author; private bool wasChangedSinceLastUpdate = true; private readonly List<StagingTexture> stagingTextures = new List<StagingTexture>(); private readonly BlockingCollection<MenuViewMessage> messageQueue = new BlockingCollection<MenuViewMessage>(); private readonly BlockingCollection<StagingTexture> readyToRenderToQueue = new BlockingCollection<StagingTexture>(); private readonly ConcurrentQueue<StagingTexture> readyToCopyFromQueue = new ConcurrentQueue<StagingTexture>(); private readonly ConcurrentQueue<StagingTexture> readyToMapQueue = new ConcurrentQueue<StagingTexture>(); private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); private readonly Thread renderThread; public MenuView(Device device, MenuModel model) { this.model = model; texture = new Texture2D(device, new Texture2DDescription { Width = PixelSize, Height = PixelSize, ArraySize = 1, MipLevels = 0, Format = Format.B8G8R8A8_UNorm_SRgb, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget, OptionFlags = ResourceOptionFlags.GenerateMipMaps }); textureView = new ShaderResourceView(device, texture); for (int i = 0; i < StagingTextureCount; ++i) { var stagingTexture = StagingTexture.Make(device); stagingTextures.Add(stagingTexture); readyToMapQueue.Enqueue(stagingTexture); } author = new MenuViewMessageAuthor(); model.Changed += () => { wasChangedSinceLastUpdate = true; }; renderThread = new Thread(MenuRenderProc); renderThread.SetApartmentState(ApartmentState.STA); renderThread.Start(); } public void Dispose() { cancellationTokenSource.Cancel(); renderThread.Join(); cancellationTokenSource.Dispose(); foreach (var stagingTexture in stagingTextures) { stagingTexture.Dispose(); } texture.Dispose(); textureView.Dispose(); } private void MenuRenderProc() { var cancellationToken = cancellationTokenSource.Token; var interpreter = new MenuViewMessageInterpreter(); var bitmap = new RenderTargetBitmap(PixelSize, PixelSize, 96 * ResolutionMultiplier, 96 * ResolutionMultiplier, PixelFormats.Pbgra32); while (!cancellationToken.IsCancellationRequested) { StagingTexture stagingTexture; MenuViewMessage message; try { stagingTexture = readyToRenderToQueue.Take(cancellationToken); message = messageQueue.Take(cancellationToken); } catch (OperationCanceledException) { break; } //if there are multiple pending messages, keep taking them until the queue is drained while (messageQueue.TryTake(out var secondMessage)) { message = secondMessage; } var visual = interpreter.Interpret(message); visual.Arrange(new Rect(0, 0, WpfSize, WpfSize)); visual.UpdateLayout(); bitmap.Clear(); bitmap.Render(visual); var dataBox = stagingTexture.dataBox; bitmap.CopyPixels(new Int32Rect(0, 0, PixelSize, PixelSize), dataBox.DataPointer, dataBox.SlicePitch, dataBox.RowPitch); readyToCopyFromQueue.Enqueue(stagingTexture); } } public ShaderResourceView TextureView => textureView; public void Update(DeviceContext context) { if (!wasChangedSinceLastUpdate) { return; } messageQueue.Add(author.AuthorMessage(model)); wasChangedSinceLastUpdate = false; } public void DoPrework(DeviceContext context) { if (readyToCopyFromQueue.TryDequeue(out var stagingTexture)) { //if there are multiple pending textures, keep taking them until the queue is drained while (readyToMapQueue.TryDequeue(out var secondStagingTexture)) { readyToRenderToQueue.Add(stagingTexture); stagingTexture = secondStagingTexture; } stagingTexture.UnmapAndCopy(context, texture); context.GenerateMips(textureView); readyToMapQueue.Enqueue(stagingTexture); } } public void DoPostwork(DeviceContext context) { while (true) { if (!readyToMapQueue.TryPeek(out var stagingTexture)) { break; } if (!stagingTexture.TryMap(context)) { break; } if (!readyToMapQueue.TryDequeue(out var stagingTextureAgain) || stagingTextureAgain != stagingTexture) { throw new Exception("impossible"); } readyToRenderToQueue.Add(stagingTexture); } } }
//----------------------------------------------------------------------- // <copyright file="PropertyModel.cs" company="NJsonSchema"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md</license> // <author>Rico Suter, mail@rsuter.com</author> //----------------------------------------------------------------------- using System.Globalization; using NJsonSchema.CodeGeneration.Models; namespace NJsonSchema.CodeGeneration.CSharp.Models { /// <summary>The CSharp property template model.</summary> public class PropertyModel : PropertyModelBase { private readonly JsonSchemaProperty _property; private readonly CSharpGeneratorSettings _settings; private readonly CSharpTypeResolver _resolver; /// <summary>Initializes a new instance of the <see cref="PropertyModel"/> class.</summary> /// <param name="classTemplateModel">The class template model.</param> /// <param name="property">The property.</param> /// <param name="typeResolver">The type resolver.</param> /// <param name="settings">The settings.</param> public PropertyModel( ClassTemplateModel classTemplateModel, JsonSchemaProperty property, CSharpTypeResolver typeResolver, CSharpGeneratorSettings settings) : base(property, classTemplateModel, typeResolver, settings) { _property = property; _settings = settings; _resolver = typeResolver; } /// <summary>Gets the name of the property.</summary> public string Name => _property.Name; /// <summary>Gets the type of the property.</summary> public override string Type => _resolver.Resolve(_property, _property.IsNullable(_settings.SchemaType), GetTypeNameHint()); /// <summary>Gets a value indicating whether the property has a description.</summary> public bool HasDescription => !string.IsNullOrEmpty(_property.Description); /// <summary>Gets the description.</summary> public string Description => _property.Description; /// <summary>Gets the name of the field.</summary> public string FieldName => "_" + ConversionUtilities.ConvertToLowerCamelCase(PropertyName, true); /// <summary>Gets a value indicating whether the property is nullable.</summary> public override bool IsNullable => (_settings.GenerateOptionalPropertiesAsNullable && !_property.IsRequired) || base.IsNullable; /// <summary>Gets or sets a value indicating whether empty strings are allowed.</summary> public bool AllowEmptyStrings => _property.ActualTypeSchema.Type.IsString() && (_property.MinLength == null || _property.MinLength == 0); /// <summary>Gets a value indicating whether this is an array property which cannot be null.</summary> public bool HasSetter => (_property.IsNullable(_settings.SchemaType) == false && ( (_property.ActualTypeSchema.IsArray && _settings.GenerateImmutableArrayProperties) || (_property.ActualTypeSchema.IsDictionary && _settings.GenerateImmutableDictionaryProperties) )) == false; /// <summary>Gets the json property required.</summary> public string JsonPropertyRequiredCode { get { if (_settings.RequiredPropertiesMustBeDefined && _property.IsRequired) { if (!_property.IsNullable(_settings.SchemaType)) { return "Newtonsoft.Json.Required.Always"; } else { return "Newtonsoft.Json.Required.AllowNull"; } } else { if (!_property.IsNullable(_settings.SchemaType)) { return "Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore"; } else { return "Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore"; } } } } /// <summary>Gets a value indicating whether to render a required attribute.</summary> public bool RenderRequiredAttribute { get { if (!_settings.GenerateDataAnnotations || !_property.IsRequired || _property.IsNullable(_settings.SchemaType)) { return false; } return _property.ActualTypeSchema.IsAnyType || _property.ActualTypeSchema.Type.IsObject() || _property.ActualTypeSchema.Type.IsString() || _property.ActualTypeSchema.Type.IsArray(); } } /// <summary>Gets a value indicating whether to render a range attribute.</summary> public bool RenderRangeAttribute { get { if (!_settings.GenerateDataAnnotations) { return false; } if (!_property.ActualTypeSchema.Type.IsNumber() && !_property.ActualTypeSchema.Type.IsInteger()) { return false; } return _property.ActualSchema.Maximum.HasValue || _property.ActualSchema.Minimum.HasValue; } } /// <summary>Gets the minimum value of the range attribute.</summary> public string RangeMinimumValue { get { var schema = _property.ActualSchema; var propertyFormat = GetSchemaFormat(schema); var format = propertyFormat == JsonFormatStrings.Integer ? JsonFormatStrings.Integer : JsonFormatStrings.Double; var type = propertyFormat == JsonFormatStrings.Integer ? "int" : "double"; var minimum = schema.Minimum; if (minimum.HasValue && schema.IsExclusiveMinimum) { if (propertyFormat == JsonFormatStrings.Integer || propertyFormat == JsonFormatStrings.Long) { minimum++; } else if (schema.MultipleOf.HasValue) { minimum += schema.MultipleOf; } else { // TODO - add support for doubles, singles and decimals here } } return minimum.HasValue ? ValueGenerator.GetNumericValue(schema.Type, minimum.Value, format) : type + "." + nameof(double.MinValue); } } /// <summary>Gets the maximum value of the range attribute.</summary> public string RangeMaximumValue { get { var schema = _property.ActualSchema; var propertyFormat = GetSchemaFormat(schema); var format = propertyFormat == JsonFormatStrings.Integer ? JsonFormatStrings.Integer : JsonFormatStrings.Double; var type = propertyFormat == JsonFormatStrings.Integer ? "int" : "double"; var maximum = schema.Maximum; if (maximum.HasValue && schema.IsExclusiveMaximum) { if (propertyFormat == JsonFormatStrings.Integer || propertyFormat == JsonFormatStrings.Long) { maximum--; } else if (schema.MultipleOf.HasValue) { maximum -= schema.MultipleOf; } else { // TODO - add support for doubles, singles and decimals here } } return maximum.HasValue ? ValueGenerator.GetNumericValue(schema.Type, maximum.Value, format) : type + "." + nameof(double.MaxValue); } } /// <summary>Gets a value indicating whether to render a string length attribute.</summary> public bool RenderStringLengthAttribute { get { if (!_settings.GenerateDataAnnotations) { return false; } if (_property.IsRequired && _property.MinLength == 1 && _property.MaxLength == null) { return false; // handled by RequiredAttribute } return _property.ActualTypeSchema.Type.IsString() && (_property.ActualSchema.MinLength.HasValue || _property.ActualSchema.MaxLength.HasValue); } } /// <summary>Gets the minimum value of the string length attribute.</summary> public int StringLengthMinimumValue => _property.ActualSchema.MinLength ?? 0; /// <summary>Gets the maximum value of the string length attribute.</summary> public string StringLengthMaximumValue => _property.ActualSchema.MaxLength.HasValue ? _property.ActualSchema.MaxLength.Value.ToString(CultureInfo.InvariantCulture) : $"int.{nameof(int.MaxValue)}"; /// <summary>Gets a value indicating whether to render the min length attribute.</summary> public bool RenderMinLengthAttribute { get { if (!_settings.GenerateDataAnnotations) { return false; } return _property.ActualTypeSchema.Type.IsArray() && _property.ActualSchema.MinItems > 0; } } /// <summary>Gets the value of the min length attribute.</summary> public int MinLengthAttribute => _property.ActualSchema.MinItems; /// <summary>Gets a value indicating whether to render the max length attribute.</summary> public bool RenderMaxLengthAttribute { get { if (!_settings.GenerateDataAnnotations) { return false; } return _property.ActualTypeSchema.Type.IsArray() && _property.ActualSchema.MaxItems > 0; } } /// <summary>Gets the value of the max length attribute.</summary> public int MaxLengthAttribute => _property.ActualSchema.MaxItems; /// <summary>Gets a value indicating whether to render a regular expression attribute.</summary> public bool RenderRegularExpressionAttribute { get { if (!_settings.GenerateDataAnnotations) { return false; } return _property.ActualTypeSchema.Type.IsString() && !string.IsNullOrEmpty(_property.ActualSchema.Pattern); } } /// <summary>Gets the regular expression value for the regular expression attribute.</summary> public string RegularExpressionValue => _property.ActualSchema.Pattern?.Replace("\"", "\"\""); /// <summary>Gets a value indicating whether the property type is string enum.</summary> public bool IsStringEnum => _property.ActualTypeSchema.IsEnumeration && _property.ActualTypeSchema.Type.IsString(); /// <summary>Gets a value indicating whether the property should be formatted like a date.</summary> public bool IsDate => _property.ActualSchema.Format == JsonFormatStrings.Date; /// <summary>Gets a value indicating whether the property is deprecated.</summary> public bool IsDeprecated => _property.IsDeprecated; /// <summary>Gets a value indicating whether the property has a deprecated message.</summary> public bool HasDeprecatedMessage => !string.IsNullOrEmpty(_property.DeprecatedMessage); /// <summary>Gets the deprecated message.</summary> public string DeprecatedMessage => _property.DeprecatedMessage; private string GetSchemaFormat(JsonSchema schema) { if (Type == "long" || Type == "long?") { return JsonFormatStrings.Long; } if (schema.Format == null) { switch (schema.Type) { case JsonObjectType.Integer: return JsonFormatStrings.Integer; case JsonObjectType.Number: return JsonFormatStrings.Double; } } return schema.Format; } } }
// <copyright file="MlkBiCgStab.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2013 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; using MathNet.Numerics.Distributions; using MathNet.Numerics.LinearAlgebra.Solvers; using MathNet.Numerics.Properties; namespace MathNet.Numerics.LinearAlgebra.Single.Solvers { /// <summary> /// A Multiple-Lanczos Bi-Conjugate Gradient stabilized iterative matrix solver. /// </summary> /// <remarks> /// <para> /// The Multiple-Lanczos Bi-Conjugate Gradient stabilized (ML(k)-BiCGStab) solver is an 'improvement' /// of the standard BiCgStab solver. /// </para> /// <para> /// The algorithm was taken from: <br/> /// ML(k)BiCGSTAB: A BiCGSTAB variant based on multiple Lanczos starting vectors /// <br/> /// Man-chung Yeung and Tony F. Chan /// <br/> /// SIAM Journal of Scientific Computing /// <br/> /// Volume 21, Number 4, pp. 1263 - 1290 /// </para> /// <para> /// The example code below provides an indication of the possible use of the /// solver. /// </para> /// </remarks> public sealed class MlkBiCgStab : IIterativeSolver<float> { /// <summary> /// The default number of starting vectors. /// </summary> const int DefaultNumberOfStartingVectors = 50; /// <summary> /// The collection of starting vectors which are used as the basis for the Krylov sub-space. /// </summary> IList<Vector<float>> _startingVectors; /// <summary> /// The number of starting vectors used by the algorithm /// </summary> int _numberOfStartingVectors = DefaultNumberOfStartingVectors; /// <summary> /// Gets or sets the number of starting vectors. /// </summary> /// <remarks> /// Must be larger than 1 and smaller than the number of variables in the matrix that /// for which this solver will be used. /// </remarks> public int NumberOfStartingVectors { [DebuggerStepThrough] get { return _numberOfStartingVectors; } [DebuggerStepThrough] set { if (value <= 1) { throw new ArgumentOutOfRangeException("value"); } _numberOfStartingVectors = value; } } /// <summary> /// Resets the number of starting vectors to the default value. /// </summary> public void ResetNumberOfStartingVectors() { _numberOfStartingVectors = DefaultNumberOfStartingVectors; } /// <summary> /// Gets or sets a series of orthonormal vectors which will be used as basis for the /// Krylov sub-space. /// </summary> public IList<Vector<float>> StartingVectors { [DebuggerStepThrough] get { return _startingVectors; } [DebuggerStepThrough] set { if ((value == null) || (value.Count == 0)) { _startingVectors = null; } else { _startingVectors = value; } } } /// <summary> /// Gets the number of starting vectors to create /// </summary> /// <param name="maximumNumberOfStartingVectors">Maximum number</param> /// <param name="numberOfVariables">Number of variables</param> /// <returns>Number of starting vectors to create</returns> static int NumberOfStartingVectorsToCreate(int maximumNumberOfStartingVectors, int numberOfVariables) { // Create no more starting vectors than the size of the problem - 1 return Math.Min(maximumNumberOfStartingVectors, (numberOfVariables - 1)); } /// <summary> /// Returns an array of starting vectors. /// </summary> /// <param name="maximumNumberOfStartingVectors">The maximum number of starting vectors that should be created.</param> /// <param name="numberOfVariables">The number of variables.</param> /// <returns> /// An array with starting vectors. The array will never be larger than the /// <paramref name="maximumNumberOfStartingVectors"/> but it may be smaller if /// the <paramref name="numberOfVariables"/> is smaller than /// the <paramref name="maximumNumberOfStartingVectors"/>. /// </returns> static IList<Vector<float>> CreateStartingVectors(int maximumNumberOfStartingVectors, int numberOfVariables) { // Create no more starting vectors than the size of the problem - 1 // Get random values and then orthogonalize them with // modified Gramm - Schmidt var count = NumberOfStartingVectorsToCreate(maximumNumberOfStartingVectors, numberOfVariables); // Get a random set of samples based on the standard normal distribution with // mean = 0 and sd = 1 var distribution = new Normal(); var matrix = new DenseMatrix(numberOfVariables, count); for (var i = 0; i < matrix.ColumnCount; i++) { var samples = new float[matrix.RowCount]; for (var j = 0; j < matrix.RowCount; j++) { samples[j] = (float)distribution.Sample(); } // Set the column matrix.SetColumn(i, samples); } // Compute the orthogonalization. var gs = matrix.GramSchmidt(); var orthogonalMatrix = gs.Q; // Now transfer this to vectors var result = new List<Vector<float>>(); for (var i = 0; i < orthogonalMatrix.ColumnCount; i++) { result.Add(orthogonalMatrix.Column(i)); // Normalize the result vector result[i].Multiply(1/(float) result[i].L2Norm(), result[i]); } return result; } /// <summary> /// Create random vectors array /// </summary> /// <param name="arraySize">Number of vectors</param> /// <param name="vectorSize">Size of each vector</param> /// <returns>Array of random vectors</returns> static Vector<float>[] CreateVectorArray(int arraySize, int vectorSize) { var result = new Vector<float>[arraySize]; for (var i = 0; i < result.Length; i++) { result[i] = new DenseVector(vectorSize); } return result; } /// <summary> /// Calculates the <c>true</c> residual of the matrix equation Ax = b according to: residual = b - Ax /// </summary> /// <param name="matrix">Source <see cref="Matrix"/>A.</param> /// <param name="residual">Residual <see cref="Vector"/> data.</param> /// <param name="x">x <see cref="Vector"/> data.</param> /// <param name="b">b <see cref="Vector"/> data.</param> static void CalculateTrueResidual(Matrix<float> matrix, Vector<float> residual, Vector<float> x, Vector<float> b) { // -Ax = residual matrix.Multiply(x, residual); residual.Multiply(-1, residual); // residual + b residual.Add(b, residual); } /// <summary> /// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the /// solution vector and x is the unknown vector. /// </summary> /// <param name="matrix">The coefficient matrix, <c>A</c>.</param> /// <param name="input">The solution vector, <c>b</c></param> /// <param name="result">The result vector, <c>x</c></param> /// <param name="iterator">The iterator to use to control when to stop iterating.</param> /// <param name="preconditioner">The preconditioner to use for approximations.</param> public void Solve(Matrix<float> matrix, Vector<float> input, Vector<float> result, Iterator<float> iterator, IPreconditioner<float> preconditioner) { if (matrix.RowCount != matrix.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix"); } if (result.Count != input.Count) { throw new ArgumentException(Resources.ArgumentVectorsSameLength); } if (input.Count != matrix.RowCount) { throw Matrix.DimensionsDontMatch<ArgumentException>(input, matrix); } if (iterator == null) { iterator = new Iterator<float>(); } if (preconditioner == null) { preconditioner = new UnitPreconditioner<float>(); } preconditioner.Initialize(matrix); // Choose an initial guess x_0 // Take x_0 = 0 var xtemp = new DenseVector(input.Count); // Choose k vectors q_1, q_2, ..., q_k // Build a new set if: // a) the stored set doesn't exist (i.e. == null) // b) Is of an incorrect length (i.e. too long) // c) The vectors are of an incorrect length (i.e. too long or too short) var useOld = false; if (_startingVectors != null) { // We don't accept collections with zero starting vectors so ... if (_startingVectors.Count <= NumberOfStartingVectorsToCreate(_numberOfStartingVectors, input.Count)) { // Only check the first vector for sizing. If that matches we assume the // other vectors match too. If they don't the process will crash if (_startingVectors[0].Count == input.Count) { useOld = true; } } } _startingVectors = useOld ? _startingVectors : CreateStartingVectors(_numberOfStartingVectors, input.Count); // Store the number of starting vectors. Not really necessary but easier to type :) var k = _startingVectors.Count; // r_0 = b - Ax_0 // This is basically a SAXPY so it could be made a lot faster var residuals = new DenseVector(matrix.RowCount); CalculateTrueResidual(matrix, residuals, xtemp, input); // Define the temporary scalars var c = new float[k]; // Define the temporary vectors var gtemp = new DenseVector(residuals.Count); var u = new DenseVector(residuals.Count); var utemp = new DenseVector(residuals.Count); var temp = new DenseVector(residuals.Count); var temp1 = new DenseVector(residuals.Count); var temp2 = new DenseVector(residuals.Count); var zd = new DenseVector(residuals.Count); var zg = new DenseVector(residuals.Count); var zw = new DenseVector(residuals.Count); var d = CreateVectorArray(_startingVectors.Count, residuals.Count); // g_0 = r_0 var g = CreateVectorArray(_startingVectors.Count, residuals.Count); residuals.CopyTo(g[k - 1]); var w = CreateVectorArray(_startingVectors.Count, residuals.Count); // FOR (j = 0, 1, 2 ....) var iterationNumber = 0; while (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) == IterationStatus.Continue) { // SOLVE M g~_((j-1)k+k) = g_((j-1)k+k) preconditioner.Approximate(g[k - 1], gtemp); // w_((j-1)k+k) = A g~_((j-1)k+k) matrix.Multiply(gtemp, w[k - 1]); // c_((j-1)k+k) = q^T_1 w_((j-1)k+k) c[k - 1] = _startingVectors[0].DotProduct(w[k - 1]); if (c[k - 1].AlmostEqualNumbersBetween(0, 1)) { throw new NumericalBreakdownException(); } // alpha_(jk+1) = q^T_1 r_((j-1)k+k) / c_((j-1)k+k) var alpha = _startingVectors[0].DotProduct(residuals)/c[k - 1]; // u_(jk+1) = r_((j-1)k+k) - alpha_(jk+1) w_((j-1)k+k) w[k - 1].Multiply(-alpha, temp); residuals.Add(temp, u); // SOLVE M u~_(jk+1) = u_(jk+1) preconditioner.Approximate(u, temp1); temp1.CopyTo(utemp); // rho_(j+1) = -u^t_(jk+1) A u~_(jk+1) / ||A u~_(jk+1)||^2 matrix.Multiply(temp1, temp); var rho = temp.DotProduct(temp); // If rho is zero then temp is a zero vector and we're probably // about to have zero residuals (i.e. an exact solution). // So set rho to 1.0 because in the next step it will turn to zero. if (rho.AlmostEqualNumbersBetween(0, 1)) { rho = 1.0f; } rho = -u.DotProduct(temp)/rho; // r_(jk+1) = rho_(j+1) A u~_(jk+1) + u_(jk+1) u.CopyTo(residuals); // Reuse temp temp.Multiply(rho, temp); residuals.Add(temp, temp2); temp2.CopyTo(residuals); // x_(jk+1) = x_((j-1)k_k) - rho_(j+1) u~_(jk+1) + alpha_(jk+1) g~_((j-1)k+k) utemp.Multiply(-rho, temp); xtemp.Add(temp, temp2); temp2.CopyTo(xtemp); gtemp.Multiply(alpha, gtemp); xtemp.Add(gtemp, temp2); temp2.CopyTo(xtemp); // Check convergence and stop if we are converged. if (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) != IterationStatus.Continue) { // Calculate the true residual CalculateTrueResidual(matrix, residuals, xtemp, input); // Now recheck the convergence if (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) != IterationStatus.Continue) { // We're all good now. // Exit from the while loop. break; } } // FOR (i = 1,2, ...., k) for (var i = 0; i < k; i++) { // z_d = u_(jk+1) u.CopyTo(zd); // z_g = r_(jk+i) residuals.CopyTo(zg); // z_w = 0 zw.Clear(); // FOR (s = i, ...., k-1) AND j >= 1 float beta; if (iterationNumber >= 1) { for (var s = i; s < k - 1; s++) { // beta^(jk+i)_((j-1)k+s) = -q^t_(s+1) z_d / c_((j-1)k+s) beta = -_startingVectors[s + 1].DotProduct(zd)/c[s]; // z_d = z_d + beta^(jk+i)_((j-1)k+s) d_((j-1)k+s) d[s].Multiply(beta, temp); zd.Add(temp, temp2); temp2.CopyTo(zd); // z_g = z_g + beta^(jk+i)_((j-1)k+s) g_((j-1)k+s) g[s].Multiply(beta, temp); zg.Add(temp, temp2); temp2.CopyTo(zg); // z_w = z_w + beta^(jk+i)_((j-1)k+s) w_((j-1)k+s) w[s].Multiply(beta, temp); zw.Add(temp, temp2); temp2.CopyTo(zw); } } beta = rho*c[k - 1]; if (beta.AlmostEqualNumbersBetween(0, 1)) { throw new NumericalBreakdownException(); } // beta^(jk+i)_((j-1)k+k) = -(q^T_1 (r_(jk+1) + rho_(j+1) z_w)) / (rho_(j+1) c_((j-1)k+k)) zw.Multiply(rho, temp2); residuals.Add(temp2, temp); beta = -_startingVectors[0].DotProduct(temp)/beta; // z_g = z_g + beta^(jk+i)_((j-1)k+k) g_((j-1)k+k) g[k - 1].Multiply(beta, temp); zg.Add(temp, temp2); temp2.CopyTo(zg); // z_w = rho_(j+1) (z_w + beta^(jk+i)_((j-1)k+k) w_((j-1)k+k)) w[k - 1].Multiply(beta, temp); zw.Add(temp, temp2); temp2.CopyTo(zw); zw.Multiply(rho, zw); // z_d = r_(jk+i) + z_w residuals.Add(zw, zd); // FOR (s = 1, ... i - 1) for (var s = 0; s < i - 1; s++) { // beta^(jk+i)_(jk+s) = -q^T_s+1 z_d / c_(jk+s) beta = -_startingVectors[s + 1].DotProduct(zd)/c[s]; // z_d = z_d + beta^(jk+i)_(jk+s) * d_(jk+s) d[s].Multiply(beta, temp); zd.Add(temp, temp2); temp2.CopyTo(zd); // z_g = z_g + beta^(jk+i)_(jk+s) * g_(jk+s) g[s].Multiply(beta, temp); zg.Add(temp, temp2); temp2.CopyTo(zg); } // d_(jk+i) = z_d - u_(jk+i) zd.Subtract(u, d[i]); // g_(jk+i) = z_g + z_w zg.Add(zw, g[i]); // IF (i < k - 1) if (i < k - 1) { // c_(jk+1) = q^T_i+1 d_(jk+i) c[i] = _startingVectors[i + 1].DotProduct(d[i]); if (c[i].AlmostEqualNumbersBetween(0, 1)) { throw new NumericalBreakdownException(); } // alpha_(jk+i+1) = q^T_(i+1) u_(jk+i) / c_(jk+i) alpha = _startingVectors[i + 1].DotProduct(u)/c[i]; // u_(jk+i+1) = u_(jk+i) - alpha_(jk+i+1) d_(jk+i) d[i].Multiply(-alpha, temp); u.Add(temp, temp2); temp2.CopyTo(u); // SOLVE M g~_(jk+i) = g_(jk+i) preconditioner.Approximate(g[i], gtemp); // x_(jk+i+1) = x_(jk+i) + rho_(j+1) alpha_(jk+i+1) g~_(jk+i) gtemp.Multiply(rho*alpha, temp); xtemp.Add(temp, temp2); temp2.CopyTo(xtemp); // w_(jk+i) = A g~_(jk+i) matrix.Multiply(gtemp, w[i]); // r_(jk+i+1) = r_(jk+i) - rho_(j+1) alpha_(jk+i+1) w_(jk+i) w[i].Multiply(-rho*alpha, temp); residuals.Add(temp, temp2); temp2.CopyTo(residuals); // We can check the residuals here if they're close if (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) != IterationStatus.Continue) { // Recalculate the residuals and go round again. This is done to ensure that // we have the proper residuals. CalculateTrueResidual(matrix, residuals, xtemp, input); } } } // END ITERATION OVER i iterationNumber++; } // copy the temporary result to the real result vector xtemp.CopyTo(result); } } }
using System.Collections.Generic; using System.Linq; using java.io; using java.lang; using java.net; using java.nio; using java.nio.channels; using java.text; using java.util; using RSUtilities; using RSUtilities.Tools; namespace OpenRSS.Cache { /// <summary> /// A file store holds multiple files inside a "virtual" file system made up of /// several index files and a single data file. /// @author Graham /// @author `Discardedx2 /// </summary> public sealed class FileStore : AbstractCloseable { /// <summary> /// The data file. /// </summary> private readonly FileChannel dataChannel; /// <summary> /// The index files. /// </summary> private readonly FileChannel[] indexChannels; /// <summary> /// The 'meta' index files. /// </summary> private readonly FileChannel metaChannel; /// <summary> /// Creates a new file store. /// </summary> /// <param name="data"> The data file. </param> /// <param name="indexes"> The index files. </param> /// <param name="meta"> The 'meta' index file. </param> public FileStore(FileChannel data, FileChannel[] indexes, FileChannel meta) { dataChannel = data; indexChannels = indexes; metaChannel = meta; } /// <summary> /// Opens the file store stored in the specified directory. /// </summary> /// <param name="root"> The directory containing the index and data files. </param> /// <returns> The file store. </returns> /// <exception cref="FileNotFoundException"> /// if any of the {@code main_file_cache.*} /// files could not be found. /// </exception> public static FileStore Open(string root) { return Open(new File(root)); } /// <summary> /// Opens the file store stored in the specified directory. /// </summary> /// <param name="root"> The directory containing the index and data files. </param> /// <returns> The file store. </returns> /// <exception cref="FileNotFoundException"> /// if any of the {@code main_file_cache.*} /// files could not be found. /// </exception> public static FileStore Open(File root) { var data = new File(root, "main_file_cache.dat2"); if (!data.exists()) { throw new FileNotFoundException(); } var raf = new RandomAccessFile(data, "rw"); var dataChannel = raf.getChannel(); var indexChannels = new List<FileChannel>(); for (var i = 0; i < 254; i++) { var index = new File(root, "main_file_cache.idx" + i); if (!index.exists()) { break; } raf = new RandomAccessFile(index, "rw"); var indexChannel = raf.getChannel(); indexChannels.Add(indexChannel); } if (indexChannels.Count == 0) { throw new FileNotFoundException(); } var meta = new File(root, "main_file_cache.idx255"); if (!meta.exists()) { throw new FileNotFoundException(); } raf = new RandomAccessFile(meta, "rw"); var metaChannel = raf.getChannel(); return new FileStore(dataChannel, indexChannels.ToArray(), metaChannel); } /// <summary> /// Gets the number of index files, not including the meta index file. /// </summary> /// <returns> The number of index files. </returns> /// <exception cref="IOException"> if an I/O error occurs. </exception> public int GetTypeCount() { return indexChannels.Length; } /// <summary> /// Gets the number of files of the specified type. /// </summary> /// <param name="type"> The type. </param> /// <returns> The number of files. </returns> /// <exception cref="IOException"> if an I/O error occurs. </exception> public int GetFileCount(int type) { if ((type < 0 || type >= indexChannels.Length) && type != 255) { throw new FileNotFoundException(); } if (type == 255) { return (int) (metaChannel.size() / Index.SIZE); } return (int) (indexChannels[type].size() / Index.SIZE); } /// <summary> /// Writes a file. /// </summary> /// <param name="type"> The type of the file. </param> /// <param name="id"> The id of the file. </param> /// <param name="data"> A <seealso cref="ByteBuffer" /> containing the contents of the file. </param> /// <exception cref="IOException"> if an I/O error occurs. </exception> public void Write(int type, int id, ByteBuffer data) { data.mark(); if (!Write(type, id, data, true)) { data.reset(); Write(type, id, data, false); } } /// <summary> /// Writes a file. /// </summary> /// <param name="type"> The type of the file. </param> /// <param name="id"> The id of the file. </param> /// <param name="data"> A <seealso cref="ByteBuffer" /> containing the contents of the file. </param> /// <param name="overwrite"> /// A flag indicating if the existing file should be /// overwritten. /// </param> /// <returns> A flag indicating if the file was written successfully. </returns> /// <exception cref="IOException"> if an I/O error occurs. </exception> private bool Write(int type, int id, ByteBuffer data, bool overwrite) { if ((type < 0 || type >= indexChannels.Length) && type != 255) { throw new FileNotFoundException(); } var indexChannel = type == 255 ? metaChannel : indexChannels[type]; var nextSector = 0; long ptr = id * Index.SIZE; ByteBuffer buf; Index index; if (overwrite) { if (ptr < 0) { throw new IOException(); } if (ptr >= indexChannel.size()) { return false; } buf = ByteBuffer.allocate(Index.SIZE); FileChannelUtils.ReadFully(indexChannel, buf, ptr); index = Index.Decode((ByteBuffer) buf.flip()); nextSector = index.GetSector(); if (nextSector <= 0 || nextSector > dataChannel.size() * Sector.SIZE) { return false; } } else { nextSector = (int) ((dataChannel.size() + Sector.SIZE - 1) / Sector.SIZE); if (nextSector == 0) { nextSector = 1; } } index = new Index(data.remaining(), nextSector); indexChannel.write(index.Encode(), ptr); buf = ByteBuffer.allocate(Sector.SIZE); int chunk = 0, remaining = index.GetSize(); do { var curSector = nextSector; ptr = curSector * Sector.SIZE; nextSector = 0; Sector sector; if (overwrite) { buf.clear(); FileChannelUtils.ReadFully(dataChannel, buf, ptr); sector = Sector.Decode((ByteBuffer) buf.flip()); if (sector.GetType() != type) { return false; } if (sector.GetId() != id) { return false; } if (sector.GetChunk() != chunk) { return false; } nextSector = sector.GetNextSector(); if (nextSector < 0 || nextSector > dataChannel.size() / Sector.SIZE) { return false; } } if (nextSector == 0) { overwrite = false; nextSector = (int) ((dataChannel.size() + Sector.SIZE - 1) / Sector.SIZE); if (nextSector == 0) { nextSector++; } if (nextSector == curSector) { nextSector++; } } var bytes = new byte[Sector.DATA_SIZE]; if (remaining < Sector.DATA_SIZE) { data.get(bytes, 0, remaining); nextSector = 0; // mark as EOF remaining = 0; } else { remaining -= Sector.DATA_SIZE; data.get(bytes, 0, Sector.DATA_SIZE); } sector = new Sector(type, id, chunk++, nextSector, bytes); dataChannel.write(sector.Encode(), ptr); } while (remaining > 0); return true; } /// <summary> /// Reads a file. /// </summary> /// <param name="type"> The type of the file. </param> /// <param name="id"> The id of the file. </param> /// <returns> A <seealso cref="ByteBuffer" /> containing the contents of the file. </returns> /// <exception cref="IOException"> if an I/O error occurs. </exception> public ByteBuffer Read(int type, int id) { if ((type < 0 || type >= indexChannels.Length) && type != 255) { throw new FileNotFoundException(); } var indexChannel = type == 255 ? metaChannel : indexChannels[type]; long ptr = id * Index.SIZE; if (ptr < 0 || ptr >= indexChannel.size()) { throw new FileNotFoundException(); } var buf = ByteBuffer.allocate(Index.SIZE); FileChannelUtils.ReadFully(indexChannel, buf, ptr); var index = Index.Decode((ByteBuffer) buf.flip()); var data = ByteBuffer.allocate(index.GetSize()); buf = ByteBuffer.allocate(Sector.SIZE); int chunk = 0, remaining = index.GetSize(); ptr = index.GetSector() * Sector.SIZE; do { buf.clear(); FileChannelUtils.ReadFully(dataChannel, buf, ptr); var sector = Sector.Decode((ByteBuffer) buf.flip()); if (remaining > Sector.DATA_SIZE) { data.put(sector.GetData(), 0, Sector.DATA_SIZE); remaining -= Sector.DATA_SIZE; if (sector.GetType() != type) { throw new IOException("File type mismatch."); } if (sector.GetId() != id) { throw new IOException("File id mismatch."); } if (sector.GetChunk() != chunk++) { throw new IOException("Chunk mismatch."); } ptr = sector.GetNextSector() * Sector.SIZE; } else { data.put(sector.GetData(), 0, remaining); remaining = 0; } } while (remaining > 0); return (ByteBuffer) data.flip(); } public override void Close() { dataChannel.close(); foreach (var channel in indexChannels) { channel.close(); } metaChannel.close(); } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // 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 Google Inc. 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 using System; using System.Collections.Generic; using System.Collections; using System.IO; using System.Reflection; namespace Google.ProtocolBuffers { /// <summary> /// Iterates over data created using a <see cref="MessageStreamWriter{T}" />. /// Unlike MessageStreamWriter, this class is not usually constructed directly with /// a stream; instead it is provided with a way of opening a stream when iteration /// is started. The stream is closed when the iteration is completed or the enumerator /// is disposed. (This occurs naturally when using <c>foreach</c>.) /// </summary> public class MessageStreamIterator<TMessage> : IEnumerable<TMessage> where TMessage : IMessage<TMessage> { private readonly StreamProvider streamProvider; private readonly ExtensionRegistry extensionRegistry; private readonly int sizeLimit; // Type.EmptyTypes isn't present on the compact framework private static readonly Type[] EmptyTypes = new Type[0]; /// <summary> /// Delegate created via reflection trickery (once per type) to create a builder /// and read a message from a CodedInputStream with it. Note that unlike in Java, /// there's one static field per constructed type. /// </summary> private static readonly Func<CodedInputStream, ExtensionRegistry, TMessage> messageReader = BuildMessageReader(); /// <summary> /// Any exception (within reason) thrown within messageReader is caught and rethrown in the constructor. /// This makes life a lot simpler for the caller. /// </summary> private static Exception typeInitializationException; /// <summary> /// Creates the delegate later used to read messages. This is only called once per type, but to /// avoid exceptions occurring at confusing times, if this fails it will set typeInitializationException /// to the appropriate error and return null. /// </summary> private static Func<CodedInputStream, ExtensionRegistry, TMessage> BuildMessageReader() { try { Type builderType = FindBuilderType(); // Yes, it's redundant to find this again, but it's only the once... MethodInfo createBuilderMethod = typeof(TMessage).GetMethod("CreateBuilder", EmptyTypes); Delegate builderBuilder = Delegate.CreateDelegate( typeof(Func<>).MakeGenericType(builderType), null, createBuilderMethod); MethodInfo buildMethod = typeof(MessageStreamIterator<TMessage>) .GetMethod("BuildImpl", BindingFlags.Static | BindingFlags.NonPublic) .MakeGenericMethod(typeof(TMessage), builderType); return (Func<CodedInputStream, ExtensionRegistry, TMessage>)Delegate.CreateDelegate( typeof(Func<CodedInputStream, ExtensionRegistry, TMessage>), builderBuilder, buildMethod); } catch (ArgumentException e) { typeInitializationException = e; } catch (InvalidOperationException e) { typeInitializationException = e; } catch (InvalidCastException e) { // Can't see why this would happen, but best to know about it. typeInitializationException = e; } return null; } /// <summary> /// Works out the builder type for TMessage, or throws an ArgumentException to explain why it can't. /// </summary> private static Type FindBuilderType() { MethodInfo createBuilderMethod = typeof(TMessage).GetMethod("CreateBuilder", EmptyTypes); if (createBuilderMethod == null) { throw new ArgumentException("Message type " + typeof(TMessage).FullName + " has no CreateBuilder method."); } if (createBuilderMethod.ReturnType == typeof(void)) { throw new ArgumentException("CreateBuilder method in " + typeof(TMessage).FullName + " has void return type"); } Type builderType = createBuilderMethod.ReturnType; Type messageInterface = typeof(IMessage<,>).MakeGenericType(typeof(TMessage), builderType); Type builderInterface = typeof(IBuilder<,>).MakeGenericType(typeof(TMessage), builderType); if (Array.IndexOf(typeof(TMessage).GetInterfaces(), messageInterface) == -1) { throw new ArgumentException("Message type " + typeof(TMessage) + " doesn't implement " + messageInterface.FullName); } if (Array.IndexOf(builderType.GetInterfaces(), builderInterface) == -1) { throw new ArgumentException("Builder type " + typeof(TMessage) + " doesn't implement " + builderInterface.FullName); } return builderType; } // This is only ever fetched by reflection, so the compiler may // complain that it's unused #pragma warning disable 0169 /// <summary> /// Method we'll use to build messageReader, with the first parameter fixed to TMessage.CreateBuilder. Note that we /// have to introduce another type parameter (TMessage2) as we can't constrain TMessage for just a single method /// (and we can't do it at the type level because we don't know TBuilder). However, by constraining TMessage2 /// to not only implement IMessage appropriately but also to derive from TMessage2, we can avoid doing a cast /// for every message; the implicit reference conversion will be fine. In practice, TMessage2 and TMessage will /// be the same type when we construct the generic method by reflection. /// </summary> private static TMessage BuildImpl<TMessage2, TBuilder>(Func<TBuilder> builderBuilder, CodedInputStream input, ExtensionRegistry registry) where TBuilder : IBuilder<TMessage2, TBuilder> where TMessage2 : TMessage, IMessage<TMessage2, TBuilder> { TBuilder builder = builderBuilder(); input.ReadMessage(builder, registry); return builder.Build(); } #pragma warning restore 0414 private static readonly uint ExpectedTag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); private MessageStreamIterator(StreamProvider streamProvider, ExtensionRegistry extensionRegistry, int sizeLimit) { if (messageReader == null) { throw typeInitializationException; } this.streamProvider = streamProvider; this.extensionRegistry = extensionRegistry; this.sizeLimit = sizeLimit; } private MessageStreamIterator(StreamProvider streamProvider, ExtensionRegistry extensionRegistry) : this (streamProvider, extensionRegistry, CodedInputStream.DefaultSizeLimit) { } /// <summary> /// Creates a new instance which uses the same stream provider as this one, /// but the specified extension registry. /// </summary> public MessageStreamIterator<TMessage> WithExtensionRegistry(ExtensionRegistry newRegistry) { return new MessageStreamIterator<TMessage>(streamProvider, newRegistry, sizeLimit); } /// <summary> /// Creates a new instance which uses the same stream provider and extension registry as this one, /// but with the specified size limit. Note that this must be big enough for the largest message /// and the tag and size preceding it. /// </summary> public MessageStreamIterator<TMessage> WithSizeLimit(int newSizeLimit) { return new MessageStreamIterator<TMessage>(streamProvider, extensionRegistry, newSizeLimit); } public static MessageStreamIterator<TMessage> FromFile(string file) { return new MessageStreamIterator<TMessage>(() => File.OpenRead(file), ExtensionRegistry.Empty); } public static MessageStreamIterator<TMessage> FromStreamProvider(StreamProvider streamProvider) { return new MessageStreamIterator<TMessage>(streamProvider, ExtensionRegistry.Empty); } public IEnumerator<TMessage> GetEnumerator() { using (Stream stream = streamProvider()) { CodedInputStream input = CodedInputStream.CreateInstance(stream); input.SetSizeLimit(sizeLimit); uint tag; while ((tag = input.ReadTag()) != 0) { if (tag != ExpectedTag) { throw InvalidProtocolBufferException.InvalidMessageStreamTag(); } yield return messageReader(input, extensionRegistry); input.ResetSizeCounter(); } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Net.Configuration; using System.Security.Cryptography.X509Certificates; using System.Threading; namespace SimShift.MapTool { public class Ets2NavigationRoute { public Ets2Item Start; public Ets2Item End; public Ets2Mapper Mapper; public bool Loading = false; public List<Tuple<Ets2Item, int, int>> Prefabs; public List<Ets2Item> Roads; public List<Ets2NavigationSegment> Segments; private Ets2Point From; private Ets2Point To; public Ets2NavigationRoute(Ets2Item start, Ets2Item end, Ets2Point from, Ets2Point to, Ets2Mapper mapper) { Start = start; End = end; From = from; To = to; Mapper = mapper; if (Start != End) ThreadPool.QueueUserWorkItem(new WaitCallback(FindRoute)); } private void FindRoute(object state) { Loading = true; Dictionary<ulong, Tuple<float, Ets2Item>> nodeMap = new Dictionary<ulong, Tuple<float, Ets2Item>>(); List<Ets2Item> nodesToWalk = new List<Ets2Item>(); // Fill node map foreach (var node in Mapper.Items.Values.Where(x => x.Type == Ets2ItemType.Prefab && x.HideUI == false)) { nodesToWalk.Add(node); nodeMap.Add(node.ItemUID, new Tuple<float, Ets2Item>(float.MaxValue, null)); } // Walk first node (START) if (nodeMap.ContainsKey(Start.ItemUID) == false) { // Nope return; } if (nodeMap.ContainsKey(End.ItemUID) == false) { // Nope return; } // <Weight, LastItem> nodeMap[Start.ItemUID] = new Tuple<float, Ets2Item>(0, null); while (nodesToWalk.Any()) { float distanceWalked = float.MaxValue; Ets2Item toWalk = null; foreach (var node in nodesToWalk) { var dTmp = nodeMap[node.ItemUID].Item1; if (dTmp != float.MaxValue && distanceWalked > dTmp) { distanceWalked = dTmp; toWalk = node; } } if (toWalk == null) break; nodesToWalk.Remove(toWalk); var currentWeight = nodeMap[toWalk.ItemUID].Item1; // Iterate all destination nodes from this node foreach (var jump in toWalk.Navigation) { var newWeight = jump.Value.Item1 + currentWeight; var newNode = jump.Key; if (nodeMap.ContainsKey(newNode.ItemUID) && nodeMap[newNode.ItemUID].Item1 > newWeight) nodeMap[newNode.ItemUID] = new Tuple<float, Ets2Item>(newWeight, toWalk); // add route with weight + previous node } } List<Ets2Item> routeNodes = new List<Ets2Item>(); List<Ets2Item> routeRoads = new List<Ets2Item>(); List<Ets2NavigationSegment> segments = new List<Ets2NavigationSegment>(); var goingViaNode = (ulong) 0; var route = End; while (route != null) { // we add this prefab to the route list routeNodes.Add(route); var prefabSeg = new Ets2NavigationSegment(route); segments.Add(prefabSeg); // find the next prefab in the route description var gotoNew = nodeMap[route.ItemUID].Item2; if (gotoNew == null) break; // get a path from the current prefab to the new one var path = route.Navigation[gotoNew]; var roadPath = path.Item3; // add the path to road list routeRoads.AddRange(roadPath); segments.Add(new Ets2NavigationSegment(roadPath, prefabSeg)); // Set the new prefab as route route = gotoNew; } routeNodes.Add(Start); segments.Reverse(); // Find entry/exit of start/end segment var foundDst = float.MaxValue; var foundNode = default(Ets2Node); // Find the closest road to startpoint foreach (var node in segments[0].Prefab.NodesList) { var dst = node.Value.Point.DistanceTo(From); if (foundDst > dst) { foundDst = dst; foundNode = node.Value; } } // We found the node; find the road that exists at this point segments[0].Entry = foundNode; foundDst = float.MaxValue; foundNode = default(Ets2Node); // Find the closest road to startpoint foreach (var node in segments[segments.Count - 1].Prefab.NodesList) { var dst = node.Value.Point.DistanceTo(To); if (foundDst > dst) { foundDst = dst; foundNode = node.Value; } } // We found the node; find the road that exists at this point segments[segments.Count - 1].Exit = foundNode; // Iterate all segments for (int seg = 0; seg < segments.Count; seg++) { // Generate prefab routes if (segments[seg].Type == Ets2NavigationSegmentType.Prefab) { var prevRoad = seg > 0 ? segments[seg - 1] : null; var nextRoad = seg + 1 < segments.Count ? segments[seg + 1] : null; // Link segments together if (prevRoad != null) segments[seg].Entry = prevRoad.Entry; if (nextRoad != null) segments[seg].Exit = nextRoad.Exit; segments[seg].GenerateOptions(prevRoad,nextRoad); } // Generate lane data if (segments[seg].Type == Ets2NavigationSegmentType.Road) { var prefFab = seg > 0 ? segments[seg - 1] : null; var nextFab = seg + 1 < segments.Count ? segments[seg + 1] : null; segments[seg].GenerateOptions(prefFab, nextFab); } } //for (int seg = 1; seg < segments.Count - 1; seg++) for (int seg = 0; seg < segments.Count; seg++) { // Validate routes if (segments[seg].Type == Ets2NavigationSegmentType.Prefab) { var prevRoad = seg > 0 ? segments[seg - 1] : null; var nextRoad = seg + 1 < segments.Count ? segments[seg + 1] : null; foreach (var opt in segments[seg].Options) { if (prevRoad == null) { // start point; validate if it is close to our start node if (opt.Points.FirstOrDefault().DistanceTo(segments[seg].Entry.Point) < 10) { opt.EntryLane = 0; // yep; sure } } else { var entryPoint = opt.Points.FirstOrDefault(); foreach (var roadOpt in prevRoad.Options) { if (roadOpt.Points.Any(x => x.CloseTo(entryPoint))) { // We've got a match ! :D opt.EntryLane = roadOpt.ExitLane; roadOpt.Valid = roadOpt.EntryLane >= 0 && roadOpt.ExitLane >= 0; } } } if (nextRoad == null) { // last point. if (opt.Points.FirstOrDefault().DistanceTo(segments[seg].Exit.Point) < 10) { opt.ExitLane = 0; // yep; sure } } else { var exitPoint = opt.Points.LastOrDefault(); foreach (var roadOpt in nextRoad.Options) { if (roadOpt.Points.Any(x => x.CloseTo(exitPoint))) { // We've got a match ! :D opt.ExitLane= roadOpt.EntryLane; roadOpt.Valid = roadOpt.EntryLane >= 0 && roadOpt.ExitLane >= 0; } } } opt.Valid = opt.EntryLane >= 0 && opt.ExitLane >= 0; } } // Generate prefab routes if (segments[seg].Type == Ets2NavigationSegmentType.Road && false) { var nextPrefab = segments[seg + 1]; var prevPrefab = segments[seg - 1]; if (nextPrefab.Type != Ets2NavigationSegmentType.Prefab || prevPrefab.Type != Ets2NavigationSegmentType.Prefab) continue; // Deduct road options by matching entry/exits for (int solI = 0; solI < segments[seg].Options.Count; solI++) { // Find if there is any route in prefab that matches our entry lane var okStart = prevPrefab.Options.Any(x => segments[seg].MatchEntry(solI, prevPrefab)); var okEnd = nextPrefab.Options.Any(x => segments[seg].MatchExit(solI, nextPrefab)); // This road has a valid end & Start if (okStart && okEnd) { segments[seg].Options[solI].Valid = true; } } } } // There is probably only 1 valid solution for entry/exit //if (segments[0].Options.Any()) segments[0].Options[0].Valid = true; //if (segments[segments.Count - 1].Options.Any()) segments[segments.Count - 1].Options[0].Valid = true; Segments = segments; var pts = Segments.SelectMany(x => x.Solutions).SelectMany(x => x.Points).ToList(); Roads = routeRoads; Prefabs = routeNodes.Select(x => new Tuple<Ets2Item, int, int>(x, 0, 0)).ToList(); Loading = false; } } }
using System; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; using System.IO; using System.Text.RegularExpressions; using Dependencies.ClrPh; namespace Dependencies { // C# typedefs #region Sxs Classes public class SxsEntry { public SxsEntry(string _Name, string _Path, string _Version="", string _Type="", string _PublicKeyToken = "") { Name = _Name; Path = _Path; Version = _Version; Type = _Type; PublicKeyToken = _PublicKeyToken; } public SxsEntry(SxsEntry OtherSxsEntry) { Name = OtherSxsEntry.Name; Path = OtherSxsEntry.Path; Version = OtherSxsEntry.Version; Type = OtherSxsEntry.Type; PublicKeyToken = OtherSxsEntry.PublicKeyToken; } public SxsEntry(XElement SxsAssemblyIdentity, XElement SxsFile, string Folder) { var RelPath = SxsFile.Attribute("name").Value.ToString(); Name = System.IO.Path.GetFileName(RelPath); Path = System.IO.Path.Combine(Folder, RelPath); Version = ""; Type = ""; PublicKeyToken = ""; if (SxsAssemblyIdentity != null) { if (SxsAssemblyIdentity.Attribute("version") != null) Version = SxsAssemblyIdentity.Attribute("version").Value.ToString(); if (SxsAssemblyIdentity.Attribute("type") != null) Type = SxsAssemblyIdentity.Attribute("type").Value.ToString(); if (SxsAssemblyIdentity.Attribute("publicKeyToken") != null) PublicKeyToken = SxsAssemblyIdentity.Attribute("publicKeyToken").Value.ToString(); } // TODO : DLL search order ? //if (!File.Exists(Path)) //{ // Path = "???"; //} } public string Name; public string Path; public string Version; public string Type; public string PublicKeyToken; } public class SxsEntries : List<SxsEntry> { public static SxsEntries FromSxsAssembly(XElement SxsAssembly, XNamespace Namespace, string Folder) { SxsEntries Entries = new SxsEntries(); XElement SxsAssemblyIdentity = SxsAssembly.Element(Namespace + "assemblyIdentity"); foreach (XElement SxsFile in SxsAssembly.Elements(Namespace + "file")) { Entries.Add(new SxsEntry(SxsAssemblyIdentity, SxsFile, Folder)); } return Entries; } } #endregion Sxs Classes #region SxsManifest public class SxsManifest { // find dll with same name as sxs assembly in target directory public static SxsEntries SxsFindTargetDll(string AssemblyName, string Folder) { SxsEntries EntriesFromElement = new SxsEntries(); string TargetFilePath = Path.Combine(Folder, AssemblyName); if (File.Exists(TargetFilePath)) { var Name = System.IO.Path.GetFileName(TargetFilePath); var Path = TargetFilePath; EntriesFromElement.Add(new SxsEntry(Name, Path)); return EntriesFromElement; } string TargetDllPath = Path.Combine(Folder, String.Format("{0:s}.dll", AssemblyName)); if (File.Exists(TargetDllPath)) { var Name = System.IO.Path.GetFileName(TargetDllPath); var Path = TargetDllPath; EntriesFromElement.Add(new SxsEntry(Name, Path)); return EntriesFromElement; } return EntriesFromElement; } public static SxsEntries ExtractDependenciesFromSxsElement(XElement SxsAssembly, string Folder, string ExecutableName = "", string ProcessorArch = "") { // Private assembly search sequence : https://msdn.microsoft.com/en-us/library/windows/desktop/aa374224(v=vs.85).aspx // // * In the application's folder. Typically, this is the folder containing the application's executable file. // * In a subfolder in the application's folder. The subfolder must have the same name as the assembly. // * In a language-specific subfolder in the application's folder. // -> The name of the subfolder is a string of DHTML language codes indicating a language-culture or language. // * In a subfolder of a language-specific subfolder in the application's folder. // -> The name of the higher subfolder is a string of DHTML language codes indicating a language-culture or language. The deeper subfolder has the same name as the assembly. // // // 0. Side-by-side searches the WinSxS folder. // 1. \\<appdir>\<assemblyname>.DLL // 2. \\<appdir>\<assemblyname>.manifest // 3. \\<appdir>\<assemblyname>\<assemblyname>.DLL // 4. \\<appdir>\<assemblyname>\<assemblyname>.manifest string TargetSxsManifestPath; string SxsManifestName = SxsAssembly.Attribute("name").Value.ToString(); string SxsManifestDir = Path.Combine(Folder, SxsManifestName); // 0. find publisher manifest in %WINDIR%/WinSxs/Manifest if (SxsAssembly.Attribute("publicKeyToken") != null) { string WinSxsDir = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Windows), "WinSxs" ); string WinSxsManifestDir = Path.Combine(WinSxsDir, "Manifests"); var RegisteredManifests = Directory.EnumerateFiles( WinSxsManifestDir, "*.manifest" ); string PublicKeyToken = SxsAssembly.Attribute("publicKeyToken").Value; string Name = SxsAssembly.Attribute("name").Value.ToLower(); string ProcessArch = SxsAssembly.Attribute("processorArchitecture") != null ? SxsAssembly.Attribute("processorArchitecture").Value : "*"; string Version = SxsAssembly.Attribute("version").Value; string Langage = SxsAssembly.Attribute("langage") != null ? SxsAssembly.Attribute("langage").Value : "none"; // TODO : support localized sxs redirection switch (ProcessArch.ToLower()) { case "$(build.arch)": case "*": ProcessArch = ProcessorArch; break; case "amd64": case "x86": case "wow64": case "msil": case "arm": case "arm64": break; // nothing to do default: ProcessArch = ".*"; break; } Regex VersionRegex = new Regex(@"([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)", RegexOptions.IgnoreCase); Match VersionMatch = VersionRegex.Match(Version); if (VersionMatch.Success) { string Major = VersionMatch.Groups[1].Value; string Minor = VersionMatch.Groups[2].Value; string Build = (VersionMatch.Groups[3].Value == "0") ? ".*" : VersionMatch.Groups[3].Value; string Patch = (VersionMatch.Groups[4].Value == "0") ? ".*" : VersionMatch.Groups[4].Value; // Manifest filename : {ProcArch}_{Name}_{PublicKeyToken}_{FuzzyVersion}_{Langage}_{some_hash}.manifest Regex ManifestFileNameRegex = new Regex( String.Format(@"({0:s}_{1:s}_{2:s}_{3:s}\.{4:s}\.({5:s})\.({6:s})_none_([a-fA-F0-9]+))\.manifest", ProcessArch, Name, PublicKeyToken, Major, Minor, Build, Patch //Langage, // some hash ), RegexOptions.IgnoreCase ); bool FoundMatch = false; int HighestBuild = 0; int HighestPatch = 0; string MatchSxsManifestDir = ""; string MatchSxsManifestPath = ""; foreach (var FileName in RegisteredManifests) { Match MatchingSxsFile = ManifestFileNameRegex.Match(FileName); if (MatchingSxsFile.Success) { int MatchingBuild = Int32.Parse(MatchingSxsFile.Groups[2].Value); int MatchingPatch = Int32.Parse(MatchingSxsFile.Groups[3].Value); if ((MatchingBuild > HighestBuild) || ((MatchingBuild == HighestBuild) && (MatchingPatch > HighestPatch))) { string TestMatchSxsManifestDir = MatchingSxsFile.Groups[1].Value; // Check the directory exists before confirming there is a match string FullPathMatchSxsManifestDir = Path.Combine(WinSxsDir, TestMatchSxsManifestDir); //Debug.WriteLine("FullPathMatchSxsManifestDir : Checking {0:s}", FullPathMatchSxsManifestDir); if (NativeFile.Exists(FullPathMatchSxsManifestDir, true)) { //Debug.WriteLine("FullPathMatchSxsManifestDir : Checking {0:s} TRUE", FullPathMatchSxsManifestDir); FoundMatch = true; HighestBuild = MatchingBuild; HighestPatch = MatchingPatch; MatchSxsManifestDir = TestMatchSxsManifestDir; MatchSxsManifestPath = Path.Combine(WinSxsManifestDir, FileName); } } } } if (FoundMatch) { string FullPathMatchSxsManifestDir = Path.Combine(WinSxsDir, MatchSxsManifestDir); // "{name}.local" local sxs directory hijack ( really used for UAC bypasses ) if (ExecutableName != "") { string LocalSxsDir = Path.Combine(Folder, String.Format("{0:s}.local", ExecutableName)); string MatchingLocalSxsDir = Path.Combine(LocalSxsDir, MatchSxsManifestDir); if (Directory.Exists(LocalSxsDir) && Directory.Exists(MatchingLocalSxsDir)) { FullPathMatchSxsManifestDir = MatchingLocalSxsDir; } } return ExtractDependenciesFromSxsManifestFile(MatchSxsManifestPath, FullPathMatchSxsManifestDir, ExecutableName, ProcessorArch); } } } // 1. \\<appdir>\<assemblyname>.DLL // find dll with same assembly name in same directory SxsEntries EntriesFromMatchingDll = SxsFindTargetDll(SxsManifestName, Folder); if (EntriesFromMatchingDll.Count > 0) { return EntriesFromMatchingDll; } // 2. \\<appdir>\<assemblyname>.manifest // find manifest with same assembly name in same directory TargetSxsManifestPath = Path.Combine(Folder, String.Format("{0:s}.manifest", SxsManifestName)); if (File.Exists(TargetSxsManifestPath)) { return ExtractDependenciesFromSxsManifestFile(TargetSxsManifestPath, Folder, ExecutableName, ProcessorArch); } // 3. \\<appdir>\<assemblyname>\<assemblyname>.DLL // find matching dll in sub directory SxsEntries EntriesFromMatchingDllSub = SxsFindTargetDll(SxsManifestName, SxsManifestDir); if (EntriesFromMatchingDllSub.Count > 0) { return EntriesFromMatchingDllSub; } // 4. \<appdir>\<assemblyname>\<assemblyname>.manifest // find manifest in sub directory TargetSxsManifestPath = Path.Combine(SxsManifestDir, String.Format("{0:s}.manifest", SxsManifestName)); if (Directory.Exists(SxsManifestDir) && File.Exists(TargetSxsManifestPath)) { return ExtractDependenciesFromSxsManifestFile(TargetSxsManifestPath, SxsManifestDir, ExecutableName, ProcessorArch); } // TODO : do the same thing for localization // // 0. Side-by-side searches the WinSxS folder. // 1. \\<appdir>\<language-culture>\<assemblyname>.DLL // 2. \\<appdir>\<language-culture>\<assemblyname>.manifest // 3. \\<appdir>\<language-culture>\<assemblyname>\<assemblyname>.DLL // 4. \\<appdir>\<language-culture>\<assemblyname>\<assemblyname>.manifest // TODO : also take into account Multilanguage User Interface (MUI) when // scanning manifests and WinSxs dll. God this is horrendously complicated. // Could not find the dependency { SxsEntries EntriesFromElement = new SxsEntries(); EntriesFromElement.Add(new SxsEntry(SxsManifestName, "file ???")); return EntriesFromElement; } } public static SxsEntries ExtractDependenciesFromSxsManifestFile(string ManifestFile, string Folder, string ExecutableName = "", string ProcessorArch = "") { // Console.WriteLine("Extracting deps from file {0:s}", ManifestFile); using (FileStream fs = new FileStream(ManifestFile, FileMode.Open, FileAccess.Read)) { return ExtractDependenciesFromSxsManifest(fs, Folder, ExecutableName, ProcessorArch); } } public static SxsEntries ExtractDependenciesFromSxsManifest(System.IO.Stream ManifestStream, string Folder, string ExecutableName = "", string ProcessorArch = "") { SxsEntries AdditionnalDependencies = new SxsEntries(); XDocument XmlManifest = ParseSxsManifest(ManifestStream); XNamespace Namespace = XmlManifest.Root.GetDefaultNamespace(); // Find any declared dll //< assembly xmlns = 'urn:schemas-microsoft-com:asm.v1' manifestVersion = '1.0' > // < assemblyIdentity name = 'additional_dll' version = 'XXX.YY.ZZ' type = 'win32' /> // < file name = 'additional_dll.dll' /> //</ assembly > foreach (XElement SxsAssembly in XmlManifest.Descendants(Namespace + "assembly")) { AdditionnalDependencies.AddRange(SxsEntries.FromSxsAssembly(SxsAssembly, Namespace, Folder)); } // Find any dependencies : // <dependency> // <dependentAssembly> // <assemblyIdentity // type="win32" // name="Microsoft.Windows.Common-Controls" // version="6.0.0.0" // processorArchitecture="amd64" // publicKeyToken="6595b64144ccf1df" // language="*" // /> // </dependentAssembly> // </dependency> foreach (XElement SxsAssembly in XmlManifest.Descendants(Namespace + "dependency") .Elements(Namespace + "dependentAssembly") .Elements(Namespace + "assemblyIdentity") ) { // find target PE AdditionnalDependencies.AddRange(ExtractDependenciesFromSxsElement(SxsAssembly, Folder, ExecutableName, ProcessorArch)); } return AdditionnalDependencies; } public static XDocument ParseSxsManifest(System.IO.Stream ManifestStream) { XDocument XmlManifest = null; // Hardcode namespaces for manifests since they are no always specified in the embedded manifests. XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace(String.Empty, "urn:schemas-microsoft-com:asm.v1"); //default namespace : manifest V1 nsmgr.AddNamespace("asmv3", "urn:schemas-microsoft-com:asm.v3"); // sometimes missing from manifests : V3 nsmgr.AddNamespace("asmv3", "http://schemas.microsoft.com/SMI/2005/WindowsSettings"); // sometimes missing from manifests : V3 XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.Preserve); using (StreamReader xStream = new StreamReader(ManifestStream)) { // Trim double quotes in manifest attributes // Example : // * Before : <assemblyIdentity name=""Microsoft.Windows.Shell.DevicePairingFolder"" processorArchitecture=""amd64"" version=""5.1.0.0"" type="win32" /> // * After : <assemblyIdentity name="Microsoft.Windows.Shell.DevicePairingFolder" processorArchitecture="amd64" version="5.1.0.0" type="win32" /> string PeManifest = xStream.ReadToEnd(); PeManifest = new Regex("\\\"\\\"([\\w\\d\\.]*)\\\"\\\"").Replace(PeManifest, "\"$1\""); // Regex magic here // some manifests have "macros" that break xml parsing PeManifest = new Regex("SXS_PROCESSOR_ARCHITECTURE").Replace(PeManifest, "\"amd64\""); PeManifest = new Regex("SXS_ASSEMBLY_VERSION").Replace(PeManifest, "\"\""); PeManifest = new Regex("SXS_ASSEMBLY_NAME").Replace(PeManifest, "\"\""); // Remove blank lines PeManifest = Regex.Replace(PeManifest, @"^\s+$[\r\n]*", string.Empty, RegexOptions.Multiline); using (XmlTextReader xReader = new XmlTextReader(PeManifest, XmlNodeType.Document, context)) { XmlManifest = XDocument.Load(xReader); } } return XmlManifest; } public static SxsEntries GetSxsEntries(PE Pe) { SxsEntries Entries = new SxsEntries(); string RootPeFolder = Path.GetDirectoryName(Pe.Filepath); string RootPeFilename = Path.GetFileName(Pe.Filepath); // Look for overriding manifest file (named "{$name}.manifest) string OverridingManifest = String.Format("{0:s}.manifest", Pe.Filepath); if (File.Exists(OverridingManifest)) { return ExtractDependenciesFromSxsManifestFile( OverridingManifest, RootPeFolder, RootPeFilename, Pe.GetProcessor() ); } // Retrieve embedded manifest string PeManifest = Pe.GetManifest(); if (PeManifest.Length == 0) return Entries; byte[] RawManifest = System.Text.Encoding.UTF8.GetBytes(PeManifest); System.IO.Stream ManifestStream = new System.IO.MemoryStream(RawManifest); Entries = ExtractDependenciesFromSxsManifest( ManifestStream, RootPeFolder, RootPeFilename, Pe.GetProcessor() ); return Entries; } } #endregion SxsManifest }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Net.Http.Headers; using System.Net.Test.Common; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { // Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary // to separately Dispose (or have a 'using' statement) for the handler. public class PostScenarioTest { private const string ExpectedContent = "Test contest"; private const string UserName = "user1"; private const string Password = "password1"; private readonly static Uri BasicAuthServerUri = Configuration.Http.BasicAuthUriForCreds(false, UserName, Password); private readonly static Uri SecureBasicAuthServerUri = Configuration.Http.BasicAuthUriForCreds(true, UserName, Password); private readonly ITestOutputHelper _output; public readonly static object[][] EchoServers = Configuration.Http.EchoServers; public readonly static object[][] BasicAuthEchoServers = new object[][] { new object[] { BasicAuthServerUri }, new object[] { SecureBasicAuthServerUri } }; public PostScenarioTest(ITestOutputHelper output) { _output = output; } [Theory, MemberData(nameof(EchoServers))] public async Task PostNoContentUsingContentLengthSemantics_Success(Uri serverUri) { await PostHelper(serverUri, string.Empty, null, useContentLengthUpload: true, useChunkedEncodingUpload: false); } [Theory, MemberData(nameof(EchoServers))] public async Task PostEmptyContentUsingContentLengthSemantics_Success(Uri serverUri) { await PostHelper(serverUri, string.Empty, new StringContent(string.Empty), useContentLengthUpload: true, useChunkedEncodingUpload: false); } [ActiveIssue(5485, PlatformID.Windows)] [Theory, MemberData(nameof(EchoServers))] public async Task PostEmptyContentUsingChunkedEncoding_Success(Uri serverUri) { await PostHelper(serverUri, string.Empty, new StringContent(string.Empty), useContentLengthUpload: false, useChunkedEncodingUpload: true); } [Theory, MemberData(nameof(EchoServers))] public async Task PostUsingContentLengthSemantics_Success(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent), useContentLengthUpload: true, useChunkedEncodingUpload: false); } [Theory, MemberData(nameof(EchoServers))] public async Task PostUsingChunkedEncoding_Success(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent), useContentLengthUpload: false, useChunkedEncodingUpload: true); } [Theory, MemberData(nameof(EchoServers))] public async Task PostSyncBlockingContentUsingChunkedEncoding_Success(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new SyncBlockingContent(ExpectedContent), useContentLengthUpload: false, useChunkedEncodingUpload: true); } [Theory, MemberData(nameof(EchoServers))] public async Task PostRepeatedFlushContentUsingChunkedEncoding_Success(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new RepeatedFlushContent(ExpectedContent), useContentLengthUpload: false, useChunkedEncodingUpload: true); } [Theory, MemberData(nameof(EchoServers))] public async Task PostUsingUsingConflictingSemantics_UsesChunkedSemantics(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent), useContentLengthUpload: true, useChunkedEncodingUpload: true); } [Theory, MemberData(nameof(EchoServers))] public async Task PostUsingNoSpecifiedSemantics_UsesChunkedSemantics(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent), useContentLengthUpload: false, useChunkedEncodingUpload: false); } [Theory] [InlineData(5 * 1024)] [InlineData(63 * 1024)] public async Task PostLongerContentLengths_UsesChunkedSemantics(int contentLength) { var rand = new Random(42); var sb = new StringBuilder(contentLength); for (int i = 0; i < contentLength; i++) { sb.Append((char)(rand.Next(0, 26) + 'a')); } string content = sb.ToString(); await PostHelper(Configuration.Http.RemoteEchoServer, content, new StringContent(content), useContentLengthUpload: true, useChunkedEncodingUpload: false); } [Theory, MemberData(nameof(BasicAuthEchoServers))] public async Task PostRewindableContentUsingAuth_NoPreAuthenticate_Success(Uri serverUri) { HttpContent content = CustomContent.Create(ExpectedContent, true); var credential = new NetworkCredential(UserName, Password); await PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, false); } [Theory, MemberData(nameof(BasicAuthEchoServers))] public async Task PostNonRewindableContentUsingAuth_NoPreAuthenticate_ThrowsInvalidOperationException(Uri serverUri) { HttpContent content = CustomContent.Create(ExpectedContent, false); var credential = new NetworkCredential(UserName, Password); await Assert.ThrowsAsync<InvalidOperationException>(() => PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, preAuthenticate: false)); } [Theory, MemberData(nameof(BasicAuthEchoServers))] public async Task PostNonRewindableContentUsingAuth_PreAuthenticate_Success(Uri serverUri) { HttpContent content = CustomContent.Create(ExpectedContent, false); var credential = new NetworkCredential(UserName, Password); await PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, preAuthenticate: true); } private async Task PostHelper( Uri serverUri, string requestBody, HttpContent requestContent, bool useContentLengthUpload, bool useChunkedEncodingUpload) { using (var client = new HttpClient()) { if (!useContentLengthUpload && requestContent != null) { requestContent.Headers.ContentLength = null; } if (useChunkedEncodingUpload) { client.DefaultRequestHeaders.TransferEncodingChunked = true; } using (HttpResponseMessage response = await client.PostAsync(serverUri, requestContent)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); if (!useContentLengthUpload && !useChunkedEncodingUpload) { useChunkedEncodingUpload = true; } TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, useChunkedEncodingUpload, requestBody); } } } private async Task PostUsingAuthHelper( Uri serverUri, string requestBody, HttpContent requestContent, NetworkCredential credential, bool preAuthenticate) { var handler = new HttpClientHandler(); handler.PreAuthenticate = preAuthenticate; handler.Credentials = credential; using (var client = new HttpClient(handler)) { // Send HEAD request to help bypass the 401 auth challenge for the latter POST assuming // that the authentication will be cached and re-used later when PreAuthenticate is true. var request = new HttpRequestMessage(HttpMethod.Head, serverUri); HttpResponseMessage response; using (response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } // Now send POST request. request = new HttpRequestMessage(HttpMethod.Post, serverUri); request.Content = requestContent; requestContent.Headers.ContentLength = null; request.Headers.TransferEncodingChunked = true; using (response = await client.PostAsync(serverUri, requestContent)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, true, requestBody); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Reflection.Metadata; using System.Runtime.ExceptionServices; using System.Text; using System.Text.Json; using System.Threading.Tasks; [assembly: MetadataUpdateHandler(typeof(Microsoft.JSInterop.Infrastructure.DotNetDispatcher))] namespace Microsoft.JSInterop.Infrastructure { /// <summary> /// Provides methods that receive incoming calls from JS to .NET. /// </summary> [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070", Justification = "Linker does not propogate annotations to generated state machine. https://github.com/mono/linker/issues/1403")] public static class DotNetDispatcher { private const string DisposeDotNetObjectReferenceMethodName = "__Dispose"; internal static readonly JsonEncodedText DotNetObjectRefKey = JsonEncodedText.Encode("__dotNetObject"); private static readonly ConcurrentDictionary<AssemblyKey, IReadOnlyDictionary<string, (MethodInfo, Type[])>> _cachedMethodsByAssembly = new(); private static readonly ConcurrentDictionary<Type, IReadOnlyDictionary<string, (MethodInfo, Type[])>> _cachedMethodsByType = new(); /// <summary> /// Receives a call from JS to .NET, locating and invoking the specified method. /// </summary> /// <param name="jsRuntime">The <see cref="JSRuntime"/>.</param> /// <param name="invocationInfo">The <see cref="DotNetInvocationInfo"/>.</param> /// <param name="argsJson">A JSON representation of the parameters.</param> /// <returns>A JSON representation of the return value, or null.</returns> public static string? Invoke(JSRuntime jsRuntime, in DotNetInvocationInfo invocationInfo, string argsJson) { // This method doesn't need [JSInvokable] because the platform is responsible for having // some way to dispatch calls here. The logic inside here is the thing that checks whether // the targeted method has [JSInvokable]. It is not itself subject to that restriction, // because there would be nobody to police that. This method *is* the police. IDotNetObjectReference? targetInstance = default; if (invocationInfo.DotNetObjectId != default) { targetInstance = jsRuntime.GetObjectReference(invocationInfo.DotNetObjectId); } var syncResult = InvokeSynchronously(jsRuntime, invocationInfo, targetInstance, argsJson); if (syncResult == null) { return null; } return JsonSerializer.Serialize(syncResult, jsRuntime.JsonSerializerOptions); } /// <summary> /// Receives a call from JS to .NET, locating and invoking the specified method asynchronously. /// </summary> /// <param name="jsRuntime">The <see cref="JSRuntime"/>.</param> /// <param name="invocationInfo">The <see cref="DotNetInvocationInfo"/>.</param> /// <param name="argsJson">A JSON representation of the parameters.</param> /// <returns>A JSON representation of the return value, or null.</returns> public static void BeginInvokeDotNet(JSRuntime jsRuntime, DotNetInvocationInfo invocationInfo, string argsJson) { // This method doesn't need [JSInvokable] because the platform is responsible for having // some way to dispatch calls here. The logic inside here is the thing that checks whether // the targeted method has [JSInvokable]. It is not itself subject to that restriction, // because there would be nobody to police that. This method *is* the police. // Using ExceptionDispatchInfo here throughout because we want to always preserve // original stack traces. var callId = invocationInfo.CallId; object? syncResult = null; ExceptionDispatchInfo? syncException = null; IDotNetObjectReference? targetInstance = null; try { if (invocationInfo.DotNetObjectId != default) { targetInstance = jsRuntime.GetObjectReference(invocationInfo.DotNetObjectId); } syncResult = InvokeSynchronously(jsRuntime, invocationInfo, targetInstance, argsJson); } catch (Exception ex) { syncException = ExceptionDispatchInfo.Capture(ex); } // If there was no callId, the caller does not want to be notified about the result if (callId == null) { return; } else if (syncException != null) { // Threw synchronously, let's respond. jsRuntime.EndInvokeDotNet(invocationInfo, new DotNetInvocationResult(syncException.SourceException, "InvocationFailure")); } else if (syncResult is Task task) { // Returned a task - we need to continue that task and then report an exception // or return the value. task.ContinueWith(t => EndInvokeDotNetAfterTask(t, jsRuntime, invocationInfo), TaskScheduler.Current); } else { var syncResultJson = JsonSerializer.Serialize(syncResult, jsRuntime.JsonSerializerOptions); var dispatchResult = new DotNetInvocationResult(syncResultJson); jsRuntime.EndInvokeDotNet(invocationInfo, dispatchResult); } } private static void EndInvokeDotNetAfterTask(Task task, JSRuntime jsRuntime, in DotNetInvocationInfo invocationInfo) { if (task.Exception != null) { var exceptionDispatchInfo = ExceptionDispatchInfo.Capture(task.Exception.GetBaseException()); var dispatchResult = new DotNetInvocationResult(exceptionDispatchInfo.SourceException, "InvocationFailure"); jsRuntime.EndInvokeDotNet(invocationInfo, dispatchResult); } var result = TaskGenericsUtil.GetTaskResult(task); var resultJson = JsonSerializer.Serialize(result, jsRuntime.JsonSerializerOptions); jsRuntime.EndInvokeDotNet(invocationInfo, new DotNetInvocationResult(resultJson)); } private static object? InvokeSynchronously(JSRuntime jsRuntime, in DotNetInvocationInfo callInfo, IDotNetObjectReference? objectReference, string argsJson) { var assemblyName = callInfo.AssemblyName; var methodIdentifier = callInfo.MethodIdentifier; AssemblyKey assemblyKey; MethodInfo methodInfo; Type[] parameterTypes; if (objectReference is null) { assemblyKey = new AssemblyKey(assemblyName!); (methodInfo, parameterTypes) = GetCachedMethodInfo(assemblyKey, methodIdentifier); } else { if (assemblyName != null) { throw new ArgumentException($"For instance method calls, '{nameof(assemblyName)}' should be null. Value received: '{assemblyName}'."); } if (string.Equals(DisposeDotNetObjectReferenceMethodName, methodIdentifier, StringComparison.Ordinal)) { // The client executed dotNetObjectReference.dispose(). Dispose the reference and exit. objectReference.Dispose(); return default; } (methodInfo, parameterTypes) = GetCachedMethodInfo(objectReference, methodIdentifier); } var suppliedArgs = ParseArguments(jsRuntime, methodIdentifier, argsJson, parameterTypes); try { // objectReference will be null if this call invokes a static JSInvokable method. return methodInfo.Invoke(objectReference?.Value, suppliedArgs); } catch (TargetInvocationException tie) // Avoid using exception filters for AOT runtime support { if (tie.InnerException != null) { ExceptionDispatchInfo.Capture(tie.InnerException).Throw(); throw tie.InnerException; // Unreachable } throw; } finally { // We require the invoked method to retrieve any pending byte arrays synchronously. If we didn't, // we wouldn't be able to have overlapping async calls. As a way to enforce this, we clear the // pending byte arrays synchronously after the call. This also helps because the recipient isn't // required to consume all the pending byte arrays, since it's legal for the JS data model to contain // more data than the .NET data model (like overposting) jsRuntime.ByteArraysToBeRevived.Clear(); } } internal static object?[] ParseArguments(JSRuntime jsRuntime, string methodIdentifier, string arguments, Type[] parameterTypes) { if (parameterTypes.Length == 0) { return Array.Empty<object>(); } var count = Encoding.UTF8.GetByteCount(arguments); var buffer = ArrayPool<byte>.Shared.Rent(count); try { var receivedBytes = Encoding.UTF8.GetBytes(arguments, buffer); Debug.Assert(count == receivedBytes); var reader = new Utf8JsonReader(buffer.AsSpan(0, count)); if (!reader.Read() || reader.TokenType != JsonTokenType.StartArray) { throw new JsonException("Invalid JSON"); } var suppliedArgs = new object?[parameterTypes.Length]; var index = 0; while (index < parameterTypes.Length && reader.Read() && reader.TokenType != JsonTokenType.EndArray) { var parameterType = parameterTypes[index]; if (reader.TokenType == JsonTokenType.StartObject && IsIncorrectDotNetObjectRefUse(parameterType, reader)) { throw new InvalidOperationException($"In call to '{methodIdentifier}', parameter of type '{parameterType.Name}' at index {(index + 1)} must be declared as type 'DotNetObjectRef<{parameterType.Name}>' to receive the incoming value."); } suppliedArgs[index] = JsonSerializer.Deserialize(ref reader, parameterType, jsRuntime.JsonSerializerOptions); index++; } if (index < parameterTypes.Length) { // If we parsed fewer parameters, we can always make a definitive claim about how many parameters were received. throw new ArgumentException($"The call to '{methodIdentifier}' expects '{parameterTypes.Length}' parameters, but received '{index}'."); } if (!reader.Read() || reader.TokenType != JsonTokenType.EndArray) { // Either we received more parameters than we expected or the JSON is malformed. throw new JsonException($"Unexpected JSON token {reader.TokenType}. Ensure that the call to `{methodIdentifier}' is supplied with exactly '{parameterTypes.Length}' parameters."); } return suppliedArgs; // Note that the JsonReader instance is intentionally not passed by ref (or an in parameter) since we want a copy of the original reader. static bool IsIncorrectDotNetObjectRefUse(Type parameterType, Utf8JsonReader jsonReader) { // Check for incorrect use of DotNetObjectRef<T> at the top level. We know it's // an incorrect use if there's a object that looks like { '__dotNetObject': <some number> }, // but we aren't assigning to DotNetObjectRef{T}. if (jsonReader.Read() && jsonReader.TokenType == JsonTokenType.PropertyName && jsonReader.ValueTextEquals(DotNetObjectRefKey.EncodedUtf8Bytes)) { // The JSON payload has the shape we expect from a DotNetObjectRef instance. return !parameterType.IsGenericType || parameterType.GetGenericTypeDefinition() != typeof(DotNetObjectReference<>); } return false; } } finally { ArrayPool<byte>.Shared.Return(buffer); } } /// <summary> /// Receives notification that a call from .NET to JS has finished, marking the /// associated <see cref="Task"/> as completed. /// </summary> /// <remarks> /// All exceptions from <see cref="EndInvokeJS"/> are caught /// are delivered via JS interop to the JavaScript side when it requests confirmation, as /// the mechanism to call <see cref="EndInvokeJS"/> relies on /// using JS->.NET interop. This overload is meant for directly triggering completion callbacks /// for .NET -> JS operations without going through JS interop, so the callsite for this /// method is responsible for handling any possible exception generated from the arguments /// passed in as parameters. /// </remarks> /// <param name="jsRuntime">The <see cref="JSRuntime"/>.</param> /// <param name="arguments">The serialized arguments for the callback completion.</param> /// <exception cref="Exception"> /// This method can throw any exception either from the argument received or as a result /// of executing any callback synchronously upon completion. /// </exception> public static void EndInvokeJS(JSRuntime jsRuntime, string arguments) { var utf8JsonBytes = Encoding.UTF8.GetBytes(arguments); // The payload that we're trying to parse is of the format // [ taskId: long, success: boolean, value: string? | object ] // where value is the .NET type T originally specified on InvokeAsync<T> or the error string if success is false. // We parse the first two arguments and call in to JSRuntimeBase to deserialize the actual value. var reader = new Utf8JsonReader(utf8JsonBytes); if (!reader.Read() || reader.TokenType != JsonTokenType.StartArray) { throw new JsonException("Invalid JSON"); } reader.Read(); var taskId = reader.GetInt64(); reader.Read(); var success = reader.GetBoolean(); reader.Read(); jsRuntime.EndInvokeJS(taskId, success, ref reader); if (!reader.Read() || reader.TokenType != JsonTokenType.EndArray) { throw new JsonException("Invalid JSON"); } } /// <summary> /// Accepts the byte array data being transferred from JS to DotNet. /// </summary> /// <param name="jsRuntime">The <see cref="JSRuntime"/>.</param> /// <param name="id">Identifier for the byte array being transfered.</param> /// <param name="data">Byte array to be transfered from JS.</param> public static void ReceiveByteArray(JSRuntime jsRuntime, int id, byte[] data) { jsRuntime.ReceiveByteArray(id, data); } private static (MethodInfo, Type[]) GetCachedMethodInfo(AssemblyKey assemblyKey, string methodIdentifier) { if (string.IsNullOrWhiteSpace(assemblyKey.AssemblyName)) { throw new ArgumentException($"Property '{nameof(AssemblyKey.AssemblyName)}' cannot be null, empty, or whitespace.", nameof(assemblyKey)); } if (string.IsNullOrWhiteSpace(methodIdentifier)) { throw new ArgumentException("Cannot be null, empty, or whitespace.", nameof(methodIdentifier)); } var assemblyMethods = _cachedMethodsByAssembly.GetOrAdd(assemblyKey, ScanAssemblyForCallableMethods); if (assemblyMethods.TryGetValue(methodIdentifier, out var result)) { return result; } else { throw new ArgumentException($"The assembly '{assemblyKey.AssemblyName}' does not contain a public invokable method with [{nameof(JSInvokableAttribute)}(\"{methodIdentifier}\")]."); } } private static (MethodInfo methodInfo, Type[] parameterTypes) GetCachedMethodInfo(IDotNetObjectReference objectReference, string methodIdentifier) { var type = objectReference.Value.GetType(); var assemblyMethods = _cachedMethodsByType.GetOrAdd(type, ScanTypeForCallableMethods); if (assemblyMethods.TryGetValue(methodIdentifier, out var result)) { return result; } else { throw new ArgumentException($"The type '{type.Name}' does not contain a public invokable method with [{nameof(JSInvokableAttribute)}(\"{methodIdentifier}\")]."); } static Dictionary<string, (MethodInfo, Type[])> ScanTypeForCallableMethods(Type type) { var result = new Dictionary<string, (MethodInfo, Type[])>(StringComparer.Ordinal); foreach (var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public)) { if (method.ContainsGenericParameters || !method.IsDefined(typeof(JSInvokableAttribute), inherit: false)) { continue; } var identifier = method.GetCustomAttribute<JSInvokableAttribute>(false)!.Identifier ?? method.Name!; var parameterTypes = GetParameterTypes(method); if (result.ContainsKey(identifier)) { throw new InvalidOperationException($"The type {type.Name} contains more than one " + $"[JSInvokable] method with identifier '{identifier}'. All [JSInvokable] methods within the same " + "type must have different identifiers. You can pass a custom identifier as a parameter to " + $"the [JSInvokable] attribute."); } result.Add(identifier, (method, parameterTypes)); } return result; } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "We expect application code is configured to ensure JSInvokable methods are retained. https://github.com/dotnet/aspnetcore/issues/29946")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2072", Justification = "We expect application code is configured to ensure JSInvokable methods are retained. https://github.com/dotnet/aspnetcore/issues/29946")] private static Dictionary<string, (MethodInfo, Type[])> ScanAssemblyForCallableMethods(AssemblyKey assemblyKey) { // TODO: Consider looking first for assembly-level attributes (i.e., if there are any, // only use those) to avoid scanning, especially for framework assemblies. var result = new Dictionary<string, (MethodInfo, Type[])>(StringComparer.Ordinal); var exportedTypes = GetRequiredLoadedAssembly(assemblyKey).GetExportedTypes(); foreach (var type in exportedTypes) { foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) { if (method.ContainsGenericParameters || !method.IsDefined(typeof(JSInvokableAttribute), inherit: false)) { continue; } var identifier = method.GetCustomAttribute<JSInvokableAttribute>(false)!.Identifier ?? method.Name; var parameterTypes = GetParameterTypes(method); if (result.ContainsKey(identifier)) { throw new InvalidOperationException($"The assembly '{assemblyKey.AssemblyName}' contains more than one " + $"[JSInvokable] method with identifier '{identifier}'. All [JSInvokable] methods within the same " + $"assembly must have different identifiers. You can pass a custom identifier as a parameter to " + $"the [JSInvokable] attribute."); } result.Add(identifier, (method, parameterTypes)); } } return result; } private static Type[] GetParameterTypes(MethodInfo method) { var parameters = method.GetParameters(); if (parameters.Length == 0) { return Type.EmptyTypes; } var parameterTypes = new Type[parameters.Length]; for (var i = 0; i < parameters.Length; i++) { parameterTypes[i] = parameters[i].ParameterType; } return parameterTypes; } private static Assembly GetRequiredLoadedAssembly(AssemblyKey assemblyKey) { // We don't want to load assemblies on demand here, because we don't necessarily trust // "assemblyName" to be something the developer intended to load. So only pick from the // set of already-loaded assemblies. // In some edge cases this might force developers to explicitly call something on the // target assembly (from .NET) before they can invoke its allowed methods from JS. // Using the last to workaround https://github.com/dotnet/arcade/issues/2816. // In most ordinary scenarios, we wouldn't have two instances of the same Assembly in the AppDomain // so this doesn't change the outcome. Assembly? assembly = null; foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) { if (new AssemblyKey(a).Equals(assemblyKey)) { assembly = a; } } return assembly ?? throw new ArgumentException($"There is no loaded assembly with the name '{assemblyKey.AssemblyName}'."); } private static void ClearCache(Type[]? _) { _cachedMethodsByAssembly.Clear(); _cachedMethodsByType.Clear(); } private readonly struct AssemblyKey : IEquatable<AssemblyKey> { public AssemblyKey(Assembly assembly) { Assembly = assembly; AssemblyName = assembly.GetName().Name!; } public AssemblyKey(string assemblyName) { Assembly = null; AssemblyName = assemblyName; } public Assembly? Assembly { get; } public string AssemblyName { get; } public bool Equals(AssemblyKey other) { if (Assembly != null && other.Assembly != null) { return Assembly == other.Assembly; } return AssemblyName.Equals(other.AssemblyName, StringComparison.Ordinal); } public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(AssemblyName); } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.Compute.V1 { /// <summary>Settings for <see cref="RegionSslCertificatesClient"/> instances.</summary> public sealed partial class RegionSslCertificatesSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="RegionSslCertificatesSettings"/>.</summary> /// <returns>A new instance of the default <see cref="RegionSslCertificatesSettings"/>.</returns> public static RegionSslCertificatesSettings GetDefault() => new RegionSslCertificatesSettings(); /// <summary> /// Constructs a new <see cref="RegionSslCertificatesSettings"/> object with default settings. /// </summary> public RegionSslCertificatesSettings() { } private RegionSslCertificatesSettings(RegionSslCertificatesSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); DeleteSettings = existing.DeleteSettings; DeleteOperationsSettings = existing.DeleteOperationsSettings.Clone(); GetSettings = existing.GetSettings; InsertSettings = existing.InsertSettings; InsertOperationsSettings = existing.InsertOperationsSettings.Clone(); ListSettings = existing.ListSettings; OnCopy(existing); } partial void OnCopy(RegionSslCertificatesSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>RegionSslCertificatesClient.Delete</c> and <c>RegionSslCertificatesClient.DeleteAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings DeleteSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))); /// <summary> /// Long Running Operation settings for calls to <c>RegionSslCertificatesClient.Delete</c> and /// <c>RegionSslCertificatesClient.DeleteAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings DeleteOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>RegionSslCertificatesClient.Get</c> and <c>RegionSslCertificatesClient.GetAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.DeadlineExceeded"/>, /// <see cref="grpccore::StatusCode.Unavailable"/>. /// </description> /// </item> /// <item><description>Timeout: 600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>RegionSslCertificatesClient.Insert</c> and <c>RegionSslCertificatesClient.InsertAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings InsertSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))); /// <summary> /// Long Running Operation settings for calls to <c>RegionSslCertificatesClient.Insert</c> and /// <c>RegionSslCertificatesClient.InsertAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings InsertOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>RegionSslCertificatesClient.List</c> and <c>RegionSslCertificatesClient.ListAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.DeadlineExceeded"/>, /// <see cref="grpccore::StatusCode.Unavailable"/>. /// </description> /// </item> /// <item><description>Timeout: 600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="RegionSslCertificatesSettings"/> object.</returns> public RegionSslCertificatesSettings Clone() => new RegionSslCertificatesSettings(this); } /// <summary> /// Builder class for <see cref="RegionSslCertificatesClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> public sealed partial class RegionSslCertificatesClientBuilder : gaxgrpc::ClientBuilderBase<RegionSslCertificatesClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public RegionSslCertificatesSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public RegionSslCertificatesClientBuilder() { UseJwtAccessWithScopes = RegionSslCertificatesClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref RegionSslCertificatesClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<RegionSslCertificatesClient> task); /// <summary>Builds the resulting client.</summary> public override RegionSslCertificatesClient Build() { RegionSslCertificatesClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<RegionSslCertificatesClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<RegionSslCertificatesClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private RegionSslCertificatesClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return RegionSslCertificatesClient.Create(callInvoker, Settings); } private async stt::Task<RegionSslCertificatesClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return RegionSslCertificatesClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => RegionSslCertificatesClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => RegionSslCertificatesClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => RegionSslCertificatesClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => ComputeRestAdapter.ComputeAdapter; } /// <summary>RegionSslCertificates client wrapper, for convenient use.</summary> /// <remarks> /// The RegionSslCertificates API. /// </remarks> public abstract partial class RegionSslCertificatesClient { /// <summary> /// The default endpoint for the RegionSslCertificates service, which is a host of "compute.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "compute.googleapis.com:443"; /// <summary>The default RegionSslCertificates scopes.</summary> /// <remarks> /// The default RegionSslCertificates scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/compute</description></item> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="RegionSslCertificatesClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="RegionSslCertificatesClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="RegionSslCertificatesClient"/>.</returns> public static stt::Task<RegionSslCertificatesClient> CreateAsync(st::CancellationToken cancellationToken = default) => new RegionSslCertificatesClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="RegionSslCertificatesClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="RegionSslCertificatesClientBuilder"/>. /// </summary> /// <returns>The created <see cref="RegionSslCertificatesClient"/>.</returns> public static RegionSslCertificatesClient Create() => new RegionSslCertificatesClientBuilder().Build(); /// <summary> /// Creates a <see cref="RegionSslCertificatesClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="RegionSslCertificatesSettings"/>.</param> /// <returns>The created <see cref="RegionSslCertificatesClient"/>.</returns> internal static RegionSslCertificatesClient Create(grpccore::CallInvoker callInvoker, RegionSslCertificatesSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } RegionSslCertificates.RegionSslCertificatesClient grpcClient = new RegionSslCertificates.RegionSslCertificatesClient(callInvoker); return new RegionSslCertificatesClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC RegionSslCertificates client</summary> public virtual RegionSslCertificates.RegionSslCertificatesClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Deletes the specified SslCertificate resource in the region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Operation, Operation> Delete(DeleteRegionSslCertificateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes the specified SslCertificate resource in the region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(DeleteRegionSslCertificateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes the specified SslCertificate resource in the region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(DeleteRegionSslCertificateRequest request, st::CancellationToken cancellationToken) => DeleteAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>Delete</c>.</summary> public virtual lro::OperationsClient DeleteOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>Delete</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<Operation, Operation> PollOnceDelete(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Operation, Operation>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of <c>Delete</c> /// . /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> PollOnceDeleteAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Operation, Operation>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteOperationsClient, callSettings); /// <summary> /// Deletes the specified SslCertificate resource in the region. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region scoping this request. /// </param> /// <param name="sslCertificate"> /// Name of the SslCertificate resource to delete. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Operation, Operation> Delete(string project, string region, string sslCertificate, gaxgrpc::CallSettings callSettings = null) => Delete(new DeleteRegionSslCertificateRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), SslCertificate = gax::GaxPreconditions.CheckNotNullOrEmpty(sslCertificate, nameof(sslCertificate)), }, callSettings); /// <summary> /// Deletes the specified SslCertificate resource in the region. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region scoping this request. /// </param> /// <param name="sslCertificate"> /// Name of the SslCertificate resource to delete. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(string project, string region, string sslCertificate, gaxgrpc::CallSettings callSettings = null) => DeleteAsync(new DeleteRegionSslCertificateRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), SslCertificate = gax::GaxPreconditions.CheckNotNullOrEmpty(sslCertificate, nameof(sslCertificate)), }, callSettings); /// <summary> /// Deletes the specified SslCertificate resource in the region. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region scoping this request. /// </param> /// <param name="sslCertificate"> /// Name of the SslCertificate resource to delete. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(string project, string region, string sslCertificate, st::CancellationToken cancellationToken) => DeleteAsync(project, region, sslCertificate, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the specified SslCertificate resource in the specified region. Get a list of available SSL certificates by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual SslCertificate Get(GetRegionSslCertificateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the specified SslCertificate resource in the specified region. Get a list of available SSL certificates by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<SslCertificate> GetAsync(GetRegionSslCertificateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the specified SslCertificate resource in the specified region. Get a list of available SSL certificates by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<SslCertificate> GetAsync(GetRegionSslCertificateRequest request, st::CancellationToken cancellationToken) => GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the specified SslCertificate resource in the specified region. Get a list of available SSL certificates by making a list() request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region scoping this request. /// </param> /// <param name="sslCertificate"> /// Name of the SslCertificate resource to return. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual SslCertificate Get(string project, string region, string sslCertificate, gaxgrpc::CallSettings callSettings = null) => Get(new GetRegionSslCertificateRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), SslCertificate = gax::GaxPreconditions.CheckNotNullOrEmpty(sslCertificate, nameof(sslCertificate)), }, callSettings); /// <summary> /// Returns the specified SslCertificate resource in the specified region. Get a list of available SSL certificates by making a list() request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region scoping this request. /// </param> /// <param name="sslCertificate"> /// Name of the SslCertificate resource to return. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<SslCertificate> GetAsync(string project, string region, string sslCertificate, gaxgrpc::CallSettings callSettings = null) => GetAsync(new GetRegionSslCertificateRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), SslCertificate = gax::GaxPreconditions.CheckNotNullOrEmpty(sslCertificate, nameof(sslCertificate)), }, callSettings); /// <summary> /// Returns the specified SslCertificate resource in the specified region. Get a list of available SSL certificates by making a list() request. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region scoping this request. /// </param> /// <param name="sslCertificate"> /// Name of the SslCertificate resource to return. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<SslCertificate> GetAsync(string project, string region, string sslCertificate, st::CancellationToken cancellationToken) => GetAsync(project, region, sslCertificate, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates a SslCertificate resource in the specified project and region using the data included in the request /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Operation, Operation> Insert(InsertRegionSslCertificateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a SslCertificate resource in the specified project and region using the data included in the request /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(InsertRegionSslCertificateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a SslCertificate resource in the specified project and region using the data included in the request /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(InsertRegionSslCertificateRequest request, st::CancellationToken cancellationToken) => InsertAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>Insert</c>.</summary> public virtual lro::OperationsClient InsertOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>Insert</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<Operation, Operation> PollOnceInsert(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Operation, Operation>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), InsertOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of <c>Insert</c> /// . /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> PollOnceInsertAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Operation, Operation>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), InsertOperationsClient, callSettings); /// <summary> /// Creates a SslCertificate resource in the specified project and region using the data included in the request /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region scoping this request. /// </param> /// <param name="sslCertificateResource"> /// The body resource for this request /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Operation, Operation> Insert(string project, string region, SslCertificate sslCertificateResource, gaxgrpc::CallSettings callSettings = null) => Insert(new InsertRegionSslCertificateRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), SslCertificateResource = gax::GaxPreconditions.CheckNotNull(sslCertificateResource, nameof(sslCertificateResource)), }, callSettings); /// <summary> /// Creates a SslCertificate resource in the specified project and region using the data included in the request /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region scoping this request. /// </param> /// <param name="sslCertificateResource"> /// The body resource for this request /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(string project, string region, SslCertificate sslCertificateResource, gaxgrpc::CallSettings callSettings = null) => InsertAsync(new InsertRegionSslCertificateRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), SslCertificateResource = gax::GaxPreconditions.CheckNotNull(sslCertificateResource, nameof(sslCertificateResource)), }, callSettings); /// <summary> /// Creates a SslCertificate resource in the specified project and region using the data included in the request /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region scoping this request. /// </param> /// <param name="sslCertificateResource"> /// The body resource for this request /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(string project, string region, SslCertificate sslCertificateResource, st::CancellationToken cancellationToken) => InsertAsync(project, region, sslCertificateResource, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Retrieves the list of SslCertificate resources available to the specified project in the specified region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="SslCertificate"/> resources.</returns> public virtual gax::PagedEnumerable<SslCertificateList, SslCertificate> List(ListRegionSslCertificatesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves the list of SslCertificate resources available to the specified project in the specified region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="SslCertificate"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<SslCertificateList, SslCertificate> ListAsync(ListRegionSslCertificatesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves the list of SslCertificate resources available to the specified project in the specified region. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region scoping this request. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="SslCertificate"/> resources.</returns> public virtual gax::PagedEnumerable<SslCertificateList, SslCertificate> List(string project, string region, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => List(new ListRegionSslCertificatesRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Retrieves the list of SslCertificate resources available to the specified project in the specified region. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="region"> /// Name of the region scoping this request. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="SslCertificate"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<SslCertificateList, SslCertificate> ListAsync(string project, string region, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListAsync(new ListRegionSslCertificatesRequest { Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); } /// <summary>RegionSslCertificates client wrapper implementation, for convenient use.</summary> /// <remarks> /// The RegionSslCertificates API. /// </remarks> public sealed partial class RegionSslCertificatesClientImpl : RegionSslCertificatesClient { private readonly gaxgrpc::ApiCall<DeleteRegionSslCertificateRequest, Operation> _callDelete; private readonly gaxgrpc::ApiCall<GetRegionSslCertificateRequest, SslCertificate> _callGet; private readonly gaxgrpc::ApiCall<InsertRegionSslCertificateRequest, Operation> _callInsert; private readonly gaxgrpc::ApiCall<ListRegionSslCertificatesRequest, SslCertificateList> _callList; /// <summary> /// Constructs a client wrapper for the RegionSslCertificates service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="RegionSslCertificatesSettings"/> used within this client.</param> public RegionSslCertificatesClientImpl(RegionSslCertificates.RegionSslCertificatesClient grpcClient, RegionSslCertificatesSettings settings) { GrpcClient = grpcClient; RegionSslCertificatesSettings effectiveSettings = settings ?? RegionSslCertificatesSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); DeleteOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClientForRegionOperations(), effectiveSettings.DeleteOperationsSettings); InsertOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClientForRegionOperations(), effectiveSettings.InsertOperationsSettings); _callDelete = clientHelper.BuildApiCall<DeleteRegionSslCertificateRequest, Operation>(grpcClient.DeleteAsync, grpcClient.Delete, effectiveSettings.DeleteSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("region", request => request.Region).WithGoogleRequestParam("ssl_certificate", request => request.SslCertificate); Modify_ApiCall(ref _callDelete); Modify_DeleteApiCall(ref _callDelete); _callGet = clientHelper.BuildApiCall<GetRegionSslCertificateRequest, SslCertificate>(grpcClient.GetAsync, grpcClient.Get, effectiveSettings.GetSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("region", request => request.Region).WithGoogleRequestParam("ssl_certificate", request => request.SslCertificate); Modify_ApiCall(ref _callGet); Modify_GetApiCall(ref _callGet); _callInsert = clientHelper.BuildApiCall<InsertRegionSslCertificateRequest, Operation>(grpcClient.InsertAsync, grpcClient.Insert, effectiveSettings.InsertSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("region", request => request.Region); Modify_ApiCall(ref _callInsert); Modify_InsertApiCall(ref _callInsert); _callList = clientHelper.BuildApiCall<ListRegionSslCertificatesRequest, SslCertificateList>(grpcClient.ListAsync, grpcClient.List, effectiveSettings.ListSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("region", request => request.Region); Modify_ApiCall(ref _callList); Modify_ListApiCall(ref _callList); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_DeleteApiCall(ref gaxgrpc::ApiCall<DeleteRegionSslCertificateRequest, Operation> call); partial void Modify_GetApiCall(ref gaxgrpc::ApiCall<GetRegionSslCertificateRequest, SslCertificate> call); partial void Modify_InsertApiCall(ref gaxgrpc::ApiCall<InsertRegionSslCertificateRequest, Operation> call); partial void Modify_ListApiCall(ref gaxgrpc::ApiCall<ListRegionSslCertificatesRequest, SslCertificateList> call); partial void OnConstruction(RegionSslCertificates.RegionSslCertificatesClient grpcClient, RegionSslCertificatesSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC RegionSslCertificates client</summary> public override RegionSslCertificates.RegionSslCertificatesClient GrpcClient { get; } partial void Modify_DeleteRegionSslCertificateRequest(ref DeleteRegionSslCertificateRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GetRegionSslCertificateRequest(ref GetRegionSslCertificateRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_InsertRegionSslCertificateRequest(ref InsertRegionSslCertificateRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListRegionSslCertificatesRequest(ref ListRegionSslCertificatesRequest request, ref gaxgrpc::CallSettings settings); /// <summary>The long-running operations client for <c>Delete</c>.</summary> public override lro::OperationsClient DeleteOperationsClient { get; } /// <summary> /// Deletes the specified SslCertificate resource in the region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<Operation, Operation> Delete(DeleteRegionSslCertificateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteRegionSslCertificateRequest(ref request, ref callSettings); Operation response = _callDelete.Sync(request, callSettings); GetRegionOperationRequest pollRequest = GetRegionOperationRequest.FromInitialResponse(response); request.PopulatePollRequestFields(pollRequest); return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), DeleteOperationsClient); } /// <summary> /// Deletes the specified SslCertificate resource in the region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(DeleteRegionSslCertificateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteRegionSslCertificateRequest(ref request, ref callSettings); Operation response = await _callDelete.Async(request, callSettings).ConfigureAwait(false); GetRegionOperationRequest pollRequest = GetRegionOperationRequest.FromInitialResponse(response); request.PopulatePollRequestFields(pollRequest); return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), DeleteOperationsClient); } /// <summary> /// Returns the specified SslCertificate resource in the specified region. Get a list of available SSL certificates by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override SslCertificate Get(GetRegionSslCertificateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetRegionSslCertificateRequest(ref request, ref callSettings); return _callGet.Sync(request, callSettings); } /// <summary> /// Returns the specified SslCertificate resource in the specified region. Get a list of available SSL certificates by making a list() request. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<SslCertificate> GetAsync(GetRegionSslCertificateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetRegionSslCertificateRequest(ref request, ref callSettings); return _callGet.Async(request, callSettings); } /// <summary>The long-running operations client for <c>Insert</c>.</summary> public override lro::OperationsClient InsertOperationsClient { get; } /// <summary> /// Creates a SslCertificate resource in the specified project and region using the data included in the request /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<Operation, Operation> Insert(InsertRegionSslCertificateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_InsertRegionSslCertificateRequest(ref request, ref callSettings); Operation response = _callInsert.Sync(request, callSettings); GetRegionOperationRequest pollRequest = GetRegionOperationRequest.FromInitialResponse(response); request.PopulatePollRequestFields(pollRequest); return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), InsertOperationsClient); } /// <summary> /// Creates a SslCertificate resource in the specified project and region using the data included in the request /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<Operation, Operation>> InsertAsync(InsertRegionSslCertificateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_InsertRegionSslCertificateRequest(ref request, ref callSettings); Operation response = await _callInsert.Async(request, callSettings).ConfigureAwait(false); GetRegionOperationRequest pollRequest = GetRegionOperationRequest.FromInitialResponse(response); request.PopulatePollRequestFields(pollRequest); return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), InsertOperationsClient); } /// <summary> /// Retrieves the list of SslCertificate resources available to the specified project in the specified region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="SslCertificate"/> resources.</returns> public override gax::PagedEnumerable<SslCertificateList, SslCertificate> List(ListRegionSslCertificatesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListRegionSslCertificatesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListRegionSslCertificatesRequest, SslCertificateList, SslCertificate>(_callList, request, callSettings); } /// <summary> /// Retrieves the list of SslCertificate resources available to the specified project in the specified region. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="SslCertificate"/> resources.</returns> public override gax::PagedAsyncEnumerable<SslCertificateList, SslCertificate> ListAsync(ListRegionSslCertificatesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListRegionSslCertificatesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListRegionSslCertificatesRequest, SslCertificateList, SslCertificate>(_callList, request, callSettings); } } public partial class ListRegionSslCertificatesRequest : gaxgrpc::IPageRequest { /// <inheritdoc/> public int PageSize { get => checked((int)MaxResults); set => MaxResults = checked((uint)value); } } public partial class SslCertificateList : gaxgrpc::IPageResponse<SslCertificate> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<SslCertificate> GetEnumerator() => Items.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public static partial class RegionSslCertificates { public partial class RegionSslCertificatesClient { /// <summary> /// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as /// this client, delegating to RegionOperations. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual lro::Operations.OperationsClient CreateOperationsClientForRegionOperations() => RegionOperations.RegionOperationsClient.CreateOperationsClient(CallInvoker); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using Codentia.Common.Logging; namespace Codentia.Common.Logging.DL { /// <summary> /// FileLogWriter implements ILogWriter and provides a file-based data store for logging. /// </summary> public class FileLogWriter : ILogWriter { private static object _fileLock = new object(); private bool _isOpen = false; private FileStream _outputStream = null; private StreamWriter _outputWriter = null; private string _logTarget = null; #region ILogWriter Members /// <summary> /// Gets or sets the LogTarget (file path + name) /// </summary> public string LogTarget { get { return _logTarget; } set { if (string.IsNullOrEmpty(value)) { throw new Exception("Invalid LogTarget specified"); } if (value.Contains("_APP_")) { // value = value.Replace("~APP~", Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)); value = value.Replace("_APP_", Environment.CurrentDirectory); } // ensure path exists here string[] parts = value.Split(@"\".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); string pathSoFar = string.Empty; for (int i = 0; i < parts.Length; i++) { if (parts[i].Contains(".")) { break; } else { pathSoFar = string.Format("{0}{1}{2}", pathSoFar, pathSoFar.Length > 0 ? @"\" : string.Empty, parts[i]); if (!Directory.Exists(pathSoFar)) { Directory.CreateDirectory(pathSoFar); } } } _logTarget = value; } } /// <summary> /// Write a given message to the log. /// </summary> /// <param name="message">Message to be written</param> public void Write(LogMessage message) { lock (_fileLock) { if (!_isOpen) { Open(); } _outputWriter.WriteLine(string.Format("{0} - {1} [{2}] {3}", message.Timestamp.ToString("yyyy/MM/dd HH:mm:ss"), message.Type.ToString(), message.Source, message.Message)); } } /// <summary> /// Write a set of messages to the log, one after the other (in incremental order) /// </summary> /// <param name="messages">Array of messages to be written, in order</param> public void Write(LogMessage[] messages) { for (int i = 0; i < messages.Length; i++) { Write(messages[i]); } } /// <summary> /// Open this LogWriter /// </summary> public void Open() { if (_logTarget == null) { throw new Exception("Cannot start FileLogWriter without setting LogTarget"); } if (!_isOpen) { OpenWithRetry(); } } /// <summary> /// Close this LogWriter /// </summary> public void Close() { if (_isOpen) { _outputWriter.Flush(); _outputWriter.Close(); _outputStream.Close(); _isOpen = false; } } /// <summary> /// Perform clean-up of files. Roll over when maximum size is exceeded, delete when number of roll-overs is exceeded. /// </summary> /// <param name="rollOverSizeKB">File size at which to consider roll-over</param> /// <param name="rollOverFileLimit">Number of roll-over files to be kept (newest first)</param> /// <param name="retentionDates">This is not used</param> public void CleanUp(int rollOverSizeKB, int rollOverFileLimit, Dictionary<LogMessageType, DateTime> retentionDates) { lock (_fileLock) { Close(); // is roll-over required? if (File.Exists(this.LogTarget)) { FileInfo fi = new FileInfo(this.LogTarget); if ((Convert.ToDecimal(fi.Length) / 1024.0m) > Convert.ToDecimal(rollOverSizeKB)) { // we need to roll-over // check if we need to purge other files string path = string.Format("{0}{1}", Path.GetDirectoryName(this.LogTarget), @"\"); string filePattern = this.LogTarget.Substring(this.LogTarget.LastIndexOf(@"\") + 1, this.LogTarget.Length - (this.LogTarget.LastIndexOf(@"\") + 1)); string[] files = Directory.GetFiles(path, string.Format("{0}_*", filePattern)); // too many files do or will exist while (files.Length >= rollOverFileLimit) { int maxFile = 0; // delete any out of range files for (int i = 0; i < files.Length; i++) { string[] current = files[i].Split("_".ToCharArray(), StringSplitOptions.None); int file = Convert.ToInt32(current[current.Length - 1]); if (file > maxFile) { maxFile = file; } } // delete the highest found if (maxFile > 0) { File.Delete(string.Format("{0}{1}_{2}", path, filePattern, maxFile)); } files = Directory.GetFiles(path, string.Format("{0}_*", filePattern)); } // now shuffle file names files = Directory.GetFiles(path, string.Format("{0}_*", filePattern)); List<string> fileList = new List<string>(); fileList.AddRange(files); while (File.Exists(string.Format("{0}{1}_1", path, filePattern))) { int maxFile = 0; int maxFileIndex = 0; // delete any out of range files for (int j = 0; j < fileList.Count; j++) { string[] current = fileList[j].Split("_".ToCharArray(), StringSplitOptions.None); int file = Convert.ToInt32(current[current.Length - 1]); if (file > maxFile) { maxFile = file; maxFileIndex = j; } } if (maxFile > 0) { File.Move(string.Format("{0}{1}_{2}", path, filePattern, maxFile), string.Format("{0}{1}_{2}", path, filePattern, maxFile + 1)); fileList.RemoveAt(maxFileIndex); } } File.Move(this.LogTarget, string.Format("{0}{1}_{2}", path, filePattern, 1)); } } Open(); } } #endregion #region IDisposable Members /// <summary> /// Dispose this LogWriter /// </summary> public void Dispose() { if (_isOpen) { Close(); } if (_outputStream != null) { _outputWriter.Dispose(); _outputStream.Dispose(); _outputWriter = null; _outputStream = null; } } #endregion private void OpenWithRetry() { OpenWithRetry(0); } private void OpenWithRetry(int counter) { try { _outputStream = new FileStream(_logTarget, FileMode.OpenOrCreate); _outputWriter = new StreamWriter(_outputStream); _outputWriter.BaseStream.Seek(0, SeekOrigin.End); _isOpen = true; } catch (Exception ex) { if (counter < 5) { System.Threading.Thread.Sleep(10); counter++; OpenWithRetry(counter); } else { throw new Exception("Unable to open output streams", ex); } } } } }
using System; using System.Data; using System.Data.OleDb; using System.Text.RegularExpressions; namespace BLToolkit.Data.DataProvider { using Mapping; using Sql.SqlProvider; public class AccessDataProvider : OleDbDataProvider { private static Regex _paramsExp; // Based on idea from http://qapi.blogspot.com/2006/12/deriveparameters-oledbprovider-ii.html // public override bool DeriveParameters(IDbCommand command) { if (command == null) throw new ArgumentNullException("command"); if (command.CommandType != CommandType.StoredProcedure) throw new InvalidOperationException("command.CommandType must be CommandType.StoredProcedure"); var conn = command.Connection as OleDbConnection; if (conn == null || conn.State != ConnectionState.Open) throw new InvalidOperationException("Invalid connection state."); command.Parameters.Clear(); var dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Procedures, new object[]{null, null, command.CommandText}); if (dt.Rows.Count == 0) { // Jet does convert parameretless procedures to views. // dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Views, new object[]{null, null, command.CommandText}); if (dt.Rows.Count == 0) throw new DataException(string.Format("Stored procedure '{0}' not found", command.CommandText)); // Do nothing. There is no parameters. // } else { var col = dt.Columns["PROCEDURE_DEFINITION"]; if (col == null) { // Not really possible // return false; } if (_paramsExp == null) _paramsExp = new Regex(@"PARAMETERS ((\[(?<name>[^\]]+)\]|(?<name>[^\s]+))\s(?<type>[^,;\s]+(\s\([^\)]+\))?)[,;]\s)*", RegexOptions.Compiled | RegexOptions.ExplicitCapture); var match = _paramsExp.Match((string)dt.Rows[0][col.Ordinal]); var names = match.Groups["name"].Captures; var types = match.Groups["type"].Captures; if (names.Count != types.Count) { // Not really possible // return false; } var separators = new[] {' ', '(', ',', ')'}; for (var i = 0; i < names.Count; ++i) { var paramName = names[i].Value; var rawType = types[i].Value.Split(separators, StringSplitOptions.RemoveEmptyEntries); var p = new OleDbParameter(paramName, GetOleDbType(rawType[0])); if (rawType.Length > 2) { p.Precision = Common.Convert.ToByte(rawType[1]); p.Scale = Common.Convert.ToByte(rawType[2]); } else if (rawType.Length > 1) { p.Size = Common.Convert.ToInt32(rawType[1]); } command.Parameters.Add(p); } } return true; } private static OleDbType GetOleDbType(string jetType) { switch (jetType.ToLower()) { case "byte": case "tinyint": case "integer1": return OleDbType.TinyInt; case "short": case "smallint": case "integer2": return OleDbType.SmallInt; case "int": case "integer": case "long": case "integer4": case "counter": case "identity": case "autoincrement": return OleDbType.Integer; case "single": case "real": case "float4": case "ieeesingle": return OleDbType.Single; case "double": case "number": case "double precision": case "float": case "float8": case "ieeedouble": return OleDbType.Double; case "currency": case "money": return OleDbType.Currency; case "dec": case "decimal": case "numeric": return OleDbType.Decimal; case "bit": case "yesno": case "logical": case "logical1": return OleDbType.Boolean; case "datetime": case "date": case "time": return OleDbType.Date; case "alphanumeric": case "char": case "character": case "character varying": case "national char": case "national char varying": case "national character": case "national character varying": case "nchar": case "string": case "text": case "varchar": return OleDbType.VarWChar; case "longchar": case "longtext": case "memo": case "note": case "ntext": return OleDbType.LongVarWChar; case "binary": case "varbinary": case "binary varying": case "bit varying": return OleDbType.VarBinary; case "longbinary": case "image": case "general": case "oleobject": return OleDbType.LongVarBinary; case "guid": case "uniqueidentifier": return OleDbType.Guid; default: // Each release of Jet brings many new aliases to existing types. // This list may be outdated, please send a report to us. // throw new NotSupportedException("Unknown DB type '" + jetType + "'"); } } public override void AttachParameter(IDbCommand command, IDbDataParameter parameter) { // Do some magic to workaround 'Data type mismatch in criteria expression' error // in JET for some european locales. // if (parameter.Value is DateTime) { // OleDbType.DBTimeStamp is locale aware, OleDbType.Date is locale neutral. // ((OleDbParameter)parameter).OleDbType = OleDbType.Date; } else if (parameter.Value is decimal) { // OleDbType.Decimal is locale aware, OleDbType.Currency is locale neutral. // ((OleDbParameter)parameter).OleDbType = OleDbType.Currency; } base.AttachParameter(command, parameter); } public new const string NameString = DataProvider.ProviderName.Access; public override string Name { get { return NameString; } } public override int MaxBatchSize { get { return 0; } } public override ISqlProvider CreateSqlProvider() { return new AccessSqlProvider(); } public override object Convert(object value, ConvertType convertType) { switch (convertType) { case ConvertType.ExceptionToErrorNumber: if (value is OleDbException) { var ex = (OleDbException)value; if (ex.Errors.Count > 0) return ex.Errors[0].NativeError; } break; } return SqlProvider.Convert(value, convertType); } #region DataReaderEx public override IDataReader GetDataReader(MappingSchema schema, IDataReader dataReader) { return dataReader is OleDbDataReader? new DataReaderEx((OleDbDataReader)dataReader): base.GetDataReader(schema, dataReader); } class DataReaderEx : DataReaderBase<OleDbDataReader>, IDataReader { public DataReaderEx(OleDbDataReader rd): base(rd) { } public new object GetValue(int i) { var value = DataReader.GetValue(i); if (value is DateTime) { var dt = (DateTime)value; if (dt.Year == 1899 && dt.Month == 12 && dt.Day == 30) return new DateTime(1, 1, 1, dt.Hour, dt.Minute, dt.Second, dt.Millisecond); } return value; } public new DateTime GetDateTime(int i) { var dt = DataReader.GetDateTime(i); if (dt.Year == 1899 && dt.Month == 12 && dt.Day == 30) return new DateTime(1, 1, 1, dt.Hour, dt.Minute, dt.Second, dt.Millisecond); return dt; } } #endregion } }
using NUnit.Framework; using SimpleContainer.Configuration; using SimpleContainer.Infection; using SimpleContainer.Interface; using SimpleContainer.Tests.Helpers; namespace SimpleContainer.Tests.Contracts { public abstract class ContractsNestingTest : SimpleContainerTestBase { public class NestedRequiredContracts : ContractsNestingTest { public class A { public readonly B b; public readonly C cx; public readonly C cy; public readonly C c; public A([TestContract("x")] B b, [TestContract("x")] C cx, [TestContract("y")] C cy, C c) { this.b = b; this.cx = cx; this.cy = cy; this.c = c; } } public class B { public readonly C c; public B([TestContract("y")] C c) { this.c = c; } } public class C { public readonly string context; public C(string context) { this.context = context; } } [Test] public void Test() { var container = Container(delegate(ContainerConfigurationBuilder b) { b.Contract("x", "y").BindDependency<C>("context", "xy"); b.Contract("x").BindDependency<C>("context", "x"); b.Contract("y").BindDependency<C>("context", "y"); b.BindDependency<C>("context", "empty"); }); var a = container.Get<A>(); Assert.That(a.b.c.context, Is.EqualTo("xy")); Assert.That(a.cx.context, Is.EqualTo("x")); Assert.That(a.cy.context, Is.EqualTo("y")); Assert.That(a.c.context, Is.EqualTo("empty")); Assert.That(container.Resolve<A>().GetConstructionLog(), Is.StringStarting("A\r\n\tB[x]\r\n\t\tC[x->y]\r\n\t\t\tcontext -> xy")); } } public class CanUseContractOnContractConfiguratorForRestriction : ContractsNestingTest { public class Contract1Attribute : RequireContractAttribute { public Contract1Attribute() : base("contract-1") { } } public class Contract2Attribute : RequireContractAttribute { public Contract2Attribute() : base("contract-2") { } } public class A { public readonly B contract1B; public readonly B b; public A([Contract1] B contract1B, B b) { this.contract1B = contract1B; this.b = b; } } public class B { public readonly C c; public B([Contract2] C c) { this.c = c; } } public class C { public readonly int parameter; public C(int parameter) { this.parameter = parameter; } } public class CConfigurator : IServiceConfigurator<C> { public void Configure(ConfigurationContext context, ServiceConfigurationBuilder<C> builder) { builder.Contract<Contract1Attribute>().Contract<Contract2Attribute>().Dependencies(new { parameter = 1 }); builder.Contract<Contract2Attribute>().Dependencies(new { parameter = 2 }); } } [Test] public void Test() { var container = Container(); var a = container.Get<A>(); Assert.That(a.contract1B.c.parameter, Is.EqualTo(1)); Assert.That(a.b.c.parameter, Is.EqualTo(2)); } } public class NotDefinedContractsCanBeUsedLaterToRestrictOtherContracts : ContractsNestingTest { [TestContract("a")] public class A { public readonly X x; public A(X x) { this.x = x; } } [TestContract("b")] public class B { public readonly X x; public B(X x) { this.x = x; } } [TestContract("x")] public class X { public readonly int parameter; public X(int parameter) { this.parameter = parameter; } } [Test] public void Test() { var container = Container(delegate(ContainerConfigurationBuilder builder) { builder.Contract("a", "x").BindDependency<X>("parameter", 1); builder.Contract("b", "x").BindDependency<X>("parameter", 2); }); Assert.That(container.Get<A>().x.parameter, Is.EqualTo(1)); Assert.That(container.Get<B>().x.parameter, Is.EqualTo(2)); } } public class CanDeclareContractsChain : ContractsNestingTest { [ContractsSequence(typeof (ContractX), typeof (ContractY))] public class Axy { public readonly B b; public Axy(B b) { this.b = b; } } public class Ayx { public readonly B b; public Ayx([ContractsSequence(typeof (ContractY), typeof (ContractX))] B b) { this.b = b; } } public class B { public readonly string contracts; public B(string contracts) { this.contracts = contracts; } } public class ContractX : RequireContractAttribute { public ContractX() : base("x") { } } public class ContractY : RequireContractAttribute { public ContractY() : base("y") { } } [Test] public void Test() { var container = Container(delegate(ContainerConfigurationBuilder builder) { builder.Contract<ContractX>().Contract<ContractY>().BindDependencies<B>(new {contracts = "xy"}); builder.Contract<ContractY>().Contract<ContractX>().BindDependencies<B>(new {contracts = "yx"}); }); Assert.That(container.Get<Axy>().b.contracts, Is.EqualTo("xy")); Assert.That(container.Get<Ayx>().b.contracts, Is.EqualTo("yx")); } } public class ConditionalContractsRedefinitionIsProhibited : ContractsNestingTest { [TestContract("c1")] public class A { public readonly B b; public A([TestContract("c2")] B b) { this.b = b; } } [TestContract("c2")] public class B { public readonly int parameter; public B(int parameter) { this.parameter = parameter; } } [Test] public void Test() { var container = Container(b => b.Contract("c1").Contract("c2").BindDependency<B>("parameter", 42)); var exception = Assert.Throws<SimpleContainerException>(() => container.Get<A>()); Assert.That(exception.Message, Is.EqualTo("contract [c2] already declared, stack\r\n\tA[c1]\r\n\tB[c2->c2]\r\n\r\n!A\r\n\t!B <---------------")); } } } }
/* * [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 { using System.Collections.Generic; using ArgumentException = System.ArgumentException; using Console = System.Console; using Math = System.Math; using DebuggerDisplay = System.Diagnostics.DebuggerDisplayAttribute; using Exception = System.Exception; using StringBuilder = System.Text.StringBuilder; using Type = System.Type; /** Useful for dumping out the input stream after doing some * augmentation or other manipulations. * * You can insert stuff, replace, and delete chunks. Note that the * operations are done lazily--only if you convert the buffer to a * String. This is very efficient because you are not moving data around * all the time. As the buffer of tokens is converted to strings, the * toString() method(s) check to see if there is an operation at the * current index. If so, the operation is done and then normal String * rendering continues on the buffer. This is like having multiple Turing * machine instruction streams (programs) operating on a single input tape. :) * * Since the operations are done lazily at toString-time, operations do not * screw up the token index values. That is, an insert operation at token * index i does not change the index values for tokens i+1..n-1. * * Because operations never actually alter the buffer, you may always get * the original token stream back without undoing anything. Since * the instructions are queued up, you can easily simulate transactions and * roll back any changes if there is an error just by removing instructions. * For example, * * CharStream input = new ANTLRFileStream("input"); * TLexer lex = new TLexer(input); * TokenRewriteStream tokens = new TokenRewriteStream(lex); * T parser = new T(tokens); * parser.startRule(); * * Then in the rules, you can execute * Token t,u; * ... * input.insertAfter(t, "text to put after t");} * input.insertAfter(u, "text after u");} * System.out.println(tokens.toString()); * * Actually, you have to cast the 'input' to a TokenRewriteStream. :( * * You can also have multiple "instruction streams" and get multiple * rewrites from a single pass over the input. Just name the instruction * streams and use that name again when printing the buffer. This could be * useful for generating a C file and also its header file--all from the * same buffer: * * tokens.insertAfter("pass1", t, "text to put after t");} * tokens.insertAfter("pass2", u, "text after u");} * System.out.println(tokens.toString("pass1")); * System.out.println(tokens.toString("pass2")); * * If you don't use named rewrite streams, a "default" stream is used as * the first example shows. */ [System.Serializable] [DebuggerDisplay( "TODO: TokenRewriteStream debugger display" )] public class TokenRewriteStream : CommonTokenStream { public const string DEFAULT_PROGRAM_NAME = "default"; public const int PROGRAM_INIT_SIZE = 100; public const int MIN_TOKEN_INDEX = 0; // Define the rewrite operation hierarchy protected class RewriteOperation { /** <summary>What index into rewrites List are we?</summary> */ public int instructionIndex; /** <summary>Token buffer index.</summary> */ public int index; public object text; // outer protected TokenRewriteStream stream; protected RewriteOperation(TokenRewriteStream stream, int index) { this.stream = stream; this.index = index; } protected RewriteOperation( TokenRewriteStream stream, int index, object text ) { this.index = index; this.text = text; this.stream = stream; } /** <summary> * Execute the rewrite operation by possibly adding to the buffer. * Return the index of the next token to operate on. * </summary> */ public virtual int Execute( StringBuilder buf ) { return index; } public override string ToString() { string opName = this.GetType().Name; int dindex = opName.IndexOf( '$' ); opName = opName.Substring( dindex + 1 ); return string.Format("<{0}@{1}:\"{2}\">", opName, stream._tokens[index], text); } } private class InsertBeforeOp : RewriteOperation { public InsertBeforeOp( TokenRewriteStream stream, int index, object text ) : base( stream, index, text ) { } public override int Execute( StringBuilder buf ) { buf.Append( text ); if (stream._tokens[index].Type != CharStreamConstants.EndOfFile) buf.Append(stream._tokens[index].Text); return index + 1; } } /** <summary> * I'm going to try replacing range from x..y with (y-x)+1 ReplaceOp * instructions. * </summary> */ private class ReplaceOp : RewriteOperation { public int lastIndex; public ReplaceOp( TokenRewriteStream stream, int from, int to, object text ) : base( stream, from, text ) { lastIndex = to; } public override int Execute( StringBuilder buf ) { if ( text != null ) { buf.Append( text ); } return lastIndex + 1; } public override string ToString() { if (text == null) { return string.Format("<DeleteOp@{0}..{1}>", stream._tokens[index], stream._tokens[lastIndex]); } return string.Format("<ReplaceOp@{0}..{1}:\"{2}\">", stream._tokens[index], stream._tokens[lastIndex], text); } } /** <summary> * You may have multiple, named streams of rewrite operations. * I'm calling these things "programs." * Maps String (name) -> rewrite (List) * </summary> */ protected IDictionary<string, IList<RewriteOperation>> programs = null; /** <summary>Map String (program name) -> Integer index</summary> */ protected IDictionary<string, int> lastRewriteTokenIndexes = null; public TokenRewriteStream() { Init(); } protected void Init() { programs = new Dictionary<string, IList<RewriteOperation>>(); programs[DEFAULT_PROGRAM_NAME] = new List<RewriteOperation>( PROGRAM_INIT_SIZE ); lastRewriteTokenIndexes = new Dictionary<string, int>(); } public TokenRewriteStream( ITokenSource tokenSource ) : base( tokenSource ) { Init(); } public TokenRewriteStream( ITokenSource tokenSource, int channel ) : base( tokenSource, channel ) { Init(); } public virtual void Rollback( int instructionIndex ) { Rollback( DEFAULT_PROGRAM_NAME, instructionIndex ); } /** <summary> * Rollback the instruction stream for a program so that * the indicated instruction (via instructionIndex) is no * longer in the stream. UNTESTED! * </summary> */ public virtual void Rollback( string programName, int instructionIndex ) { IList<RewriteOperation> @is; if ( programs.TryGetValue( programName, out @is ) && @is != null ) { List<RewriteOperation> sublist = new List<RewriteOperation>(); for ( int i = MIN_TOKEN_INDEX; i <= instructionIndex; i++ ) sublist.Add( @is[i] ); programs[programName] = sublist; } } public virtual void DeleteProgram() { DeleteProgram( DEFAULT_PROGRAM_NAME ); } /** <summary>Reset the program so that no instructions exist</summary> */ public virtual void DeleteProgram( string programName ) { Rollback( programName, MIN_TOKEN_INDEX ); } public virtual void InsertAfter( IToken t, object text ) { InsertAfter( DEFAULT_PROGRAM_NAME, t, text ); } public virtual void InsertAfter( int index, object text ) { InsertAfter( DEFAULT_PROGRAM_NAME, index, text ); } public virtual void InsertAfter( string programName, IToken t, object text ) { InsertAfter( programName, t.TokenIndex, text ); } public virtual void InsertAfter( string programName, int index, object text ) { // to insert after, just insert before next index (even if past end) InsertBefore( programName, index + 1, text ); } public virtual void InsertBefore( IToken t, object text ) { InsertBefore( DEFAULT_PROGRAM_NAME, t, text ); } public virtual void InsertBefore( int index, object text ) { InsertBefore( DEFAULT_PROGRAM_NAME, index, text ); } public virtual void InsertBefore( string programName, IToken t, object text ) { InsertBefore( programName, t.TokenIndex, text ); } public virtual void InsertBefore( string programName, int index, object text ) { RewriteOperation op = new InsertBeforeOp( this, index, text ); IList<RewriteOperation> rewrites = GetProgram( programName ); op.instructionIndex = rewrites.Count; rewrites.Add( op ); } public virtual void Replace( int index, object text ) { Replace( DEFAULT_PROGRAM_NAME, index, index, text ); } public virtual void Replace( int from, int to, object text ) { Replace( DEFAULT_PROGRAM_NAME, from, to, text ); } public virtual void Replace( IToken indexT, object text ) { Replace( DEFAULT_PROGRAM_NAME, indexT, indexT, text ); } public virtual void Replace( IToken from, IToken to, object text ) { Replace( DEFAULT_PROGRAM_NAME, from, to, text ); } public virtual void Replace( string programName, int from, int to, object text ) { if ( from > to || from < 0 || to < 0 || to >= _tokens.Count ) { throw new ArgumentException( "replace: range invalid: " + from + ".." + to + "(size=" + _tokens.Count + ")" ); } RewriteOperation op = new ReplaceOp( this, from, to, text ); IList<RewriteOperation> rewrites = GetProgram( programName ); op.instructionIndex = rewrites.Count; rewrites.Add( op ); } public virtual void Replace( string programName, IToken from, IToken to, object text ) { Replace( programName, from.TokenIndex, to.TokenIndex, text ); } public virtual void Delete( int index ) { Delete( DEFAULT_PROGRAM_NAME, index, index ); } public virtual void Delete( int from, int to ) { Delete( DEFAULT_PROGRAM_NAME, from, to ); } public virtual void Delete( IToken indexT ) { Delete( DEFAULT_PROGRAM_NAME, indexT, indexT ); } public virtual void Delete( IToken from, IToken to ) { Delete( DEFAULT_PROGRAM_NAME, from, to ); } public virtual void Delete( string programName, int from, int to ) { Replace( programName, from, to, null ); } public virtual void Delete( string programName, IToken from, IToken to ) { Replace( programName, from, to, null ); } public virtual int GetLastRewriteTokenIndex() { return GetLastRewriteTokenIndex( DEFAULT_PROGRAM_NAME ); } protected virtual int GetLastRewriteTokenIndex( string programName ) { int value; if ( lastRewriteTokenIndexes.TryGetValue( programName, out value ) ) return value; return -1; } protected virtual void SetLastRewriteTokenIndex( string programName, int i ) { lastRewriteTokenIndexes[programName] = i; } protected virtual IList<RewriteOperation> GetProgram( string name ) { IList<RewriteOperation> @is; if ( !programs.TryGetValue( name, out @is ) || @is == null ) { @is = InitializeProgram( name ); } return @is; } private IList<RewriteOperation> InitializeProgram( string name ) { IList<RewriteOperation> @is = new List<RewriteOperation>( PROGRAM_INIT_SIZE ); programs[name] = @is; return @is; } public virtual string ToOriginalString() { Fill(); return ToOriginalString( MIN_TOKEN_INDEX, Count - 1 ); } public virtual string ToOriginalString( int start, int end ) { StringBuilder buf = new StringBuilder(); for ( int i = start; i >= MIN_TOKEN_INDEX && i <= end && i < _tokens.Count; i++ ) { if (Get(i).Type != CharStreamConstants.EndOfFile) buf.Append(Get(i).Text); } return buf.ToString(); } public override string ToString() { Fill(); return ToString( MIN_TOKEN_INDEX, Count - 1 ); } public virtual string ToString( string programName ) { Fill(); return ToString(programName, MIN_TOKEN_INDEX, Count - 1); } public override string ToString( int start, int end ) { return ToString( DEFAULT_PROGRAM_NAME, start, end ); } public virtual string ToString( string programName, int start, int end ) { IList<RewriteOperation> rewrites; if ( !programs.TryGetValue( programName, out rewrites ) ) rewrites = null; // ensure start/end are in range if ( end > _tokens.Count - 1 ) end = _tokens.Count - 1; if ( start < 0 ) start = 0; if ( rewrites == null || rewrites.Count == 0 ) { return ToOriginalString( start, end ); // no instructions to execute } StringBuilder buf = new StringBuilder(); // First, optimize instruction stream IDictionary<int, RewriteOperation> indexToOp = ReduceToSingleOperationPerIndex( rewrites ); // Walk buffer, executing instructions and emitting tokens int i = start; while ( i <= end && i < _tokens.Count ) { RewriteOperation op; bool exists = indexToOp.TryGetValue( i, out op ); if ( exists ) { // remove so any left have index size-1 indexToOp.Remove( i ); } if ( !exists || op == null ) { IToken t = _tokens[i]; // no operation at that index, just dump token if (t.Type != CharStreamConstants.EndOfFile) buf.Append(t.Text); i++; // move to next token } else { i = op.Execute( buf ); // execute operation and skip } } // include stuff after end if it's last index in buffer // So, if they did an insertAfter(lastValidIndex, "foo"), include // foo if end==lastValidIndex. if ( end == _tokens.Count - 1 ) { // Scan any remaining operations after last token // should be included (they will be inserts). foreach ( RewriteOperation op in indexToOp.Values ) { if ( op.index >= _tokens.Count - 1 ) buf.Append( op.text ); } } return buf.ToString(); } /** We need to combine operations and report invalid operations (like * overlapping replaces that are not completed nested). Inserts to * same index need to be combined etc... Here are the cases: * * I.i.u I.j.v leave alone, nonoverlapping * I.i.u I.i.v combine: Iivu * * R.i-j.u R.x-y.v | i-j in x-y delete first R * R.i-j.u R.i-j.v delete first R * R.i-j.u R.x-y.v | x-y in i-j ERROR * R.i-j.u R.x-y.v | boundaries overlap ERROR * * Delete special case of replace (text==null): * D.i-j.u D.x-y.v | boundaries overlap combine to max(min)..max(right) * * I.i.u R.x-y.v | i in (x+1)-y delete I (since insert before * we're not deleting i) * I.i.u R.x-y.v | i not in (x+1)-y leave alone, nonoverlapping * R.x-y.v I.i.u | i in x-y ERROR * R.x-y.v I.x.u R.x-y.uv (combine, delete I) * R.x-y.v I.i.u | i not in x-y leave alone, nonoverlapping * * I.i.u = insert u before op @ index i * R.x-y.u = replace x-y indexed tokens with u * * First we need to examine replaces. For any replace op: * * 1. wipe out any insertions before op within that range. * 2. Drop any replace op before that is contained completely within * that range. * 3. Throw exception upon boundary overlap with any previous replace. * * Then we can deal with inserts: * * 1. for any inserts to same index, combine even if not adjacent. * 2. for any prior replace with same left boundary, combine this * insert with replace and delete this replace. * 3. throw exception if index in same range as previous replace * * Don't actually delete; make op null in list. Easier to walk list. * Later we can throw as we add to index -> op map. * * Note that I.2 R.2-2 will wipe out I.2 even though, technically, the * inserted stuff would be before the replace range. But, if you * add tokens in front of a method body '{' and then delete the method * body, I think the stuff before the '{' you added should disappear too. * * Return a map from token index to operation. */ protected virtual IDictionary<int, RewriteOperation> ReduceToSingleOperationPerIndex( IList<RewriteOperation> rewrites ) { //System.out.println("rewrites="+rewrites); // WALK REPLACES for ( int i = 0; i < rewrites.Count; i++ ) { RewriteOperation op = rewrites[i]; if ( op == null ) continue; if ( !( op is ReplaceOp ) ) continue; ReplaceOp rop = (ReplaceOp)rewrites[i]; // Wipe prior inserts within range var inserts = GetKindOfOps( rewrites, typeof( InsertBeforeOp ), i ); for ( int j = 0; j < inserts.Count; j++ ) { InsertBeforeOp iop = (InsertBeforeOp)inserts[j]; if (iop.index == rop.index) { // E.g., insert before 2, delete 2..2; update replace // text to include insert before, kill insert rewrites[iop.instructionIndex] = null; rop.text = iop.text.ToString() + (rop.text != null ? rop.text.ToString() : string.Empty); } else if (iop.index > rop.index && iop.index <= rop.lastIndex) { // delete insert as it's a no-op. rewrites[iop.instructionIndex] = null; } } // Drop any prior replaces contained within var prevReplaces = GetKindOfOps( rewrites, typeof( ReplaceOp ), i ); for ( int j = 0; j < prevReplaces.Count; j++ ) { ReplaceOp prevRop = (ReplaceOp)prevReplaces[j]; if ( prevRop.index >= rop.index && prevRop.lastIndex <= rop.lastIndex ) { // delete replace as it's a no-op. rewrites[prevRop.instructionIndex] = null; continue; } // throw exception unless disjoint or identical bool disjoint = prevRop.lastIndex < rop.index || prevRop.index > rop.lastIndex; bool same = prevRop.index == rop.index && prevRop.lastIndex == rop.lastIndex; // Delete special case of replace (text==null): // D.i-j.u D.x-y.v | boundaries overlap combine to max(min)..max(right) if (prevRop.text == null && rop.text == null && !disjoint) { //System.out.println("overlapping deletes: "+prevRop+", "+rop); rewrites[prevRop.instructionIndex] = null; // kill first delete rop.index = Math.Min(prevRop.index, rop.index); rop.lastIndex = Math.Max(prevRop.lastIndex, rop.lastIndex); Console.WriteLine("new rop " + rop); } else if ( !disjoint && !same ) { throw new ArgumentException( "replace op boundaries of " + rop + " overlap with previous " + prevRop ); } } } // WALK INSERTS for ( int i = 0; i < rewrites.Count; i++ ) { RewriteOperation op = (RewriteOperation)rewrites[i]; if ( op == null ) continue; if ( !( op is InsertBeforeOp ) ) continue; InsertBeforeOp iop = (InsertBeforeOp)rewrites[i]; // combine current insert with prior if any at same index var prevInserts = GetKindOfOps( rewrites, typeof( InsertBeforeOp ), i ); for ( int j = 0; j < prevInserts.Count; j++ ) { InsertBeforeOp prevIop = (InsertBeforeOp)prevInserts[j]; if ( prevIop.index == iop.index ) { // combine objects // convert to strings...we're in process of toString'ing // whole token buffer so no lazy eval issue with any templates iop.text = CatOpText( iop.text, prevIop.text ); // delete redundant prior insert rewrites[prevIop.instructionIndex] = null; } } // look for replaces where iop.index is in range; error var prevReplaces = GetKindOfOps( rewrites, typeof( ReplaceOp ), i ); for ( int j = 0; j < prevReplaces.Count; j++ ) { ReplaceOp rop = (ReplaceOp)prevReplaces[j]; if ( iop.index == rop.index ) { rop.text = CatOpText( iop.text, rop.text ); rewrites[i] = null; // delete current insert continue; } if ( iop.index >= rop.index && iop.index <= rop.lastIndex ) { throw new ArgumentException( "insert op " + iop + " within boundaries of previous " + rop ); } } } // System.out.println("rewrites after="+rewrites); IDictionary<int, RewriteOperation> m = new Dictionary<int, RewriteOperation>(); for ( int i = 0; i < rewrites.Count; i++ ) { RewriteOperation op = (RewriteOperation)rewrites[i]; if ( op == null ) continue; // ignore deleted ops RewriteOperation existing; if ( m.TryGetValue( op.index, out existing ) && existing != null ) { throw new Exception( "should only be one op per index" ); } m[op.index] = op; } //System.out.println("index to op: "+m); return m; } protected virtual string CatOpText( object a, object b ) { return string.Concat( a, b ); } protected virtual IList<RewriteOperation> GetKindOfOps( IList<RewriteOperation> rewrites, Type kind ) { return GetKindOfOps( rewrites, kind, rewrites.Count ); } /** <summary>Get all operations before an index of a particular kind</summary> */ protected virtual IList<RewriteOperation> GetKindOfOps( IList<RewriteOperation> rewrites, Type kind, int before ) { IList<RewriteOperation> ops = new List<RewriteOperation>(); for ( int i = 0; i < before && i < rewrites.Count; i++ ) { RewriteOperation op = rewrites[i]; if ( op == null ) continue; // ignore deleted if ( op.GetType() == kind ) ops.Add( op ); } return ops; } public virtual string ToDebugString() { return ToDebugString( MIN_TOKEN_INDEX, Count - 1 ); } public virtual string ToDebugString( int start, int end ) { StringBuilder buf = new StringBuilder(); for ( int i = start; i >= MIN_TOKEN_INDEX && i <= end && i < _tokens.Count; i++ ) { buf.Append( Get( i ) ); } return buf.ToString(); } } }
//--------------------------------------------------------------------------- // // <copyright file="M3DUtil.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: Collection of utility classes for the Media3D namespace. // //--------------------------------------------------------------------------- using MS.Utility; using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows; using System.Windows.Media; using System.Windows.Media.Media3D; namespace MS.Internal.Media3D { internal static class M3DUtil { // Returns the interpolated 3D point from the given positions and barycentric // coordinate. // // NOTE: v0-v2 and barycentric are passed by ref for performance. They are // not modified. // internal static Point3D Interpolate(ref Point3D v0, ref Point3D v1, ref Point3D v2, ref Point barycentric) { double v = barycentric.X; double w = barycentric.Y; double u = 1 - v - w; return new Point3D(u*v0.X + v*v1.X + w*v2.X, u*v0.Y + v*v1.Y + w*v2.Y, u*v0.Z + v*v1.Z + w*v2.Z); } // Helper method for compiting the bounds of a set of points. The given point // is added to the bounds of the given Rect3D. The point/bounds are both passed // by reference for perf. Only the bounds may be modified. private static void AddPointToBounds(ref Point3D point, ref Rect3D bounds) { Debug.Assert(!bounds.IsEmpty, "Caller should construct the Rect3D from the first point before calling this method."); if (point.X < bounds.X) { bounds.SizeX += (bounds.X - point.X); bounds.X = point.X; } else if (point.X > (bounds.X + bounds.SizeX)) { bounds.SizeX = point.X - bounds.X; } if (point.Y < bounds.Y) { bounds.SizeY += (bounds.Y - point.Y); bounds.Y = point.Y; } else if (point.Y > (bounds.Y + bounds.SizeY)) { bounds.SizeY = point.Y - bounds.Y; } if (point.Z < bounds.Z) { bounds.SizeZ += (bounds.Z - point.Z); bounds.Z = point.Z; } else if (point.Z > (bounds.Z + bounds.SizeZ)) { bounds.SizeZ = point.Z - bounds.Z; } #if NEVER // Because we do not store rectangles as TLRB (+ another dimension in 3D) // we need to compute SizeX/Y/Z which involves subtraction and introduces // cancelation so this assert isn't accurate. Debug.Assert(bounds.Contains(point), "Error detect - bounds did not contain point on exit."); #endif } // Computes an axis aligned bounding box that contains the given set of points. internal static Rect3D ComputeAxisAlignedBoundingBox(Point3DCollection positions) { if (positions != null) { FrugalStructList<Point3D> points = positions._collection; if (points.Count != 0) { Point3D p = points[0]; Rect3D newBounds = new Rect3D(p.X, p.Y, p.Z, 0, 0, 0); for(int i = 1; i < points.Count; i++) { p = points[i]; M3DUtil.AddPointToBounds(ref p, ref newBounds); } return newBounds; } } return Rect3D.Empty; } // Returns a new axis aligned bounding box that contains the old // bounding box post the given transformation. internal static Rect3D ComputeTransformedAxisAlignedBoundingBox(/* IN */ ref Rect3D originalBox, Transform3D transform) { if (transform == null || transform == Transform3D.Identity) { return originalBox; } Matrix3D matrix = transform.Value; return ComputeTransformedAxisAlignedBoundingBox(ref originalBox, ref matrix); } // Returns a new axis aligned bounding box that contains the old // bounding box post the given transformation. internal static Rect3D ComputeTransformedAxisAlignedBoundingBox( /* IN */ ref Rect3D originalBox, /* IN */ ref Matrix3D matrix) { if (originalBox.IsEmpty) { return originalBox; } if (matrix.IsAffine) { return ComputeTransformedAxisAlignedBoundingBoxAffine(ref originalBox, ref matrix); } else { return ComputeTransformedAxisAlignedBoundingBoxNonAffine(ref originalBox, ref matrix); } } // CTAABB for an affine transforms internal static Rect3D ComputeTransformedAxisAlignedBoundingBoxAffine(/* IN */ ref Rect3D originalBox, /* IN */ ref Matrix3D matrix) { Debug.Assert(matrix.IsAffine); // Based on Arvo's paper "Transforming Axis-Aligned Bounding Boxes" // from the original Graphics Gems book. Specifically, this code // is based on Figure 1 which is for a box stored as min and // max points. Our bounding boxes are stored as a min point and // a diagonal so we'll convert when needed. Also, we have row // vectors. // // Mapping Arvo's variables to ours: // A - the untransformed box (originalBox) // B - the transformed box (what we return at the end) // M - the rotation + scale (matrix.Mji) // T - the translation (matrix.Offset?) // // for i = 1 ... 3 // Bmin_i = Bmax_i = T_i // for j = 1 ... 3 // a = M_ij * Amin_j // b = M_ij * Amax_j // Bmin_i += min(a, b) // Bmax_i += max(a, b) // // Matrix3D doesn't have indexers because they're too slow so we'll // have to unroll the loops. A complete unroll of both loops was // found to be the fastest. double oldMaxX = originalBox.X + originalBox.SizeX; double oldMaxY = originalBox.Y + originalBox.SizeY; double oldMaxZ = originalBox.Z + originalBox.SizeZ; // i = 1 (X) double newMinX = matrix.OffsetX; double newMaxX = matrix.OffsetX; { // i = 1 (X), j = 1 (X) double a = matrix.M11 * originalBox.X; double b = matrix.M11 * oldMaxX; if (b > a) { newMinX += a; newMaxX += b; } else { newMinX += b; newMaxX += a; } // i = 1 (X), j = 2 (Y) a = matrix.M21 * originalBox.Y; b = matrix.M21 * oldMaxY; if (b > a) { newMinX += a; newMaxX += b; } else { newMinX += b; newMaxX += a; } // i = 1 (X), j = 3 (Z) a = matrix.M31 * originalBox.Z; b = matrix.M31 * oldMaxZ; if (b > a) { newMinX += a; newMaxX += b; } else { newMinX += b; newMaxX += a; } } // i = 2 (Y) double newMinY = matrix.OffsetY; double newMaxY = matrix.OffsetY; { // i = 2 (Y), j = 1 (X) double a = matrix.M12 * originalBox.X; double b = matrix.M12 * oldMaxX; if (b > a) { newMinY += a; newMaxY += b; } else { newMinY += b; newMaxY += a; } // i = 2 (Y), j = 2 (Y) a = matrix.M22 * originalBox.Y; b = matrix.M22 * oldMaxY; if (b > a) { newMinY += a; newMaxY += b; } else { newMinY += b; newMaxY += a; } // i = 2 (Y), j = 3 (Z) a = matrix.M32 * originalBox.Z; b = matrix.M32 * oldMaxZ; if (b > a) { newMinY += a; newMaxY += b; } else { newMinY += b; newMaxY += a; } } // i = 3 (Z) double newMinZ = matrix.OffsetZ; double newMaxZ = matrix.OffsetZ; { // i = 3 (Z), j = 1 (X) double a = matrix.M13 * originalBox.X; double b = matrix.M13 * oldMaxX; if (b > a) { newMinZ += a; newMaxZ += b; } else { newMinZ += b; newMaxZ += a; } // i = 3 (Z), j = 2 (Y) a = matrix.M23 * originalBox.Y; b = matrix.M23 * oldMaxY; if (b > a) { newMinZ += a; newMaxZ += b; } else { newMinZ += b; newMaxZ += a; } // i = 3 (Z), j = 3 (Z) a = matrix.M33 * originalBox.Z; b = matrix.M33 * oldMaxZ; if (b > a) { newMinZ += a; newMaxZ += b; } else { newMinZ += b; newMaxZ += a; } } return new Rect3D(newMinX, newMinY, newMinZ, newMaxX - newMinX, newMaxY - newMinY, newMaxZ - newMinZ); } // CTAABB for non-affine transformations internal static Rect3D ComputeTransformedAxisAlignedBoundingBoxNonAffine(/* IN */ ref Rect3D originalBox, /* IN */ ref Matrix3D matrix) { Debug.Assert(!matrix.IsAffine); double x1 = originalBox.X; double y1 = originalBox.Y; double z1 = originalBox.Z; double x2 = originalBox.X + originalBox.SizeX; double y2 = originalBox.Y + originalBox.SizeY; double z2 = originalBox.Z + originalBox.SizeZ; Point3D[] points = new Point3D[] { new Point3D(x1, y1, z1), new Point3D(x1, y1, z2), new Point3D(x1, y2, z1), new Point3D(x1, y2, z2), new Point3D(x2, y1, z1), new Point3D(x2, y1, z2), new Point3D(x2, y2, z1), new Point3D(x2, y2, z2), }; matrix.Transform(points); Point3D p = points[0]; Rect3D newBounds = new Rect3D(p.X, p.Y, p.Z, 0, 0, 0); // Traverse the entire mesh and compute bounding box. for(int i = 1; i < points.Length; i++) { p = points[i]; AddPointToBounds(ref p, ref newBounds); } return newBounds; } // Returns the aspect ratio of the given size. internal static double GetAspectRatio(Size viewSize) { return viewSize.Width / viewSize.Height; } // Normalizes the point in the given size to the range [-1, 1]. internal static Point GetNormalizedPoint(Point point, Size size) { return new Point( ((2*point.X)/size.Width) - 1, -(((2*point.Y)/size.Height) - 1)); } internal static double RadiansToDegrees(double radians) { return radians*(180.0/Math.PI); } internal static double DegreesToRadians(double degrees) { return degrees*(Math.PI/180.0); } internal static Matrix3D GetWorldToViewportTransform3D(Camera camera, Rect viewport) { Debug.Assert(camera != null, "Caller is responsible for ensuring camera is not null."); return camera.GetViewMatrix() * camera.GetProjectionMatrix(M3DUtil.GetAspectRatio(viewport.Size)) * M3DUtil.GetHomogeneousToViewportTransform3D(viewport); } /// <summary> /// GetHomogeneousToViewportTransform3D. /// /// Returns a matrix that performs the coordinate system change from /// /// 1 /// | /// -1 --------|------ 1 /// | /// -1 /// /// /// (Viewport.X, Viewport.Y) ---------- (Viewport.X + Viewport.Width, 0) /// | /// | /// | /// (Viewport.X, Viewport.Y + Viewport.Height) /// /// In other words, the viewport transform stretches the normalized coordinate /// system of [(-1, 1):(1, -1)] into the Viewport. /// </summary> internal static Matrix3D GetHomogeneousToViewportTransform3D(Rect viewport) { // Matrix3D scaling = new Matrix3D( // 1, 0, 0, 0, // 0, -1, 0, 0, // 0, 0, 1, 0, // 0, 0, 0, 1); // // Matrix3D translation = new Matrix3D( // 1, 0, 0, 0, // 0, 1, 0, 0, // 0, 0, 1, 0, // 1, 1, 0, 1); // // scaling * translation // // // == // // 1, 0, 0, 0, // 0, -1, 0, 0, // 0, 0, 1, 0, // 1, 1, 0, 1 // // // Matrix3D viewportScale = new Matrix3D( // Viewport.Width / 2, 0, 0, 0, // 0, Viewport.Height / 2, 0, 0, // 0, 0, 1, 0, // 0, 0, 0, 1); // // // * viewportScale // // == // // vw/2, 0, 0, 0, // 0, -vh/2, 0, 0, // 0, 0, 1, 0, // vw/2, vh/2, 0, 1, // // // Matrix3D viewportOffset = new Matrix3D( // 1, 0, 0, 0, // 0, 1, 0, 0, // 0, 0, 1, 0, // Viewport.X, Viewport.Y, 0, 1); // // // * viewportOffset // // == // // vw/2, 0, 0, 0, // 0, -vh/2, 0, 0, // 0, 0, 1, 0, // vw/2+vx, vh/2+vy, 0, 1 double sx = viewport.Width / 2; // half viewport width double sy = viewport.Height / 2; // half viewport height double tx = viewport.X + sx; double ty = viewport.Y + sy; return new Matrix3D( sx, 0, 0, 0, 0 , -sy, 0, 0, 0 , 0, 1, 0, tx, ty, 0, 1); } /// <summary> /// Same as GetHomogeneousToViewportTransform3D but returns a 2D matrix. /// For detailed comments see: GetHomogeneousToViewportTransform3D /// </summary> internal static Matrix GetHomogeneousToViewportTransform(Rect viewport) { double sx = viewport.Width / 2; // half viewport width double sy = viewport.Height / 2; // half viewport height double tx = viewport.X + sx; double ty = viewport.Y + sy; return new Matrix( sx, 0, 0 , -sy, tx, ty); } /// <summary> /// Gets the object space to world space transformation for the given Visual3D /// </summary> /// <param name="visual">The visual whose world space transform should be found</param> /// <returns>The world space transformation</returns> internal static Matrix3D GetWorldTransformationMatrix(Visual3D visual) { Viewport3DVisual ignored; return GetWorldTransformationMatrix(visual, out ignored); } /// <summary> /// Gets the object space to world space transformation for the given Visual3D /// </summary> /// <param name="visual3DStart">The visual whose world space transform should be found</param> /// <param name="viewport">The containing Viewport3D for the Visual3D</param> /// <returns>The world space transformation</returns> internal static Matrix3D GetWorldTransformationMatrix(Visual3D visual3DStart, out Viewport3DVisual viewport) { DependencyObject dependencyObject = visual3DStart; Matrix3D worldTransform = Matrix3D.Identity; while (dependencyObject != null) { Visual3D visual3D = dependencyObject as Visual3D; // we reached the top if (visual3D == null) { break; } Transform3D transform = (Transform3D)visual3D.GetValue(Visual3D.TransformProperty); if (transform != null) { transform.Append(ref worldTransform); } dependencyObject = VisualTreeHelper.GetParent(dependencyObject); } if (dependencyObject != null) { viewport = (Viewport3DVisual)dependencyObject; } else { viewport = null; } return worldTransform; } /// <summary> /// Computes the transformation matrix to go from a 3D point in the given Visual3D's coordinate space out in to /// the Viewport3DVisual. /// </summary> internal static bool TryTransformToViewport3DVisual(Visual3D visual3D, out Viewport3DVisual viewport, out Matrix3D matrix) { matrix = GetWorldTransformationMatrix(visual3D, out viewport); if (viewport != null) { matrix *= GetWorldToViewportTransform3D(viewport.Camera, viewport.Viewport); return true; } else { return false; } } /// <summary> /// Function tests to see if the given texture coordinate point p is contained within the /// given triangle. If it is it returns the 3D point corresponding to that intersection. /// </summary> /// <param name="p">The point to test</param> /// <param name="triUVVertices">The texture coordinates of the triangle</param> /// <param name="tri3DVertices">The 3D coordinates of the triangle</param> /// <param name="inters3DPoint">The 3D point of intersection</param> /// <returns>True if the point is in the triangle, false otherwise</returns> internal static bool IsPointInTriangle(Point p, Point[] triUVVertices, Point3D[] tri3DVertices, out Point3D inters3DPoint) { double denom = 0.0; inters3DPoint = new Point3D(); // // get the barycentric coordinates and then use these to test if the point is in the triangle // any standard math reference on barycentric coordinates will give the derivation for the below // parameters. // double A = triUVVertices[0].X - triUVVertices[2].X; double B = triUVVertices[1].X - triUVVertices[2].X; double C = triUVVertices[2].X - p.X; double D = triUVVertices[0].Y - triUVVertices[2].Y; double E = triUVVertices[1].Y - triUVVertices[2].Y; double F = triUVVertices[2].Y - p.Y; denom = (A * E - B * D); if (denom == 0) { return false; } double lambda1 = (B * F - C * E) / denom; denom = (B * D - A * E); if (denom == 0) { return false; } double lambda2 = (A * F - C * D) / denom; if (lambda1 < 0 || lambda1 > 1 || lambda2 < 0 || lambda2 > 1 || (lambda1 + lambda2) > 1) { return false; } inters3DPoint = (Point3D)(lambda1 * (Vector3D)tri3DVertices[0] + lambda2 * (Vector3D)tri3DVertices[1] + (1.0f - lambda1 - lambda2) * (Vector3D)tri3DVertices[2]); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; namespace System.Collections.Specialized { /// <summary> /// This enum describes the action that caused a CollectionChanged event. /// </summary> public enum NotifyCollectionChangedAction { /// <summary> One or more items were added to the collection. </summary> Add, /// <summary> One or more items were removed from the collection. </summary> Remove, /// <summary> One or more items were replaced in the collection. </summary> Replace, /// <summary> One or more items were moved within the collection. </summary> Move, /// <summary> The contents of the collection changed dramatically. </summary> Reset, } /// <summary> /// Arguments for the CollectionChanged event. /// A collection that supports INotifyCollectionChangedThis raises this event /// whenever an item is added or removed, or when the contents of the collection /// changes dramatically. /// </summary> public class NotifyCollectionChangedEventArgs : EventArgs { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a reset change. /// </summary> /// <param name="action">The action that caused the event (must be Reset).</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action) { if (action != NotifyCollectionChangedAction.Reset) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Reset), nameof(action)); InitializeAdd(action, null, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item change. /// </summary> /// <param name="action">The action that caused the event; can only be Reset, Add or Remove action.</param> /// <param name="changedItem">The item affected by the change.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.MustBeResetAddOrRemoveActionForCtor, nameof(action)); if (action == NotifyCollectionChangedAction.Reset) { if (changedItem != null) throw new ArgumentException(SR.ResetActionRequiresNullItem, nameof(action)); InitializeAdd(action, null, -1); } else { InitializeAddOrRemove(action, new object[] { changedItem }, -1); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item change. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItem">The item affected by the change.</param> /// <param name="index">The index where the change occurred.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem, int index) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.MustBeResetAddOrRemoveActionForCtor, nameof(action)); if (action == NotifyCollectionChangedAction.Reset) { if (changedItem != null) throw new ArgumentException(SR.ResetActionRequiresNullItem, nameof(action)); if (index != -1) throw new ArgumentException(SR.ResetActionRequiresIndexMinus1, nameof(action)); InitializeAdd(action, null, -1); } else { InitializeAddOrRemove(action, new object[] { changedItem }, index); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item change. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.MustBeResetAddOrRemoveActionForCtor, nameof(action)); if (action == NotifyCollectionChangedAction.Reset) { if (changedItems != null) throw new ArgumentException(SR.ResetActionRequiresNullItem, nameof(action)); InitializeAdd(action, null, -1); } else { if (changedItems == null) throw new ArgumentNullException(nameof(changedItems)); InitializeAddOrRemove(action, changedItems, -1); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item change (or a reset). /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> /// <param name="startingIndex">The index where the change occurred.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems, int startingIndex) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.MustBeResetAddOrRemoveActionForCtor, nameof(action)); if (action == NotifyCollectionChangedAction.Reset) { if (changedItems != null) throw new ArgumentException(SR.ResetActionRequiresNullItem, nameof(action)); if (startingIndex != -1) throw new ArgumentException(SR.ResetActionRequiresIndexMinus1, nameof(action)); InitializeAdd(action, null, -1); } else { if (changedItems == null) throw new ArgumentNullException(nameof(changedItems)); if (startingIndex < -1) throw new ArgumentException(SR.IndexCannotBeNegative, nameof(startingIndex)); InitializeAddOrRemove(action, changedItems, startingIndex); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItem">The new item replacing the original item.</param> /// <param name="oldItem">The original item that is replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object newItem, object oldItem) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), nameof(action)); InitializeMoveOrReplace(action, new object[] { newItem }, new object[] { oldItem }, -1, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItem">The new item replacing the original item.</param> /// <param name="oldItem">The original item that is replaced.</param> /// <param name="index">The index of the item being replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object newItem, object oldItem, int index) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), nameof(action)); InitializeMoveOrReplace(action, new object[] { newItem }, new object[] { oldItem }, index, index); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItems">The new items replacing the original items.</param> /// <param name="oldItems">The original items that are replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), nameof(action)); if (newItems == null) throw new ArgumentNullException(nameof(newItems)); if (oldItems == null) throw new ArgumentNullException(nameof(oldItems)); InitializeMoveOrReplace(action, newItems, oldItems, -1, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItems">The new items replacing the original items.</param> /// <param name="oldItems">The original items that are replaced.</param> /// <param name="startingIndex">The starting index of the items being replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int startingIndex) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), nameof(action)); if (newItems == null) throw new ArgumentNullException(nameof(newItems)); if (oldItems == null) throw new ArgumentNullException(nameof(oldItems)); InitializeMoveOrReplace(action, newItems, oldItems, startingIndex, startingIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Move event. /// </summary> /// <param name="action">Can only be a Move action.</param> /// <param name="changedItem">The item affected by the change.</param> /// <param name="index">The new index for the changed item.</param> /// <param name="oldIndex">The old index for the changed item.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem, int index, int oldIndex) { if (action != NotifyCollectionChangedAction.Move) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Move), nameof(action)); if (index < 0) throw new ArgumentException(SR.IndexCannotBeNegative, nameof(index)); object[] changedItems = new object[] { changedItem }; InitializeMoveOrReplace(action, changedItems, changedItems, index, oldIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Move event. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> /// <param name="index">The new index for the changed items.</param> /// <param name="oldIndex">The old index for the changed items.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems, int index, int oldIndex) { if (action != NotifyCollectionChangedAction.Move) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Move), nameof(action)); if (index < 0) throw new ArgumentException(SR.IndexCannotBeNegative, nameof(index)); InitializeMoveOrReplace(action, changedItems, changedItems, index, oldIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs with given fields (no validation). Used by WinRT marshaling. /// </summary> internal NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int newIndex, int oldIndex) { _action = action; _newItems = (newItems == null) ? null : new ReadOnlyList(newItems); _oldItems = (oldItems == null) ? null : new ReadOnlyList(oldItems); _newStartingIndex = newIndex; _oldStartingIndex = oldIndex; } private void InitializeAddOrRemove(NotifyCollectionChangedAction action, IList changedItems, int startingIndex) { if (action == NotifyCollectionChangedAction.Add) InitializeAdd(action, changedItems, startingIndex); else if (action == NotifyCollectionChangedAction.Remove) InitializeRemove(action, changedItems, startingIndex); else Debug.Assert(false, String.Format("Unsupported action: {0}", action.ToString())); } private void InitializeAdd(NotifyCollectionChangedAction action, IList newItems, int newStartingIndex) { _action = action; _newItems = (newItems == null) ? null : new ReadOnlyList(newItems); _newStartingIndex = newStartingIndex; } private void InitializeRemove(NotifyCollectionChangedAction action, IList oldItems, int oldStartingIndex) { _action = action; _oldItems = (oldItems == null) ? null : new ReadOnlyList(oldItems); _oldStartingIndex = oldStartingIndex; } private void InitializeMoveOrReplace(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int startingIndex, int oldStartingIndex) { InitializeAdd(action, newItems, startingIndex); InitializeRemove(action, oldItems, oldStartingIndex); } //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ /// <summary> /// The action that caused the event. /// </summary> public NotifyCollectionChangedAction Action { get { return _action; } } /// <summary> /// The items affected by the change. /// </summary> public IList NewItems { get { return _newItems; } } /// <summary> /// The old items affected by the change (for Replace events). /// </summary> public IList OldItems { get { return _oldItems; } } /// <summary> /// The index where the change occurred. /// </summary> public int NewStartingIndex { get { return _newStartingIndex; } } /// <summary> /// The old index where the change occurred (for Move events). /// </summary> public int OldStartingIndex { get { return _oldStartingIndex; } } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ private NotifyCollectionChangedAction _action; private IList _newItems, _oldItems; private int _newStartingIndex = -1; private int _oldStartingIndex = -1; } /// <summary> /// The delegate to use for handlers that receive the CollectionChanged event. /// </summary> public delegate void NotifyCollectionChangedEventHandler(object sender, NotifyCollectionChangedEventArgs e); internal sealed class ReadOnlyList : IList { private readonly IList _list; internal ReadOnlyList(IList list) { Debug.Assert(list != null); _list = list; } public int Count { get { return _list.Count; } } public bool IsReadOnly { get { return true; } } public bool IsFixedSize { get { return true; } } public bool IsSynchronized { get { return _list.IsSynchronized; } } public object this[int index] { get { return _list[index]; } set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } public object SyncRoot { get { return _list.SyncRoot; } } public int Add(object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public void Clear() { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public bool Contains(object value) { return _list.Contains(value); } public void CopyTo(Array array, int index) { _list.CopyTo(array, index); } public IEnumerator GetEnumerator() { return _list.GetEnumerator(); } public int IndexOf(object value) { return _list.IndexOf(value); } public void Insert(int index, object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public void Remove(object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public void RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } }
/* * 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 CsvHelper; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Logging; using QuantConnect.Util; using RestSharp; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using QuantConnect.Securities; namespace QuantConnect.ToolBox.AlphaVantageDownloader { /// <summary> /// Alpha Vantage data downloader /// </summary> public class AlphaVantageDataDownloader : IDataDownloader, IDisposable { private readonly MarketHoursDatabase _marketHoursDatabase; private readonly IRestClient _avClient; private readonly RateGate _rateGate; private bool _disposed; /// <summary> /// Construct AlphaVantageDataDownloader with default RestClient /// </summary> /// <param name="apiKey">API key</param> public AlphaVantageDataDownloader(string apiKey) : this(new RestClient(), apiKey) { } /// <summary> /// Dependency injection constructor /// </summary> /// <param name="restClient">The <see cref="RestClient"/> to use</param> /// <param name="apiKey">API key</param> public AlphaVantageDataDownloader(IRestClient restClient, string apiKey) { _avClient = restClient; _marketHoursDatabase = MarketHoursDatabase.FromDataFolder(); _avClient.BaseUrl = new Uri("https://www.alphavantage.co/"); _avClient.Authenticator = new AlphaVantageAuthenticator(apiKey); _rateGate = new RateGate(5, TimeSpan.FromMinutes(1)); // Free API is limited to 5 requests/minute } /// <summary> /// Get data from API /// </summary> /// <param name="symbol">Symbol to download</param> /// <param name="resolution">Resolution to download</param> /// <param name="startUtc">Start time</param> /// <param name="endUtc">End time</param> /// <returns></returns> public IEnumerable<BaseData> Get(Symbol symbol, Resolution resolution, DateTime startUtc, DateTime endUtc) { var request = new RestRequest("query", DataFormat.Json); request.AddParameter("symbol", symbol.Value); request.AddParameter("datatype", "csv"); IEnumerable<TimeSeries> data = null; switch (resolution) { case Resolution.Minute: case Resolution.Hour: data = GetIntradayData(request, startUtc, endUtc, resolution); break; case Resolution.Daily: data = GetDailyData(request, startUtc, endUtc, symbol); break; default: throw new ArgumentOutOfRangeException(nameof(resolution), $"{resolution} resolution not supported by API."); } var period = resolution.ToTimeSpan(); return data.Select(d => new TradeBar(d.Time, symbol, d.Open, d.High, d.Low, d.Close, d.Volume, period)); } /// <summary> /// Get data from daily API /// </summary> /// <param name="request">Base request</param> /// <param name="startUtc">Start time</param> /// <param name="endUtc">End time</param> /// <param name="symbol">Symbol to download</param> /// <returns></returns> private IEnumerable<TimeSeries> GetDailyData(RestRequest request, DateTime startUtc, DateTime endUtc, Symbol symbol) { request.AddParameter("function", "TIME_SERIES_DAILY"); // The default output only includes 100 trading days of data. If we want need more, specify full output if (GetBusinessDays(startUtc, endUtc, symbol) > 100) { request.AddParameter("outputsize", "full"); } return GetTimeSeries(request); } /// <summary> /// Get data from intraday API /// </summary> /// <param name="request">Base request</param> /// <param name="startUtc">Start time</param> /// <param name="endUtc">End time</param> /// <param name="resolution">Data resolution to request</param> /// <returns></returns> private IEnumerable<TimeSeries> GetIntradayData(RestRequest request, DateTime startUtc, DateTime endUtc, Resolution resolution) { request.AddParameter("function", "TIME_SERIES_INTRADAY_EXTENDED"); request.AddParameter("adjusted", "false"); switch (resolution) { case Resolution.Minute: request.AddParameter("interval", "1min"); break; case Resolution.Hour: request.AddParameter("interval", "60min"); break; default: throw new ArgumentOutOfRangeException($"{resolution} resolution not supported by intraday API."); } var slices = GetSlices(startUtc, endUtc); foreach (var slice in slices) { request.AddOrUpdateParameter("slice", slice); var data = GetTimeSeries(request); foreach (var record in data) { yield return record; } } } /// <summary> /// Execute request and parse response. /// </summary> /// <param name="request">The request</param> /// <returns><see cref="TimeSeries"/> data</returns> private IEnumerable<TimeSeries> GetTimeSeries(RestRequest request) { if (_rateGate.IsRateLimited) { Log.Trace("Requests are limited to 5 per minute. Reduce the time between start and end times or simply wait, and this process will continue automatically."); } _rateGate.WaitToProceed(); //var url = _avClient.BuildUri(request); Log.Trace("Downloading /{0}?{1}", request.Resource, string.Join("&", request.Parameters)); var response = _avClient.Get(request); if (response.ContentType != "application/x-download") { throw new FormatException($"Unexpected content received from API.\n{response.Content}"); } using (var reader = new StringReader(response.Content)) { using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { return csv.GetRecords<TimeSeries>() .OrderBy(t => t.Time) .ToList(); // Execute query before readers are disposed. } } } /// <summary> /// Get slice names for date range. /// See https://www.alphavantage.co/documentation/#intraday-extended /// </summary> /// <param name="startUtc">Start date</param> /// <param name="endUtc">End date</param> /// <returns>Slice names</returns> private static IEnumerable<string> GetSlices(DateTime startUtc, DateTime endUtc) { if ((DateTime.UtcNow - startUtc).TotalDays > 365 * 2) { throw new ArgumentOutOfRangeException(nameof(startUtc), "Intraday data is only available for the last 2 years."); } var timeSpan = endUtc - startUtc; var months = (int)Math.Floor(timeSpan.TotalDays / 30); for (var i = months; i >= 0; i--) { var year = i / 12 + 1; var month = i % 12 + 1; yield return $"year{year}month{month}"; } } /// <summary> /// From https://stackoverflow.com/questions/1617049/calculate-the-number-of-business-days-between-two-dates /// </summary> private int GetBusinessDays(DateTime start, DateTime end, Symbol symbol) { var exchangeHours = _marketHoursDatabase.GetExchangeHours(symbol.ID.Market, symbol, symbol.SecurityType); var current = start.Date; var days = 0; while (current < end) { if (exchangeHours.IsDateOpen(current)) { days++; } current = current.AddDays(1); } return days; } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { // dispose managed state (managed objects) _rateGate.Dispose(); } // free unmanaged resources (unmanaged objects) and override finalizer _disposed = true; } } public void Dispose() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method Dispose(disposing: true); GC.SuppressFinalize(this); } } }
using System; using System.Text; using Microsoft.Isam.Esent.Interop; namespace Rhino.Queues.Storage { public class SchemaCreator { private readonly Session session; public const string SchemaVersion = "1.9"; public SchemaCreator(Session session) { this.session = session; } public void Create(string database) { JET_DBID dbid; Api.JetCreateDatabase(session, database, null, out dbid, CreateDatabaseGrbit.None); try { using (var tx = new Transaction(session)) { CreateDetailsTable(dbid); CreateQueuesTable(dbid); CreateSubQueuesTable(dbid); CreateTransactionTable(dbid); CreateRecoveryTable(dbid); CreateOutgoingTable(dbid); CreateOutgoingHistoryTable(dbid); CreateReceivedMessagesTable(dbid); tx.Commit(CommitTransactionGrbit.None); } } finally { Api.JetCloseDatabase(session, dbid, CloseDatabaseGrbit.None); } } private void CreateSubQueuesTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "subqueues", 16, 100, out tableid); JET_COLUMNID columnid; Api.JetAddColumn(session, tableid, "queue", new JET_COLUMNDEF { cbMax = 255, coltyp = JET_coltyp.Text, cp = JET_CP.Unicode, grbit = ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "subqueue", new JET_COLUMNDEF { cbMax = 255, coltyp = JET_coltyp.Text, cp = JET_CP.Unicode, grbit = ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); var indexDef = "+queue\0subqueue\0\0"; Api.JetCreateIndex(session, tableid, "pk", CreateIndexGrbit.IndexPrimary, indexDef, indexDef.Length, 100); indexDef = "+queue\0\0"; Api.JetCreateIndex(session, tableid, "by_queue", CreateIndexGrbit.IndexDisallowNull, indexDef, indexDef.Length, 100); } private void CreateOutgoingHistoryTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "outgoing_history", 16, 100, out tableid); JET_COLUMNID columnid; Api.JetAddColumn(session, tableid, "msg_id", new JET_COLUMNDEF { coltyp = JET_coltyp.Binary, cbMax = 16, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "tx_id", new JET_COLUMNDEF { cbMax = 16, coltyp = JET_coltyp.Binary, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "address", new JET_COLUMNDEF { cbMax = 255, cp = JET_CP.Unicode, coltyp = JET_coltyp.Text, grbit = ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "port", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "number_of_retries", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "size_of_data", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "time_to_send", new JET_COLUMNDEF { coltyp = JET_coltyp.DateTime, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "sent_at", new JET_COLUMNDEF { coltyp = JET_coltyp.DateTime, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "send_status", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed, }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "queue", new JET_COLUMNDEF { cbMax = 255, coltyp = JET_coltyp.Text, grbit = ColumndefGrbit.ColumnNotNULL, cp = JET_CP.Unicode }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "subqueue", new JET_COLUMNDEF { cbMax = 255, coltyp = JET_coltyp.Text, grbit = ColumndefGrbit.None, cp = JET_CP.Unicode }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "headers", new JET_COLUMNDEF { cbMax = 8192, cp = JET_CP.Unicode, coltyp = JET_coltyp.LongText, grbit = ColumndefGrbit.None }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "data", new JET_COLUMNDEF { coltyp = JET_coltyp.LongBinary, // For Win2k3 support, it doesn't support long binary columsn that are not null grbit = ColumndefGrbit.None }, null, 0, out columnid); var indexDef = "+msg_id\0\0"; Api.JetCreateIndex(session, tableid, "pk", CreateIndexGrbit.IndexPrimary, indexDef, indexDef.Length, 100); indexDef = "+tx_id\0\0"; Api.JetCreateIndex(session, tableid, "by_tx_id", CreateIndexGrbit.IndexDisallowNull, indexDef, indexDef.Length, 100); } private void CreateOutgoingTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "outgoing", 16, 100, out tableid); JET_COLUMNID columnid; Api.JetAddColumn(session, tableid, "msg_id", new JET_COLUMNDEF { coltyp = JET_coltyp.Binary, cbMax = 16, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "tx_id", new JET_COLUMNDEF { cbMax = 16, coltyp = JET_coltyp.Binary, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "address", new JET_COLUMNDEF { cbMax = 255, cp = JET_CP.Unicode, coltyp = JET_coltyp.Text, grbit = ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "port", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "number_of_retries", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "size_of_data", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "time_to_send", new JET_COLUMNDEF { coltyp = JET_coltyp.DateTime, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed },null, 0, out columnid); Api.JetAddColumn(session, tableid, "sent_at", new JET_COLUMNDEF { coltyp = JET_coltyp.DateTime, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "send_status", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed, }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "queue", new JET_COLUMNDEF { cbMax = 255, coltyp = JET_coltyp.Text, grbit = ColumndefGrbit.ColumnNotNULL, cp = JET_CP.Unicode }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "subqueue", new JET_COLUMNDEF { cbMax = 255, coltyp = JET_coltyp.Text, grbit = ColumndefGrbit.None, cp = JET_CP.Unicode }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "headers", new JET_COLUMNDEF { cbMax = 8192, cp = JET_CP.Unicode, coltyp = JET_coltyp.LongText, grbit = ColumndefGrbit.None }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "data", new JET_COLUMNDEF { coltyp = JET_coltyp.LongBinary, // For Win2k3 support, it doesn't support long binary columsn that are not null grbit = ColumndefGrbit.None }, null, 0, out columnid); var indexDef = "+msg_id\0\0"; Api.JetCreateIndex(session, tableid, "pk", CreateIndexGrbit.IndexPrimary, indexDef, indexDef.Length, 100); indexDef = "+tx_id\0\0"; Api.JetCreateIndex(session, tableid, "by_tx_id", CreateIndexGrbit.IndexDisallowNull, indexDef, indexDef.Length, 100); } private void CreateRecoveryTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "recovery", 16, 100, out tableid); JET_COLUMNID columnid; Api.JetAddColumn(session, tableid, "tx_id", new JET_COLUMNDEF { cbMax = 16, coltyp = JET_coltyp.Binary, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "recovery_info", new JET_COLUMNDEF { cbMax = 1024, coltyp = JET_coltyp.LongBinary, // For Win2k3 support, it doesn't support long binary columsn that are not null grbit = ColumndefGrbit.None }, null, 0, out columnid); const string indexDef = "+tx_id\0\0"; Api.JetCreateIndex(session, tableid, "pk", CreateIndexGrbit.IndexPrimary, indexDef, indexDef.Length, 100); } private void CreateDetailsTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "details", 16, 100, out tableid); JET_COLUMNID id; Api.JetAddColumn(session, tableid, "id", new JET_COLUMNDEF { cbMax = 16, coltyp = JET_coltyp.Binary, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out id); JET_COLUMNID schemaVersion; Api.JetAddColumn(session, tableid, "schema_version", new JET_COLUMNDEF { cbMax = Encoding.Unicode.GetByteCount(SchemaVersion), cp = JET_CP.Unicode, coltyp = JET_coltyp.Text, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out schemaVersion); using (var update = new Update(session, tableid, JET_prep.Insert)) { Api.SetColumn(session, tableid, id, Guid.NewGuid().ToByteArray()); Api.SetColumn(session, tableid, schemaVersion, SchemaVersion, Encoding.Unicode); update.Save(); } } private void CreateTransactionTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "transactions", 16, 100, out tableid); JET_COLUMNID columnid; Api.JetAddColumn(session, tableid, "tx_id", new JET_COLUMNDEF { cbMax = 16, coltyp = JET_coltyp.Binary, grbit = ColumndefGrbit.ColumnNotNULL|ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "local_id", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnAutoincrement }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "queue", new JET_COLUMNDEF { cbMax = 255, cp = JET_CP.Unicode, coltyp = JET_coltyp.Text, grbit = ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "subqueue", new JET_COLUMNDEF { cbMax = 255, cp = JET_CP.Unicode, coltyp = JET_coltyp.Text, grbit = ColumndefGrbit.None }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "bookmark_size", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "bookmark_data", new JET_COLUMNDEF { cbMax = 256, coltyp = JET_coltyp.Binary, grbit = ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "value_to_restore", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); var indexDef = "+tx_id\0local_id\0\0"; Api.JetCreateIndex(session, tableid, "pk", CreateIndexGrbit.IndexPrimary, indexDef, indexDef.Length, 100); indexDef = "+tx_id\0\0"; Api.JetCreateIndex(session, tableid, "by_tx_id", CreateIndexGrbit.IndexDisallowNull, indexDef, indexDef.Length, 100); indexDef = "+bookmark_size\0bookmark_data\0\0"; Api.JetCreateIndex(session, tableid, "by_bookmark", CreateIndexGrbit.IndexDisallowNull | CreateIndexGrbit.IndexUnique, indexDef, indexDef.Length, 100); } private void CreateQueuesTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "queues", 16, 100, out tableid); JET_COLUMNID columnid; Api.JetAddColumn(session, tableid, "name", new JET_COLUMNDEF { cbMax = 255, coltyp = JET_coltyp.Text, cp = JET_CP.Unicode, grbit = ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); var defaultValue = BitConverter.GetBytes(0); Api.JetAddColumn(session, tableid, "number_of_messages", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnEscrowUpdate }, defaultValue, defaultValue.Length, out columnid); Api.JetAddColumn(session, tableid, "created_at", new JET_COLUMNDEF { coltyp = JET_coltyp.DateTime, grbit = ColumndefGrbit.ColumnFixed }, null, 0, out columnid); const string indexDef = "+name\0\0"; Api.JetCreateIndex(session, tableid, "pk", CreateIndexGrbit.IndexPrimary, indexDef, indexDef.Length, 100); } private void CreateReceivedMessagesTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "recveived_msgs", 16, 100, out tableid); JET_COLUMNID columnid; Api.JetAddColumn(session, tableid, "local_id", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnAutoincrement }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "instance_id", new JET_COLUMNDEF { coltyp = JET_coltyp.Binary, cbMax = 16, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "msg_id", new JET_COLUMNDEF { coltyp = JET_coltyp.Binary, cbMax = 16, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); const string indexDef = "+local_id\0\0"; Api.JetCreateIndex(session, tableid, "pk", CreateIndexGrbit.IndexPrimary, indexDef, indexDef.Length, 100); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Tracing; using System.Net.Http; using System.Globalization; namespace System.Net { //TODO: If localization resources are not found, logging does not work. Issue #5126. [EventSource(Name = "Microsoft-System-Net-Http", Guid = "bdd9a83e-1929-5482-0d73-2fe5e1c0e16d", LocalizationResources = "FxResources.System.Net.Http.SR")] internal sealed class HttpEventSource : EventSource { private const int AssociateId = 1; private const int UriBaseAddressId = 2; private const int ContentNullId = 3; private const int ClientSendCompletedId = 4; private const int HeadersInvalidValueId = 5; private const int HandlerMessageId = 6; private readonly static HttpEventSource s_log = new HttpEventSource(); private HttpEventSource() { } public static HttpEventSource Log { get { return s_log; } } [NonEvent] internal static void Associate(object objA, object objB) { if (!s_log.IsEnabled()) { return; } s_log.Associate(LoggingHash.GetObjectName(objA), LoggingHash.HashInt(objA), LoggingHash.GetObjectName(objB), LoggingHash.HashInt(objB)); } [Event(AssociateId, Keywords = Keywords.Default, Level = EventLevel.Informational, Message = "[{0}#{1}]<-->[{2}#{3}]")] internal unsafe void Associate(string objectA, int objectAHash, string objectB, int objectBHash) { const int SizeData = 4; fixed (char* arg1Ptr = objectA, arg2Ptr = objectB) { EventData* dataDesc = stackalloc EventSource.EventData[SizeData]; dataDesc[0].DataPointer = (IntPtr)(arg1Ptr); dataDesc[0].Size = (objectA.Length + 1) * sizeof(char); // Size in bytes, including a null terminator. dataDesc[1].DataPointer = (IntPtr)(&objectAHash); dataDesc[1].Size = sizeof(int); dataDesc[2].DataPointer = (IntPtr)(arg2Ptr); dataDesc[2].Size = (objectB.Length + 1) * sizeof(char); dataDesc[3].DataPointer = (IntPtr)(&objectBHash); dataDesc[3].Size = sizeof(int); WriteEventCore(AssociateId, SizeData, dataDesc); } } [NonEvent] internal static void UriBaseAddress(object obj, string baseAddress) { if (!s_log.IsEnabled()) { return; } s_log.UriBaseAddress(baseAddress, LoggingHash.GetObjectName(obj), LoggingHash.HashInt(obj)); } [Event(UriBaseAddressId, Keywords = Keywords.Debug, Level = EventLevel.Informational)] internal unsafe void UriBaseAddress(string uriBaseAddress, string objName, int objHash) { const int SizeData = 3; fixed (char* arg1Ptr = uriBaseAddress, arg2Ptr = objName) { EventData* dataDesc = stackalloc EventSource.EventData[SizeData]; dataDesc[0].DataPointer = (IntPtr)(arg1Ptr); dataDesc[0].Size = (uriBaseAddress.Length + 1) * sizeof(char); // Size in bytes, including a null terminator. dataDesc[1].DataPointer = (IntPtr)(arg2Ptr); dataDesc[1].Size = (objName.Length + 1) * sizeof(char); dataDesc[2].DataPointer = (IntPtr)(&objHash); dataDesc[2].Size = sizeof(int); WriteEventCore(UriBaseAddressId, SizeData, dataDesc); } } [NonEvent] internal static void ContentNull(object obj) { if (!s_log.IsEnabled()) { return; } s_log.ContentNull(LoggingHash.GetObjectName(obj), LoggingHash.HashInt(obj)); } [Event(ContentNullId, Keywords = Keywords.Debug, Level = EventLevel.Informational)] internal void ContentNull(string objName, int objHash) { WriteEvent(ContentNullId, objName, objHash); } [NonEvent] internal static void ClientSendCompleted(HttpClient httpClient, HttpResponseMessage response, HttpRequestMessage request) { if (!s_log.IsEnabled()) { return; } string responseString = ""; if (response != null) { responseString = response.ToString(); } s_log.ClientSendCompleted(LoggingHash.HashInt(request), LoggingHash.HashInt(response), responseString, LoggingHash.HashInt(httpClient)); } [Event(ClientSendCompletedId, Keywords = Keywords.Debug, Level = EventLevel.Verbose)] internal unsafe void ClientSendCompleted(int httpRequestMessageHash, int httpResponseMessageHash, string responseString, int httpClientHash) { const int SizeData = 4; fixed (char* arg1Ptr = responseString) { EventData* dataDesc = stackalloc EventSource.EventData[SizeData]; dataDesc[0].DataPointer = (IntPtr)(&httpRequestMessageHash); dataDesc[0].Size = sizeof(int); dataDesc[1].DataPointer = (IntPtr)(&httpResponseMessageHash); dataDesc[1].Size = sizeof(int); dataDesc[2].DataPointer = (IntPtr)(arg1Ptr); dataDesc[2].Size = (responseString.Length + 1) * sizeof(char); dataDesc[3].DataPointer = (IntPtr)(&httpClientHash); dataDesc[3].Size = sizeof(int); WriteEventCore(ClientSendCompletedId, SizeData, dataDesc); } } [Event(HeadersInvalidValueId, Keywords = Keywords.Debug, Level = EventLevel.Verbose)] internal void HeadersInvalidValue(string name, string rawValue) { WriteEvent(HeadersInvalidValueId, name, rawValue); } [Event(HandlerMessageId, Keywords = Keywords.Debug, Level = EventLevel.Verbose)] internal unsafe void HandlerMessage(int workerId, int requestId, string memberName, string message) { if (memberName == null) { memberName = string.Empty; } if (message == null) { message = string.Empty; } const int SizeData = 4; fixed (char* memberNamePtr = memberName) fixed (char* messagePtr = message) { EventData* dataDesc = stackalloc EventSource.EventData[SizeData]; dataDesc[0].DataPointer = (IntPtr)(&workerId); dataDesc[0].Size = sizeof(int); dataDesc[1].DataPointer = (IntPtr)(&requestId); dataDesc[1].Size = sizeof(int); dataDesc[2].DataPointer = (IntPtr)(memberNamePtr); dataDesc[2].Size = (memberName.Length + 1) * sizeof(char); dataDesc[3].DataPointer = (IntPtr)(messagePtr); dataDesc[3].Size = (message.Length + 1) * sizeof(char); WriteEventCore(HandlerMessageId, SizeData, dataDesc); } } public class Keywords { public const EventKeywords Default = (EventKeywords)0x0001; public const EventKeywords Debug = (EventKeywords)0x0002; } } }
// --------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // The MIT License (MIT) // // 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 Windows.Foundation.Metadata; using Windows.System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; namespace Yodo1APICaller.Navigation { /// <summary> /// A specialized ListView to represent the items in the navigation menu. /// </summary> /// <remarks> /// This class handles the following: /// 1. Sizes the panel that hosts the items so they fit in the hosting pane. Otherwise, the keyboard /// may appear cut off on one side b/c the Pane clips instead of affecting layout. /// 2. Provides a single selection experience where keyboard focus can move without changing selection. /// Both the 'Space' and 'Enter' keys will trigger selection. The up/down arrow keys can move /// keyboard focus without triggering selection. This is different than the default behavior when /// SelectionMode == Single. The default behavior for a ListView in single selection requires using /// the Ctrl + arrow key to move keyboard focus without triggering selection. Users won't expect /// this type of keyboarding model on the nav menu. /// </remarks> public class NavMenuListView : ListView { private SplitView splitViewHost; public NavMenuListView() { SelectionMode = ListViewSelectionMode.Single; // This API doesn't exist on early versions of Windows 10, so check for it an only set it if it // exists on the version that the app is being run on. if (ApiInformation.IsPropertyPresent("Windows.UI.Xaml.Controls.ListViewBase", "SingleSelectionFollowsFocus")) { SingleSelectionFollowsFocus = false; } IsItemClickEnabled = true; ItemClick += ItemClickedHandler; // Locate the hosting SplitView control Loaded += (s, a) => { var parent = VisualTreeHelper.GetParent(this); while (parent != null && !(parent is SplitView)) { parent = VisualTreeHelper.GetParent(parent); } if (parent != null) { splitViewHost = parent as SplitView; splitViewHost.RegisterPropertyChangedCallback( SplitView.IsPaneOpenProperty, (sender, args) => { OnPaneToggled(); }); splitViewHost.RegisterPropertyChangedCallback( SplitView.DisplayModeProperty, (sender, args) => { OnPaneToggled(); }); // Call once to ensure we're in the correct state OnPaneToggled(); } }; } protected override void OnApplyTemplate() { base.OnApplyTemplate(); // Remove the entrance animation on the item containers. for (int i = 0; i < ItemContainerTransitions.Count; i++) { if (ItemContainerTransitions[i] is EntranceThemeTransition) { ItemContainerTransitions.RemoveAt(i); } } } /// <summary> /// Mark the <paramref name="item"/> as selected and ensures everything else is not. /// If the <paramref name="item"/> is null then everything is unselected. /// </summary> /// <param name="item"></param> public void SetSelectedItem(ListViewItem item) { int index = -1; if (item != null) { index = IndexFromContainer(item); } for (int i = 0; i < Items.Count; i++) { var lvi = (ListViewItem)ContainerFromIndex(i); if (i != index && lvi != null) { lvi.IsSelected = false; } else if (i == index) { lvi.IsSelected = true; } } } /// <summary> /// Occurs when an item has been selected /// </summary> public event EventHandler<ListViewItem> ItemInvoked; /// <summary> /// Custom keyboarding logic to enable movement via the arrow keys without triggering selection /// until a 'Space' or 'Enter' key is pressed. /// </summary> /// <param name="e"></param> protected override void OnKeyDown(KeyRoutedEventArgs e) { var focusedItem = FocusManager.GetFocusedElement(); switch (e.Key) { case VirtualKey.Up: TryMoveFocus(FocusNavigationDirection.Up); e.Handled = true; break; case VirtualKey.Down: TryMoveFocus(FocusNavigationDirection.Down); e.Handled = true; break; case VirtualKey.Space: case VirtualKey.Enter: // Fire our event using the item with current keyboard focus InvokeItem(focusedItem); e.Handled = true; break; default: base.OnKeyDown(e); break; } } /// <summary> /// This method is a work-around until the bug in FocusManager.TryMoveFocus is fixed. /// </summary> /// <param name="direction"></param> private void TryMoveFocus(FocusNavigationDirection direction) { if (direction == FocusNavigationDirection.Next || direction == FocusNavigationDirection.Previous) { FocusManager.TryMoveFocus(direction); } else { var control = FocusManager.FindNextFocusableElement(direction) as Control; if (control != null) { control.Focus(FocusState.Programmatic); } } } private void ItemClickedHandler(object sender, ItemClickEventArgs e) { // Triggered when the item is selected using something other than a keyboard var item = ContainerFromItem(e.ClickedItem); InvokeItem(item); } private void InvokeItem(object focusedItem) { SetSelectedItem(focusedItem as ListViewItem); ItemInvoked(this, focusedItem as ListViewItem); if (splitViewHost.IsPaneOpen && ( splitViewHost.DisplayMode == SplitViewDisplayMode.CompactOverlay || splitViewHost.DisplayMode == SplitViewDisplayMode.Overlay)) { splitViewHost.IsPaneOpen = false; } if (focusedItem is ListViewItem) { ((ListViewItem)focusedItem).Focus(FocusState.Programmatic); } } /// <summary> /// Re-size the ListView's Panel when the SplitView is compact so the items /// will fit within the visible space and correctly display a keyboard focus rect. /// </summary> private void OnPaneToggled() { if (splitViewHost.IsPaneOpen) { ItemsPanelRoot.ClearValue(FrameworkElement.WidthProperty); ItemsPanelRoot.ClearValue(FrameworkElement.HorizontalAlignmentProperty); } else if (splitViewHost.DisplayMode == SplitViewDisplayMode.CompactInline || splitViewHost.DisplayMode == SplitViewDisplayMode.CompactOverlay) { ItemsPanelRoot.SetValue(FrameworkElement.WidthProperty, splitViewHost.CompactPaneLength); ItemsPanelRoot.SetValue(FrameworkElement.HorizontalAlignmentProperty, HorizontalAlignment.Left); } } } }
//MIT License //Copyright (c) 2020-2021 Peter Kirmeier //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.Drawing; using System.Net; using System.Reflection; using System.Windows.Forms; using TinyJson; namespace HitCounterManager { public static class GitHubUpdate { private static List<Dictionary<string, object>> Releases = null; /// <summary> /// Opens the default project website on GitHub /// </summary> public static void WebOpenLandingPage() { System.Diagnostics.Process.Start("https://github.com/topeterk/HitCounterManager"); } /// <summary> /// Opens the website on GitHub of the latest release version /// </summary> public static void WebOpenLatestRelease() { System.Diagnostics.Process.Start("https://github.com/topeterk/HitCounterManager/releases/latest"); } /// <summary> /// Updates the information about all available releases /// </summary> /// <returns>Success state</returns> public static bool QueryAllReleases() { bool result = false; try { WebClient client = new WebClient(); client.Encoding = System.Text.Encoding.UTF8; // https://developer.github.com/v3/#user-agent-required client.Headers.Add("User-Agent", "HitCounterManager/" + Application.ProductVersion.ToString()); // https://developer.github.com/v3/media/#request-specific-version client.Headers.Add("Accept", "application/vnd.github.v3.text+json"); // https://developer.github.com/v3/repos/releases/#get-a-single-release string response = client.DownloadString("http://api.github.com/repos/topeterk/HitCounterManager/releases"); Releases = response.FromJson<List<Dictionary<string, object>>>(); // Only keep newer releases of own major version int i = Releases.Count; string MajorVersionString = Assembly.GetExecutingAssembly().GetName().Version.Major.ToString() + "."; while (0 < i--) { string tag_name = Releases[i]["tag_name"].ToString(); if (!tag_name.StartsWith(MajorVersionString)) Releases.RemoveAt(i); } result = true; } catch (Exception) { }; return result; } /// <summary> /// Returns the latest release version name /// </summary> /// <returns>Version name</returns> public static string GetLatestVersionName() { string result = "Unknown"; if (Releases == null) return result; try { result = Releases[0]["tag_name"].ToString(); // 0 = latest } catch (Exception) { }; return result; } /// <summary> /// Returns the change log from current version up to the latest release version /// </summary> /// <returns>Change log summary or error text</returns> public static string GetChangelog() { string result; string errorstr = "An error occurred during update check!" + Environment.NewLine + Environment.NewLine; if (Releases == null) return errorstr + "Could not receive changelog!"; if (GetLatestVersionName() == Application.ProductVersion.ToString()) { result = "Up to date!"; } else { try { Dictionary<string, object> release; int i; result = ""; for (i = 0; i < Releases.Count; i++) { release = Releases[i]; if (release["tag_name"].ToString() == Application.ProductVersion.ToString()) break; // stop on current version result += "----------------------------------------------------------------------------------------------------------------------------------------------------------------" + Environment.NewLine + release["name"].ToString() + Environment.NewLine + Environment.NewLine + release["body_text"].ToString().Replace("\n\n", Environment.NewLine) + Environment.NewLine + Environment.NewLine; } result = i.ToString() + " new version" + (i == 1 ? "" : "s") + " available:" + Environment.NewLine + Environment.NewLine + result; result = result.Replace("\n", Environment.NewLine); } catch (Exception ex) { result = errorstr + ex.Message.ToString(); } } return result; } /// <summary> /// Creates a window to show changelog of new available versions /// </summary> /// <param name="LatestVersionTitle">Name of latest release</param> /// <param name="Changelog">Pathnotes</param> /// <returns>OK = OK, Yes = Website, else = Cancel</returns> public static DialogResult NewVersionDialog(Form ParentWindow) { const int ClientPad = 15; Form frm = new Form(); frm.StartPosition = FormStartPosition.CenterParent; frm.FormBorderStyle = FormBorderStyle.FixedDialog; frm.Icon = ParentWindow.Icon; frm.ShowInTaskbar = false; frm.FormBorderStyle = FormBorderStyle.Sizable; frm.MaximizeBox = true; frm.MinimizeBox = false; frm.ClientSize = new Size(600, 400); frm.MinimumSize = frm.ClientSize; frm.Text = "New version available!"; Label label = new Label(); label.Size = new Size(frm.ClientSize.Width - ClientPad, 20); label.Location = new Point(ClientPad, ClientPad); label.Text = "Latest available version: " + GetLatestVersionName(); frm.Controls.Add(label); Button okButton = new Button(); okButton.DialogResult = DialogResult.OK; okButton.Name = "okButton"; okButton.Location = new Point(frm.ClientSize.Width - okButton.Size.Width - ClientPad, frm.ClientSize.Height - okButton.Size.Height - ClientPad); okButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; okButton.Text = "&OK"; frm.Controls.Add(okButton); Button wwwButton = new Button(); wwwButton.DialogResult = DialogResult.Yes; wwwButton.Name = "wwwButton"; wwwButton.Location = new Point(frm.ClientSize.Width - wwwButton.Size.Width- ClientPad - okButton.Size.Width - ClientPad, frm.ClientSize.Height - wwwButton.Size.Height - ClientPad); wwwButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; wwwButton.Text = "&Go to download page"; wwwButton.AutoSizeMode = AutoSizeMode.GrowAndShrink; wwwButton.AutoSize = true; frm.Controls.Add(wwwButton); TextBox textBox = new TextBox(); textBox.Location = new Point(ClientPad, label.Location.Y + label.Size.Height + 5); textBox.Size = new Size(frm.ClientSize.Width - ClientPad*2, okButton.Location.Y - ClientPad - textBox.Location.Y); textBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; textBox.Multiline = true; textBox.Text = GetChangelog(); textBox.ReadOnly = true; textBox.ScrollBars = ScrollBars.Both; textBox.BackColor = Color.FromKnownColor(KnownColor.Window); textBox.ForeColor = Color.FromKnownColor(KnownColor.ControlText); frm.Controls.Add(textBox); frm.AcceptButton = okButton; return frm.ShowDialog(ParentWindow); } } }
using System; using Loon.Utils; using Loon.Core.Geom; namespace Loon.Core.Graphics.Device { public class LGraphicsMath :LTrans { private static readonly int[] SHIFT = { 0, 1144, 2289, 3435, 4583, 5734, 6888, 8047, 9210, 10380, 11556, 12739, 13930, 15130, 16340, 17560, 18792, 20036, 21294, 22566, 23853, 25157, 26478, 27818, 29179, 30560, 31964, 33392, 34846, 36327, 37837, 39378, 40951, 42560, 44205, 45889, 47615, 49385, 51202, 53070, 54991, 56970, 59009, 61113, 63287, 65536 }; public static int Round(int div1, int div2) { int remainder = div1 % div2; if (MathUtils.Abs(remainder) * 2 <= MathUtils.Abs(div2)) { return div1 / div2; } else if (div1 * div2 < 0) { return div1 / div2 - 1; } else { return div1 / div2 + 1; } } public static long Round(long div1, long div2) { long remainder = div1 % div2; if (MathUtils.Abs(remainder) * 2 <= MathUtils.Abs(div2)) { return div1 / div2; } else if (div1 * div2 < 0) { return div1 / div2 - 1; } else { return div1 / div2 + 1; } } public static int ToShift(int angle) { if (angle <= 45) { return SHIFT[angle]; } else if (angle >= 315) { return -SHIFT[360 - angle]; } else if (angle >= 135 && angle <= 180) { return -SHIFT[180 - angle]; } else if (angle >= 180 && angle <= 225) { return SHIFT[angle - 180]; } else if (angle >= 45 && angle <= 90) { return SHIFT[90 - angle]; } else if (angle >= 90 && angle <= 135) { return -SHIFT[angle - 90]; } else if (angle >= 225 && angle <= 270) { return SHIFT[270 - angle]; } else { return -SHIFT[angle - 270]; } } public static Loon.Core.Geom.Point.Point2i GetBoundingPointAtAngle(int boundingX, int boundingY, int boundingWidth, int boundingHeight, int angle) { if (angle >= 315 || angle <= 45) { return new Loon.Core.Geom.Point.Point2i(boundingX + boundingWidth, boundingY + ((int)(((uint)boundingHeight * (65536 - ToShift(angle))) >> 17))); } else if (angle > 45 && angle < 135) { return new Loon.Core.Geom.Point.Point2i(boundingX + ((int)(((uint)boundingWidth * (65536 + ToShift(angle))) >> 17)), boundingY); } else if (angle >= 135 && angle <= 225) { return new Loon.Core.Geom.Point.Point2i(boundingX, boundingY + ((int)(((uint)boundingHeight * (65536 + ToShift(angle))) >> 17))); } else { return new Loon.Core.Geom.Point.Point2i(boundingX + ((int)(((uint)boundingWidth * (65536 - ToShift(angle))) >> 17)), boundingY + boundingHeight); } } public static RectBox GetBoundingBox(int[] xpoints, int[] ypoints, int npoints) { int boundsMinX = Int32.MaxValue; int boundsMinY = Int32.MaxValue; int boundsMaxX = Int32.MinValue; int boundsMaxY = Int32.MinValue; for (int i = 0; i < npoints; i++) { int x_0 = xpoints[i]; boundsMinX = Math.Min(boundsMinX, x_0); boundsMaxX = Math.Max(boundsMaxX, x_0); int y_1 = ypoints[i]; boundsMinY = Math.Min(boundsMinY, y_1); boundsMaxY = Math.Max(boundsMaxY, y_1); } return new RectBox(boundsMinX, boundsMinY, boundsMaxX - boundsMinX, boundsMaxY - boundsMinY); } public static int GetBoundingShape(int[] xPoints, int[] yPoints, int startAngle, int arcAngle, int centerX, int centerY, int boundingX, int boundingY, int boundingWidth, int boundingHeight) { xPoints[0] = centerX; yPoints[0] = centerY; Loon.Core.Geom.Point.Point2i startPoint = GetBoundingPointAtAngle(boundingX, boundingY, boundingWidth, boundingHeight, startAngle); xPoints[1] = startPoint.x; yPoints[1] = startPoint.y; int i = 2; for (int angle = 0; angle < arcAngle; i++, angle += 90) { if (angle + 90 > arcAngle && ((startAngle + angle - 45) % 360) / 90 == ((startAngle + arcAngle + 45) % 360) / 90) { break; } int modAngle = (startAngle + angle) % 360; if (modAngle > 315 || modAngle <= 45) { xPoints[i] = boundingX + boundingWidth; yPoints[i] = boundingY; } else if (modAngle > 135 && modAngle <= 225) { xPoints[i] = boundingX; yPoints[i] = boundingY + boundingHeight; } else if (modAngle > 45 && modAngle <= 135) { xPoints[i] = boundingX; yPoints[i] = boundingY; } else { xPoints[i] = boundingX + boundingWidth; yPoints[i] = boundingY + boundingHeight; } } Loon.Core.Geom.Point.Point2i endPoint = GetBoundingPointAtAngle(boundingX, boundingY, boundingWidth, boundingHeight, (startAngle + arcAngle) % 360); if (xPoints[i - 1] != endPoint.x || yPoints[i - 1] != endPoint.y) { xPoints[i] = endPoint.x; yPoints[i++] = endPoint.y; } return i; } public static bool Contains(int[] xPoints, int[] yPoints, int nPoints,RectBox bounds, int x1, int y1) { if ((bounds != null && bounds.Inside(x1, y1)) || (bounds == null && GetBoundingBox(xPoints, yPoints, nPoints) .Inside(x1, y1))) { int hits = 0; int ySave = 0; int i = 0; while (i < nPoints && yPoints[i] == y1) { i++; } for (int n = 0; n < nPoints; n++) { int j = (i + 1) % nPoints; int dx = xPoints[j] - xPoints[i]; int dy = yPoints[j] - yPoints[i]; if (dy != 0) { int rx = x1 - xPoints[i]; int ry = y1 - yPoints[i]; if (yPoints[j] == y1 && xPoints[j] >= x1) { ySave = yPoints[i]; } if (yPoints[i] == y1 && xPoints[i] >= x1) { if ((ySave > y1) != (yPoints[j] > y1)) { hits--; } } if (ry * dy >= 0 && (ry <= dy && ry >= 0 || ry >= dy && ry <= 0) && Round(dx * ry, dy) >= rx) { hits++; } } i = j; } return (hits % 2) != 0; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.Metadata { public readonly partial struct AssemblyReference { private readonly MetadataReader _reader; // Workaround: JIT doesn't generate good code for nested structures, so use raw uint. private readonly uint _treatmentAndRowId; private static readonly Version s_version_4_0_0_0 = new Version(4, 0, 0, 0); internal AssemblyReference(MetadataReader reader, uint treatmentAndRowId) { Debug.Assert(reader != null); Debug.Assert(treatmentAndRowId != 0); // only virtual bit can be set in highest byte: Debug.Assert((treatmentAndRowId & ~(TokenTypeIds.VirtualBit | TokenTypeIds.RIDMask)) == 0); _reader = reader; _treatmentAndRowId = treatmentAndRowId; } private int RowId { get { return (int)(_treatmentAndRowId & TokenTypeIds.RIDMask); } } private bool IsVirtual { get { return (_treatmentAndRowId & TokenTypeIds.VirtualBit) != 0; } } public Version Version { get { if (IsVirtual) { return GetVirtualVersion(); } // change mscorlib version: if (RowId == _reader.WinMDMscorlibRef) { return s_version_4_0_0_0; } return _reader.AssemblyRefTable.GetVersion(RowId); } } public AssemblyFlags Flags { get { if (IsVirtual) { return GetVirtualFlags(); } return _reader.AssemblyRefTable.GetFlags(RowId); } } public StringHandle Name { get { if (IsVirtual) { return GetVirtualName(); } return _reader.AssemblyRefTable.GetName(RowId); } } public StringHandle Culture { get { if (IsVirtual) { return GetVirtualCulture(); } return _reader.AssemblyRefTable.GetCulture(RowId); } } public BlobHandle PublicKeyOrToken { get { if (IsVirtual) { return GetVirtualPublicKeyOrToken(); } return _reader.AssemblyRefTable.GetPublicKeyOrToken(RowId); } } public BlobHandle HashValue { get { if (IsVirtual) { return GetVirtualHashValue(); } return _reader.AssemblyRefTable.GetHashValue(RowId); } } public CustomAttributeHandleCollection GetCustomAttributes() { if (IsVirtual) { return GetVirtualCustomAttributes(); } return new CustomAttributeHandleCollection(_reader, AssemblyReferenceHandle.FromRowId(RowId)); } #region Virtual Rows private Version GetVirtualVersion() { // currently all projected assembly references have version 4.0.0.0 return s_version_4_0_0_0; } private AssemblyFlags GetVirtualFlags() { // use flags from mscorlib ref (specifically PublicKey flag): return _reader.AssemblyRefTable.GetFlags(_reader.WinMDMscorlibRef); } private StringHandle GetVirtualName() { return StringHandle.FromVirtualIndex(GetVirtualNameIndex((AssemblyReferenceHandle.VirtualIndex)RowId)); } private StringHandle.VirtualIndex GetVirtualNameIndex(AssemblyReferenceHandle.VirtualIndex index) { switch (index) { case AssemblyReferenceHandle.VirtualIndex.System_ObjectModel: return StringHandle.VirtualIndex.System_ObjectModel; case AssemblyReferenceHandle.VirtualIndex.System_Runtime: return StringHandle.VirtualIndex.System_Runtime; case AssemblyReferenceHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime: return StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime; case AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime: return StringHandle.VirtualIndex.System_Runtime_WindowsRuntime; case AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml: return StringHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml; case AssemblyReferenceHandle.VirtualIndex.System_Numerics_Vectors: return StringHandle.VirtualIndex.System_Numerics_Vectors; } Debug.Assert(false, "Unexpected virtual index value"); return 0; } private StringHandle GetVirtualCulture() { return default(StringHandle); } private BlobHandle GetVirtualPublicKeyOrToken() { switch ((AssemblyReferenceHandle.VirtualIndex)RowId) { case AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime: case AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml: // use key or token from mscorlib ref: return _reader.AssemblyRefTable.GetPublicKeyOrToken(_reader.WinMDMscorlibRef); default: // use contract assembly key or token: var hasFullKey = (_reader.AssemblyRefTable.GetFlags(_reader.WinMDMscorlibRef) & AssemblyFlags.PublicKey) != 0; return BlobHandle.FromVirtualIndex(hasFullKey ? BlobHandle.VirtualIndex.ContractPublicKey : BlobHandle.VirtualIndex.ContractPublicKeyToken, 0); } } private BlobHandle GetVirtualHashValue() { return default(BlobHandle); } private CustomAttributeHandleCollection GetVirtualCustomAttributes() { // return custom attributes applied on mscorlib ref return new CustomAttributeHandleCollection(_reader, AssemblyReferenceHandle.FromRowId(_reader.WinMDMscorlibRef)); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetFramework.Analyzers.UnitTests { public partial class DoNotUseInsecureDtdProcessingAnalyzerTests { private static DiagnosticResult GetCA3075DataViewCSharpResultAt(int line, int column) => VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleReviewDtdProcessingProperties).WithLocation(line, column); private static DiagnosticResult GetCA3075DataViewBasicResultAt(int line, int column) => VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleReviewDtdProcessingProperties).WithLocation(line, column); [Fact] public async Task UseDataSetDefaultDataViewManagerSetCollectionStringShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; namespace TestNamespace { public class ReviewDataViewConnectionString { public void TestMethod(string src) { DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; } } } ", GetCA3075DataViewCSharpResultAt(11, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Namespace TestNamespace Public Class ReviewDataViewConnectionString Public Sub TestMethod(src As String) Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src End Sub End Class End Namespace", GetCA3075DataViewBasicResultAt(8, 13) ); } [Fact] public async Task UseDataSetDefaultDataViewManagernInGetShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { public DataSet Test { get { var src = """"; DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; return ds; } } }", GetCA3075DataViewCSharpResultAt(11, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Public ReadOnly Property Test() As DataSet Get Dim src = """" Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src Return ds End Get End Property End Class", GetCA3075DataViewBasicResultAt(9, 13) ); } [Fact] public async Task UseDataSetDefaultDataViewManagerInSetShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { DataSet privateDoc; public DataSet GetDoc { set { if (value == null) { var src = """"; DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; privateDoc = ds; } else privateDoc = value; } } }", GetCA3075DataViewCSharpResultAt(15, 21) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Private privateDoc As DataSet Public WriteOnly Property GetDoc() As DataSet Set If value Is Nothing Then Dim src = """" Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src privateDoc = ds Else privateDoc = value End If End Set End Property End Class", GetCA3075DataViewBasicResultAt(11, 17) ); } [Fact] public async Task UseDataSetDefaultDataViewManagerInTryBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { var src = """"; DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; } catch (Exception) { throw; } finally { } } }", GetCA3075DataViewCSharpResultAt(13, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Dim src = """" Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src Catch generatedExceptionName As Exception Throw Finally End Try End Sub End Class", GetCA3075DataViewBasicResultAt(10, 13) ); } [Fact] public async Task UseDataSetDefaultDataViewManagerInCatchBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { } catch (Exception) { var src = """"; DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; } finally { } } }", GetCA3075DataViewCSharpResultAt(14, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Dim src = """" Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src Finally End Try End Sub End Class", GetCA3075DataViewBasicResultAt(11, 13) ); } [Fact] public async Task UseDataSetDefaultDataViewManagerInFinallyBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { } catch (Exception) { throw; } finally { var src = """"; DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; } } }", GetCA3075DataViewCSharpResultAt(15, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Throw Finally Dim src = """" Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src End Try End Sub End Class", GetCA3075DataViewBasicResultAt(13, 13) ); } [Fact] public async Task UseDataSetDefaultDataViewManagerInAsyncAwaitShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Threading.Tasks; using System.Data; class TestClass { private async Task TestMethod() { await Task.Run(() => { var src = """"; DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; }); } private async void TestMethod2() { await TestMethod(); } }", GetCA3075DataViewCSharpResultAt(12, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Threading.Tasks Imports System.Data Class TestClass Private Async Function TestMethod() As Task Await Task.Run(Function() Dim src = """" Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src End Function) End Function Private Async Sub TestMethod2() Await TestMethod() End Sub End Class", GetCA3075DataViewBasicResultAt(10, 9) ); } [Fact] public async Task UseDataSetDefaultDataViewManagerInDelegateShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { delegate void Del(); Del d = delegate () { var src = """"; DataSet ds = new DataSet(); ds.DefaultViewManager.DataViewSettingCollectionString = src; }; }", GetCA3075DataViewCSharpResultAt(11, 9) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Private Delegate Sub Del() Private d As Del = Sub() Dim src = """" Dim ds As New DataSet() ds.DefaultViewManager.DataViewSettingCollectionString = src End Sub End Class", GetCA3075DataViewBasicResultAt(10, 5) ); } [Fact] public async Task UseDataViewManagerSetCollectionStringShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; namespace TestNamespace { public class ReviewDataViewConnectionString { public void TestMethod(string src) { DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; } } } ", GetCA3075DataViewCSharpResultAt(11, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Namespace TestNamespace Public Class ReviewDataViewConnectionString Public Sub TestMethod(src As String) Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src End Sub End Class End Namespace", GetCA3075DataViewBasicResultAt(8, 13) ); } [Fact] public async Task UseDataViewManagerInGetShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { public DataViewManager Test { get { var src = """"; DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; return manager; } } }", GetCA3075DataViewCSharpResultAt(11, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Public ReadOnly Property Test() As DataViewManager Get Dim src = """" Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src Return manager End Get End Property End Class", GetCA3075DataViewBasicResultAt(9, 13) ); } [Fact] public async Task UseDataViewManagerInSetShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { DataViewManager privateDoc; public DataViewManager GetDoc { set { if (value == null) { var src = """"; DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; privateDoc = manager; } else privateDoc = value; } } }", GetCA3075DataViewCSharpResultAt(15, 21) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Private privateDoc As DataViewManager Public WriteOnly Property GetDoc() As DataViewManager Set If value Is Nothing Then Dim src = """" Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src privateDoc = manager Else privateDoc = value End If End Set End Property End Class", GetCA3075DataViewBasicResultAt(11, 17) ); } [Fact] public async Task UseDataViewManagerInTryBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { var src = """"; DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; } catch (Exception) { throw; } finally { } } }", GetCA3075DataViewCSharpResultAt(13, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Dim src = """" Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src Catch generatedExceptionName As Exception Throw Finally End Try End Sub End Class", GetCA3075DataViewBasicResultAt(10, 13) ); } [Fact] public async Task UseDataViewManagerInCatchBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { } catch (Exception) { var src = """"; DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; } finally { } } }", GetCA3075DataViewCSharpResultAt(14, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Dim src = """" Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src Finally End Try End Sub End Class", GetCA3075DataViewBasicResultAt(11, 13) ); } [Fact] public async Task UseDataViewManagerInFinallyBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { } catch (Exception) { throw; } finally { var src = """"; DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; } } }", GetCA3075DataViewCSharpResultAt(15, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Throw Finally Dim src = """" Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src End Try End Sub End Class", GetCA3075DataViewBasicResultAt(13, 13) ); } [Fact] public async Task UseDataViewManagerInAsyncAwaitShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Threading.Tasks; using System.Data; class TestClass { private async Task TestMethod() { await Task.Run(() => { var src = """"; DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; }); } private async void TestMethod2() { await TestMethod(); } }", GetCA3075DataViewCSharpResultAt(12, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Threading.Tasks Imports System.Data Class TestClass Private Async Function TestMethod() As Task Await Task.Run(Function() Dim src = """" Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src End Function) End Function Private Async Sub TestMethod2() Await TestMethod() End Sub End Class", GetCA3075DataViewBasicResultAt(10, 9) ); } [Fact] public async Task UseDataViewManagerInDelegateShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { delegate void Del(); Del d = delegate () { var src = """"; DataViewManager manager = new DataViewManager(); manager.DataViewSettingCollectionString = src; }; }", GetCA3075DataViewCSharpResultAt(11, 9) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Private Delegate Sub Del() Private d As Del = Sub() Dim src = """" Dim manager As New DataViewManager() manager.DataViewSettingCollectionString = src End Sub End Class", GetCA3075DataViewBasicResultAt(10, 5) ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using DertInfo.WEB.Models; using DertInfo.WEB.ViewModels.ImageVMs; using DertInfo.Util.Images; using DertInfo.WEB.Controllers.Base; using System.Configuration; using DertInfo.WEB.Core.Session; using DertInfo.WEB.Core.AssetManagement; namespace DertInfo.WEB.Controllers { public class ImageController : DertControllerBase { private readonly IImageRepository imageRepo; private readonly IGroupRepository groupRepo; private readonly IMarkingSheetImageRepository markingSheetImageRepo; private readonly IDanceRepository danceRepo; private readonly ITeamImageRepository teamImageRepo; private readonly IEventImageRepository eventImageRepo; private readonly IGroupImageRepository groupImageRepo; public ImageController(IImageRepository imageRepository, IGroupRepository groupRepository, IMarkingSheetImageRepository markingSheetImageRepository, IDanceRepository danceRepository, ITeamImageRepository teamImageRepository, IEventImageRepository eventImageRepository, IGroupImageRepository groupImageRepository) { this.imageRepo = imageRepository; this.groupRepo = groupRepository; this.markingSheetImageRepo = markingSheetImageRepository; this.danceRepo = danceRepository; this.teamImageRepo = teamImageRepository; this.eventImageRepo = eventImageRepository; this.groupImageRepo = groupImageRepository; } // // GET: /Image/ public ViewResult Index() { return View(imageRepo.AllIncluding(image => image.GroupImages, image => image.TeamImages)); } // // GET: /Image/Details/5 public ViewResult Details(int id) { return View(imageRepo.Find(id)); } // // GET: /Image/Create public ActionResult Create() { return View(); } // // POST: /Image/Create [HttpPost] public ActionResult Create(Image image) { if (ModelState.IsValid) { imageRepo.InsertOrUpdate(image); imageRepo.Save(); return RedirectToAction("Index"); } else { return View(); } } // // GET: /Image/Edit/5 public ActionResult Edit(int id) { return View(imageRepo.Find(id)); } // // POST: /Image/Edit/5 [HttpPost] public ActionResult Edit(Image image) { if (ModelState.IsValid) { imageRepo.InsertOrUpdate(image); imageRepo.Save(); return RedirectToAction("Index"); } else { return View(); } } // // GET: /Image/Delete/5 public ActionResult Delete(int id) { return View(imageRepo.Find(id)); } // // POST: /Image/Delete/5 [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { imageRepo.Delete(id); imageRepo.Save(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { imageRepo.Dispose(); } base.Dispose(disposing); } #region Partial View Operations #region Group Images public ActionResult ViewGroupGallery_Partial(int id) { GroupImage groupImage = new GroupImage(); List<GroupImage> groupImages = groupImage.ListByGroup(id); ImageGalleryViewModel imageGalleryViewModel = new ImageGalleryViewModel(id, groupImages); //List<Image> images = return PartialView("P_Group_Image_Gallery", imageGalleryViewModel); } public ActionResult AddGroupImage_Partial(int id, string message = "", string messageType = "") { if (message != string.Empty && messageType != string.Empty) { base.PostSectionMessage(messageType, "swapbox_group_imagegallery", message); } ImageUploadViewModel imageUploadVM = new ImageUploadViewModel(); imageUploadVM.ObjectId = id; return PartialView("P_Group_Image_Add", imageUploadVM); } //POST [HttpPost] public ActionResult AddGroupImage_Partial(ImageUploadViewModel imageUploadVM, HttpPostedFileBase file) { ////Get the group id. This is not great as the user could be working with another group in other window. //UserJourneyTracker userJourneyTracker = new UserJourneyTracker(); //int groupId = userJourneyTracker.LastAccessedGroupId; //NOW int groupId = imageUploadVM.ObjectId; if (file == null || file.ContentLength == 0) { return Json(new { Url = Url.Action("AddGroupImage_Partial", new { id = groupId, message = "Upload File Failed", messageType = "error" }) }); } string storageContainerUrl = ConfigurationManager.AppSettings["StorageContainerUrl"].ToString(); //todo - split the image and make relevant sizes at this point. if (file != null) { int imageId = 0; ImageStorage imageStorage = new ImageStorage("~/_temp/", "Images_GroupImages_"); imageStorage.SaveImageToLocalTemp(file); imageStorage.UploadToAzure(); imageId = imageStorage.CreateImageReference("Team Image"); imageStorage.CleanUp(); imageRepo.ApplyGroupImage(groupId, imageId); imageRepo.Save(); base.PostSectionMessage("success", "swapbox_group_imagegallery", "New image uploaded and added to your collection."); return Json(new { Url = Url.Action("ViewGroupGallery_Partial", new { id = groupId }) }); } else { base.PostSectionMessage("error", "swapbox_group_imagegallery", "No image was submitted. Cannot upload file. Please try again."); return Json(new { Url = Url.Action("AddGroupImage_Partial", new { id = groupId }) }); } } #endregion #region Marking Sheet Images public ActionResult ViewMarkingSheetGallery_Partial(int id) { List<MarkingSheetImage> markingSheetImages = markingSheetImageRepo.AllByDanceIdIncluding(id, msi => msi.Image).ToList(); ImageGalleryViewModel imageGalleryViewModel = new ImageGalleryViewModel(id, markingSheetImages); //List<Image> images = return PartialView("P_MarkingSheet_Image_Gallery", imageGalleryViewModel); } public ActionResult AddMarkingSheetImage_Partial(int id, string message = "", string messageType = "") { if (message != string.Empty && messageType != string.Empty) { base.PostSectionMessage(messageType, "swapbox_markingsheet_imagegallery", message); } ImageUploadViewModel imageUploadVM = new ImageUploadViewModel(); imageUploadVM.ObjectId = id; return PartialView("P_MarkingSheet_Image_Add", imageUploadVM); } //POST [HttpPost] public ActionResult AddMarkingSheetImage_Partial(ImageUploadViewModel imageUploadVM, HttpPostedFileBase file) { ////Get the markingSheet id. This is not great as the user could be working with another markingSheet in other window. //UserJourneyTracker userJourneyTracker = new UserJourneyTracker(); //int markingSheetId = userJourneyTracker.LastAccessedMarkingSheetId; //NOW int danceId = imageUploadVM.ObjectId; if (file == null || file.ContentLength == 0) { return Json(new { Url = Url.Action("AddMarkingSheetImage_Partial", new { id = danceId, message = "Upload File Failed", messageType = "error" }) }); } string storageContainerUrl = ConfigurationManager.AppSettings["StorageContainerUrl"].ToString(); //todo - split the image and make relevant sizes at this point. if (file != null) { int imageId = 0; ImageStorage imageStorage = new ImageStorage("~/_temp/", "Images_MarkingSheet_"); imageStorage.SaveImageToLocalTemp(file); imageStorage.UploadToAzure(); imageId = imageStorage.CreateImageReference("Team Image"); imageStorage.CleanUp(); Dance dance = danceRepo.Find(danceId); imageRepo.ApplyMarkingSheetImage(danceId, imageId, dance.AccessToken); imageRepo.Save(); base.PostSectionMessage("success", "swapbox_markingsheet_imagegallery", "New image uploaded and added to your collection."); return Json(new { Url = Url.Action("ViewMarkingSheetGallery_Partial", new { id = danceId }) }); } else { base.PostSectionMessage("error", "swapbox_markingsheet_imagegallery", "No image was submitted. Cannot upload file. Please try again."); return Json(new { Url = Url.Action("AddMarkingSheetImage_Partial", new { id = danceId }) }); } } #endregion ///GET /Image/EditGroupImage/ //public ActionResult EditGroupImage(int id) //{ // ImageViewModel imageViewModel = new ImageViewModel(); // return PartialView("P_Edit", imageViewModel); //} //GET //public ActionResult AddGroupImage_Partial(int id) //{ // ImageUploadViewModel imageUploadVM = new ImageUploadViewModel(); // imageUploadVM.ObjectId = id; // return PartialView("P_Group_Image_Add", imageUploadVM); //} //[HttpPost] //public ActionResult EditGroupImage(ImageViewModel imageVM, HttpPostedFileBase file) //{ // if (!ModelState.IsValid) // { // return PartialView("P_Edit", imageVM); // } // /* todo - convert to store images to azure*/ // IGroupRepository groupRepo = new GroupRepository(); // //not required - const string pictureUploadVirSavePath = "~/_user_upload/teampics/"; // string storageContainerUrl = ConfigurationSettings.AppSettings["StorageContainerUrl"].ToString(); // if (file != null) // { // string azureFileName = Core.AzureStorage.Images.HandleImagePost(file,"TeamImage_" + this.SystemDertYear + "_"); // //NEW UPLOADED FILE // //Save the file to disk // //ImageUpload imageUpload = new ImageUpload(); // //string uploadedFilename = imageUpload.SaveToFile(file, Server.MapPath(pictureUploadVirSavePath)); // //string imageStoreFilePath = pictureUploadVirSavePath + Url.Encode(uploadedFilename); // //Get the group to attach to from user // UserJourneyTracker userJourneyTracker = new UserJourneyTracker(); // //Attach file reference in the database // GroupImage groupImage = new GroupImage(); // groupImage.Image = imageVM.ToModel(); // groupImage.Image.ImagePath = storageContainerUrl + azureFileName; // groupImage.GroupId = userJourneyTracker.LastAccessedGroupId; // groupImage.SaveChanges(this.CurrentUser); // base.AddNotification(Core.Enumerations.NotificationTypes.Green, "New image added to your image gallery " + file.FileName); // return Json(new { Url = Url.Action("GroupGallery", new { groupId = userJourneyTracker.LastAccessedGroupId }) }); // } // else // { // //SUBMITTED WITH NO NEW FILE // throw new NotImplementedException("No File Post Not Handled"); // } // //Must return JSON as fulfilling a Json Ajax Call //} [HttpPost] public ActionResult JsonToggleTeamAttachment(int imageId, int objectId) { bool added = imageRepo.ToggleTeamImage(imageId, objectId); return Json(new { imageId = imageId , selected = added }); } [HttpPost] public ActionResult JsonSetTeamPrimary(int imageId, int objectId) { teamImageRepo.SetPrimaryImageId(objectId, imageId); return Json(new { imageId = imageId}); //redundant } [HttpPost] public ActionResult JsonSetEventPrimary(int imageId, int objectId) { eventImageRepo.SetPrimaryImageId(objectId, imageId); return Json(new { imageId = imageId }); //redundant } [HttpPost] public ActionResult JsonSetGroupPrimary(int imageId, int objectId) { groupImageRepo.SetPrimaryImageId(objectId, imageId); return Json(new { imageId = imageId }); //redundant } #endregion } }
/* * Copyright 2005 OpenXRI Foundation * * 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 DotNetXri.Client.Resolve { using java.util.Random; using org.openxri.AuthorityPath; using org.openxri.GCSAuthority; using org.openxri.XRIAuthority; using org.openxri.resolve.Cache; using org.openxri.xml.Service; using org.openxri.xml.Tags; using org.openxri.xml.XRD; using junit.framework.Test; using junit.framework.TestCase; using junit.framework.TestSuite; using junit.textui.TestRunner; /* ******************************************************************************** * Class: CacheTest ******************************************************************************** */ /** * @author =chetan * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class CacheTest :TestCase { /* **************************************************************************** * main() **************************************************************************** */ /** * */ public static void main(String[] oArgs) { // Pass control to the non-graphical test runner TestRunner.run(suite()); } // main() /* **************************************************************************** * suite() **************************************************************************** */ /** * */ public static Test suite() { return new TestSuite(typeof(CacheTest)); } // suite() /* **************************************************************************** * testCache() **************************************************************************** */ /** * */ public void testCache() { Cache oCache = new Cache(1000); assertTrue("Initial cache not empty", oCache.getNumNodes() == 0); XRD oDesc = new XRD(); Service atAuthService = new Service(); atAuthService.addMediaType(Tags.CONTENT_TYPE_XRDS + ";trust=none"); atAuthService.addType(Tags.SERVICE_AUTH_RES); atAuthService.addURI("http://gcs.epok.net/xri/resolve?ns=at"); oDesc.addService(atAuthService); XRD oDummy = new XRD(); Service dummyService = new Service(); dummyService.addMediaType(Tags.CONTENT_TYPE_XRDS + ";trust=none"); dummyService.addType(Tags.SERVICE_AUTH_RES); dummyService.addURI("http://www.example.com/xri/resolve?id=1"); oDummy.addService(dummyService); GCSAuthority oAuth = new GCSAuthority("@"); oCache.stuff(oAuth, oDesc); assertTrue("Initial cache incorrect", oCache.getNumNodes() == 1); oCache.stuff( (XRIAuthority) AuthorityPath.buildAuthorityPath("@!a!b!foo"), oDummy); assertTrue("Cache size incorrect", oCache.getNumNodes() == 4); oCache.stuff( (XRIAuthority) AuthorityPath.buildAuthorityPath("@!a!c!moo"), oDummy); assertTrue("Cache size incorrect", oCache.getNumNodes() == 6); oCache.stuff( (XRIAuthority) AuthorityPath.buildAuthorityPath("@!a!c!woo"), oDummy); assertTrue("Cache size incorrect", oCache.getNumNodes() == 7); Cache.CachedValue oVal = oCache.find( (XRIAuthority) AuthorityPath.buildAuthorityPath("@!a!c!woo"), false); assertTrue("Cached value not found", oVal != null); oVal = oCache.find( (XRIAuthority) AuthorityPath.buildAuthorityPath("@!a!b!woo"), false); assertTrue("Cached value should not have been found", oVal == null); oCache.dump(); } // testCache() /* **************************************************************************** * testConcurrent() **************************************************************************** */ /** * */ public void testConcurrent() { Cache oCache = new Cache(1000); oCache.prune((XRIAuthority) AuthorityPath.buildAuthorityPath("@")); assertTrue("Initial cache not empty", oCache.getNumNodes() == 0); XRD oDesc = new XRD(); Service atAuthService = new Service(); atAuthService.addMediaType(Tags.CONTENT_TYPE_XRDS + ";trust=none"); atAuthService.addType(Tags.SERVICE_AUTH_RES); atAuthService.addURI("http://gcs.epok.net/xri/resolve?ns=at"); oDesc.addService(atAuthService); GCSAuthority oAuth = new GCSAuthority("@"); oCache.stuff(oAuth, oDesc); assertTrue("Initial cache incorrect", oCache.getNumNodes() == 1); oCache.setMaxSize(5); Random oRand = new Random(); try { Thread[] oThreads = new StuffPruneThread[100]; for (int i = 0; i < oThreads.length; i++) { oThreads[i] = new StuffPruneThread(oRand); } for (int i = 0; i < oThreads.length; i++) { oThreads[i].start(); } for (int i = 0; i < oThreads.length; i++) { oThreads[i].join(); } } catch (Exception e) { assertTrue("Unexpected exception" + e, false); } oCache.dump(); assertTrue( "Max cache size not honored", oCache.getNumNodes() <= oCache.getMaxSize()); Cache.CachedValue oVal = oCache.find( (XRIAuthority) AuthorityPath.buildAuthorityPath("@"), false); assertTrue("Cached value for @ not found", oVal != null); } // testConcurrent() /* **************************************************************************** * Class: StuffPruneThread **************************************************************************** */ /** * */ class StuffPruneThread :Thread { private Random moRand = null; /* ************************************************************************ * Constructor() ************************************************************************ */ /** * */ public StuffPruneThread(Random oRand) { moRand = oRand; } // Constructor() /* ************************************************************************ * run() ************************************************************************ */ /** * */ public void run() { XRD oDummy = new XRD(); Service dummyService = new Service(); dummyService.addMediaType(Tags.CONTENT_TYPE_XRDS + ";trust=none"); dummyService.addType(Tags.SERVICE_AUTH_RES); dummyService.addURI("http://www.example.com/xri/resolve?id=1"); oDummy.addService(dummyService); String[] oCases = { "@!a1!b2!c3!d4", "@!x1!y2!z3", "@!a1!b2!c3", "@!a1!b2", "@!a1!b2!m3", "@!a1!o2!p3", "@!a1!o2!q3", "@!a1!b2!c3!d4!e5", "@!x1!y2" }; Cache oCache = new Cache(1000); for (int i = 0; i < 1000; i++) { int x = moRand.nextInt(oCases.length); bool bStuff = moRand.nextBoolean(); XRIAuthority oAuth = (XRIAuthority) AuthorityPath.buildAuthorityPath(oCases[x]); if (bStuff) { oCache.stuff(oAuth, oDummy); } else { oCache.prune(oAuth); } oCache.find(oAuth, true); } } // run() } // Class: StuffPruneThread } // Class: CacheTest }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security; using Xunit; namespace System.Net.Primitives.Functional.Tests { public static partial class NetworkCredentialTest { [Fact] public static void Ctor_Empty_Success() { NetworkCredential nc = new NetworkCredential(); Assert.Equal(String.Empty, nc.UserName); Assert.Equal(String.Empty, nc.Password); Assert.Equal(String.Empty, nc.Domain); } [Fact] public static void Ctor_UserNamePassword_Success() { NetworkCredential nc = new NetworkCredential("username", "password"); Assert.Equal("username", nc.UserName); Assert.Equal("password", nc.Password); Assert.Equal(String.Empty, nc.Domain); } [Fact] public static void Ctor_UserNamePasswordDomain_Success() { NetworkCredential nc = new NetworkCredential("username", "password", "domain"); Assert.Equal("username", nc.UserName); Assert.Equal("password", nc.Password); Assert.Equal("domain", nc.Domain); } [Fact] public static void UserName_GetSet_Success() { NetworkCredential nc = new NetworkCredential(); nc.UserName = "username"; Assert.Equal("username", nc.UserName); nc.UserName = null; Assert.Equal(String.Empty, nc.UserName); } [Fact] public static void Password_GetSet_Success() { NetworkCredential nc = new NetworkCredential(); nc.Password = "password"; Assert.Equal("password", nc.Password); } [Fact] public static void Domain_GetSet_Success() { NetworkCredential nc = new NetworkCredential(); nc.Domain = "domain"; Assert.Equal("domain", nc.Domain); nc.Domain = null; Assert.Equal(String.Empty, nc.Domain); } [Fact] public static void GetCredential_UriAuthenticationType_Success() { NetworkCredential nc = new NetworkCredential(); Assert.Equal(nc, nc.GetCredential(new Uri("http://microsoft.com"), "authenticationType")); } [Fact] public static void GetCredential_HostPortAuthenticationType_Success() { NetworkCredential nc = new NetworkCredential(); Assert.Equal(nc, nc.GetCredential("host", 500, "authenticationType")); } public static IEnumerable<object[]> SecurePassword_TestData() { yield return new object[] { "password", AsSecureString("password") }; yield return new object[] { "SecurePassword", AsSecureString("SecurePassword") }; yield return new object[] { "", AsSecureString("") }; yield return new object[] { null, AsSecureString(null) }; } public static IEnumerable<object[]> Password_RoundTestData() { yield return new object[] { "password", "planPassword" }; yield return new object[] { "SecurePassword", "justOnePassword" }; yield return new object[] { "", "OneMoreTest" }; yield return new object[] { null, null }; } [Fact] public static void Ctor_SecureString_Test() { string expectedUser = "UserName"; using (SecureString expectedSecurePassword = AsSecureString("password")) { NetworkCredential nc = new NetworkCredential(expectedUser, expectedSecurePassword); Assert.Equal(expectedUser, nc.UserName); Assert.True(expectedSecurePassword.CompareSecureString(nc.SecurePassword)); } } [Fact] public static void Ctor_SecureStringDomain_Test() { string expectedUser = "UserName"; string expectedDomain = "thisDomain"; using (SecureString expectedSecurePassword = AsSecureString("password")) { NetworkCredential nc = new NetworkCredential(expectedUser, expectedSecurePassword, expectedDomain); Assert.Equal(expectedUser, nc.UserName); Assert.Equal(expectedDomain, nc.Domain); Assert.True(expectedSecurePassword.CompareSecureString(nc.SecurePassword)); } } [Theory] [MemberData(nameof(SecurePassword_TestData))] public static void SecurePasswordSetGet_Test(string password, SecureString expectedPassword) { NetworkCredential nc = new NetworkCredential(); using (SecureString securePassword = AsSecureString(password)) { nc.SecurePassword = securePassword; Assert.True(expectedPassword.CompareSecureString(nc.SecurePassword)); } } [Theory] [MemberData(nameof(Password_RoundTestData))] public static void SecurePassword_Password_RoundData_Test(string expectedSecurePassword, string expectedPassword) { NetworkCredential nc = new NetworkCredential(); using (SecureString securePassword = AsSecureString(expectedSecurePassword)) { nc.SecurePassword = securePassword; Assert.Equal(expectedSecurePassword ?? string.Empty, nc.Password); nc.Password = expectedPassword; Assert.True(AsSecureString(expectedPassword).CompareSecureString(nc.SecurePassword)); } } private static bool CompareSecureString(this SecureString s1, SecureString s2) { return s1 != null && s2 != null && AsString(s1) == AsString(s2); } private static string AsString(SecureString sstr) { if (sstr.Length == 0) { return string.Empty; } IntPtr ptr = IntPtr.Zero; string result = string.Empty; try { ptr = Marshal.SecureStringToGlobalAllocUnicode(sstr); result = Marshal.PtrToStringUni(ptr); } finally { if (ptr != IntPtr.Zero) { Marshal.ZeroFreeGlobalAllocUnicode(ptr); } } return result; } private static SecureString AsSecureString(string str) { SecureString secureString = new SecureString(); if (string.IsNullOrEmpty(str)) { return secureString; } foreach (char ch in str) { secureString.AppendChar(ch); } return secureString; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** Object is the root class for all CLR objects. This class ** defines only the basics. ** ** ===========================================================*/ namespace System { using System; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; using FieldInfo = System.Reflection.FieldInfo; using BindingFlags = System.Reflection.BindingFlags; #if FEATURE_REMOTING using RemotingException = System.Runtime.Remoting.RemotingException; #endif // The Object is the root class for all object in the CLR System. Object // is the super class for all other CLR objects and provide a set of methods and low level // services to subclasses. These services include object synchronization and support for clone // operations. // //This class contains no data and does not need to be serializable [Serializable] [ClassInterface(ClassInterfaceType.AutoDual)] [System.Runtime.InteropServices.ComVisible(true)] public class Object { // Creates a new instance of an Object. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public Object() { } // Returns a String which represents the object instance. The default // for an object is to return the fully qualified name of the class. // public virtual String ToString() { return GetType().ToString(); } // Returns a boolean indicating if the passed in object obj is // Equal to this. Equality is defined as object equality for reference // types and bitwise equality for value types using a loader trick to // replace Equals with EqualsValue for value types). // public virtual bool Equals(Object obj) { return RuntimeHelpers.Equals(this, obj); } public static bool Equals(Object objA, Object objB) { if (objA==objB) { return true; } if (objA==null || objB==null) { return false; } return objA.Equals(objB); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static bool ReferenceEquals (Object objA, Object objB) { return objA == objB; } // GetHashCode is intended to serve as a hash function for this object. // Based on the contents of the object, the hash function will return a suitable // value with a relatively random distribution over the various inputs. // // The default implementation returns the sync block index for this instance. // Calling it on the same object multiple times will return the same value, so // it will technically meet the needs of a hash function, but it's less than ideal. // Objects (& especially value classes) should override this method. // public virtual int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } // Returns a Type object which represent this object instance. // [System.Security.SecuritySafeCritical] // auto-generated [Pure] [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern Type GetType(); // Allow an object to free resources before the object is reclaimed by the GC. // [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] ~Object() { } // Returns a new object instance that is a memberwise copy of this // object. This is always a shallow copy of the instance. The method is protected // so that other object may only call this method on themselves. It is entended to // support the ICloneable interface. // [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] protected extern Object MemberwiseClone(); // Sets the value specified in the variant on the field // [System.Security.SecurityCritical] // auto-generated private void FieldSetter(String typeName, String fieldName, Object val) { Contract.Requires(typeName != null); Contract.Requires(fieldName != null); // Extract the field info object FieldInfo fldInfo = GetFieldInfo(typeName, fieldName); if (fldInfo.IsInitOnly) throw new FieldAccessException(Environment.GetResourceString("FieldAccess_InitOnly")); // Make sure that the value is compatible with the type // of field #if FEATURE_REMOTING System.Runtime.Remoting.Messaging.Message.CoerceArg(val, fldInfo.FieldType); #else Type pt=fldInfo.FieldType; if (pt.IsByRef) { pt = pt.GetElementType(); } if (!pt.IsInstanceOfType(val)) { val = Convert.ChangeType(val, pt, CultureInfo.InvariantCulture); } #endif // Set the value fldInfo.SetValue(this, val); } // Gets the value specified in the variant on the field // private void FieldGetter(String typeName, String fieldName, ref Object val) { Contract.Requires(typeName != null); Contract.Requires(fieldName != null); // Extract the field info object FieldInfo fldInfo = GetFieldInfo(typeName, fieldName); // Get the value val = fldInfo.GetValue(this); } // Gets the field info object given the type name and field name. // private FieldInfo GetFieldInfo(String typeName, String fieldName) { Contract.Requires(typeName != null); Contract.Requires(fieldName != null); Contract.Ensures(Contract.Result<FieldInfo>() != null); Type t = GetType(); while(null != t) { if(t.FullName.Equals(typeName)) { break; } t = t.BaseType; } if (null == t) { #if FEATURE_REMOTING throw new RemotingException(String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_BadType"), typeName)); #else throw new ArgumentException(); #endif } FieldInfo fldInfo = t.GetField(fieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if(null == fldInfo) { #if FEATURE_REMOTING throw new RemotingException(String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_BadField"), fieldName, typeName)); #else throw new ArgumentException(); #endif } return fldInfo; } } // Internal methodtable used to instantiate the "canonical" methodtable for generic instantiations. // The name "__Canon" will never been seen by users but it will appear a lot in debugger stack traces // involving generics so it is kept deliberately short as to avoid being a nuisance. [Serializable] [ClassInterface(ClassInterfaceType.AutoDual)] [System.Runtime.InteropServices.ComVisible(true)] internal class __Canon { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; namespace Orleans.Runtime.ConsistentRing { /// <summary> /// We use the 'backward/clockwise' definition to assign responsibilities on the ring. /// E.g. in a ring of nodes {5, 10, 15} the responsible for key 7 is 10 (the node is responsible for its predecessing range). /// The backwards/clockwise approach is consistent with many overlays, e.g., Chord, Cassandra, etc. /// Note: MembershipOracle uses 'forward/counter-clockwise' definition to assign responsibilities. /// E.g. in a ring of nodes {5, 10, 15}, the responsible of key 7 is node 5 (the node is responsible for its sucessing range).. /// </summary> internal class ConsistentRingProvider : IConsistentRingProvider, ISiloStatusListener // make the ring shutdown-able? { // internal, so that unit tests can access them internal SiloAddress MyAddress { get; private set; } internal IRingRange MyRange { get; private set; } /// list of silo members sorted by the hash value of their address private readonly List<SiloAddress> membershipRingList; private readonly ILogger log; private bool isRunning; private readonly int myKey; private readonly List<IRingRangeListener> statusListeners; public ConsistentRingProvider(SiloAddress siloAddr, ILoggerFactory loggerFactory) { log = loggerFactory.CreateLogger<ConsistentRingProvider>(); membershipRingList = new List<SiloAddress>(); MyAddress = siloAddr; myKey = MyAddress.GetConsistentHashCode(); // add myself to the list of members AddServer(MyAddress); MyRange = RangeFactory.CreateFullRange(); // i am responsible for the whole range statusListeners = new List<IRingRangeListener>(); Start(); } /// <summary> /// Returns the silo that this silo thinks is the primary owner of the key /// </summary> /// <param name="key"></param> /// <returns></returns> public SiloAddress GetPrimaryTargetSilo(uint key) { return CalculateTargetSilo(key); } public IRingRange GetMyRange() { return MyRange; // its immutable, so no need to clone } /// <summary> /// Returns null if silo is not in the list of members /// </summary> public List<SiloAddress> GetMySucessors(int n = 1) { return FindSuccessors(MyAddress, n); } /// <summary> /// Returns null if silo is not in the list of members /// </summary> public List<SiloAddress> GetMyPredecessors(int n = 1) { return FindPredecessors(MyAddress, n); } private void Start() { isRunning = true; } private void Stop() { isRunning = false; } internal void AddServer(SiloAddress silo) { lock (membershipRingList) { if (membershipRingList.Contains(silo)) return; // we already have this silo int myOldIndex = membershipRingList.FindIndex(elem => elem.Equals(MyAddress)); if (!(membershipRingList.Count == 0 || myOldIndex != -1)) throw new OrleansException(string.Format("{0}: Couldn't find my position in the ring {1}.", MyAddress, Utils.EnumerableToString(membershipRingList))); // insert new silo in the sorted order int hash = silo.GetConsistentHashCode(); // Find the last silo with hash smaller than the new silo, and insert the latter after (this is why we have +1 here) the former. // Notice that FindLastIndex might return -1 if this should be the first silo in the list, but then // 'index' will get 0, as needed. int index = membershipRingList.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1; membershipRingList.Insert(index, silo); // relating to triggering handler ... new node took over some of my responsibility if (index == myOldIndex || // new node was inserted in my place (myOldIndex == 0 && index == membershipRingList.Count - 1)) // I am the first node, and the new server is the last node { IRingRange oldRange = MyRange; try { MyRange = RangeFactory.CreateRange(unchecked((uint)hash), unchecked((uint)myKey)); } catch (OverflowException exc) { log.Error(ErrorCode.ConsistentRingProviderBase + 5, String.Format("OverflowException: hash as int= x{0, 8:X8}, hash as uint= x{1, 8:X8}, myKey as int x{2, 8:X8}, myKey as uint x{3, 8:X8}.", hash, (uint)hash, myKey, (uint)myKey), exc); } NotifyLocalRangeSubscribers(oldRange, MyRange, false); } log.Info("Added Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString()); } } public override string ToString() { lock (membershipRingList) { if (membershipRingList.Count == 1) return Utils.EnumerableToString(membershipRingList, silo => String.Format("{0} -> {1}", silo.ToStringWithHashCode(), RangeFactory.CreateFullRange())); var sb = new StringBuilder("["); for (int i=0; i < membershipRingList.Count; i++) { SiloAddress curr = membershipRingList[ i ]; SiloAddress next = membershipRingList[ (i +1) % membershipRingList.Count]; IRingRange range = RangeFactory.CreateRange(unchecked((uint)curr.GetConsistentHashCode()), unchecked((uint)next.GetConsistentHashCode())); sb.Append(String.Format("{0} -> {1}, ", curr.ToStringWithHashCode(), range)); } sb.Append("]"); return sb.ToString(); } } internal void RemoveServer(SiloAddress silo) { lock (membershipRingList) { int indexOfFailedSilo = membershipRingList.FindIndex(elem => elem.Equals(silo)); if (indexOfFailedSilo < 0) return; // we have already removed this silo membershipRingList.Remove(silo); // related to triggering handler int myNewIndex = membershipRingList.FindIndex(elem => elem.Equals(MyAddress)); if (myNewIndex == -1) throw new OrleansException(string.Format("{0}: Couldn't find my position in the ring {1}.", MyAddress, this.ToString())); bool wasMyPred = ((myNewIndex == indexOfFailedSilo) || (myNewIndex == 0 && indexOfFailedSilo == membershipRingList.Count)); // no need for '- 1' if (wasMyPred) // failed node was our predecessor { if (log.IsEnabled(LogLevel.Debug)) log.Debug("Failed server was my pred? {0}, updated view {1}", wasMyPred, this.ToString()); IRingRange oldRange = MyRange; if (membershipRingList.Count == 1) // i'm the only one left { MyRange = RangeFactory.CreateFullRange(); NotifyLocalRangeSubscribers(oldRange, MyRange, true); } else { int myNewPredIndex = myNewIndex == 0 ? membershipRingList.Count - 1 : myNewIndex - 1; int myPredecessorsHash = membershipRingList[myNewPredIndex].GetConsistentHashCode(); MyRange = RangeFactory.CreateRange(unchecked((uint)myPredecessorsHash), unchecked((uint)myKey)); NotifyLocalRangeSubscribers(oldRange, MyRange, true); } } log.Info("Removed Server {0} hash {1}. Current view {2}", silo, silo.GetConsistentHashCode(), this.ToString()); } } /// <summary> /// Returns null if silo is not in the list of members /// </summary> internal List<SiloAddress> FindPredecessors(SiloAddress silo, int count) { lock (membershipRingList) { int index = membershipRingList.FindIndex(elem => elem.Equals(silo)); if (index == -1) { log.Warn(ErrorCode.Runtime_Error_100201, "Got request to find predecessors of silo " + silo + ", which is not in the list of members."); return null; } var result = new List<SiloAddress>(); int numMembers = membershipRingList.Count; for (int i = index - 1; ((i + numMembers) % numMembers) != index && result.Count < count; i--) { result.Add(membershipRingList[(i + numMembers) % numMembers]); } return result; } } /// <summary> /// Returns null if silo is not in the list of members /// </summary> internal List<SiloAddress> FindSuccessors(SiloAddress silo, int count) { lock (membershipRingList) { int index = membershipRingList.FindIndex(elem => elem.Equals(silo)); if (index == -1) { log.Warn(ErrorCode.Runtime_Error_100203, "Got request to find successors of silo " + silo + ", which is not in the list of members."); return null; } var result = new List<SiloAddress>(); int numMembers = membershipRingList.Count; for (int i = index + 1; i % numMembers != index && result.Count < count; i++) { result.Add(membershipRingList[i % numMembers]); } return result; } } public bool SubscribeToRangeChangeEvents(IRingRangeListener observer) { lock (statusListeners) { if (statusListeners.Contains(observer)) return false; statusListeners.Add(observer); return true; } } public bool UnSubscribeFromRangeChangeEvents(IRingRangeListener observer) { lock (statusListeners) { return statusListeners.Contains(observer) && statusListeners.Remove(observer); } } private void NotifyLocalRangeSubscribers(IRingRange old, IRingRange now, bool increased) { log.Info("-NotifyLocalRangeSubscribers about old {0} new {1} increased? {2}", old, now, increased); List<IRingRangeListener> copy; lock (statusListeners) { copy = statusListeners.ToList(); } foreach (IRingRangeListener listener in copy) { try { listener.RangeChangeNotification(old, now, increased); } catch (Exception exc) { log.Error(ErrorCode.CRP_Local_Subscriber_Exception, String.Format("Local IRangeChangeListener {0} has thrown an exception when was notified about RangeChangeNotification about old {1} new {2} increased? {3}", listener.GetType().FullName, old, now, increased), exc); } } } public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { // This silo's status has changed if (updatedSilo.Equals(MyAddress)) { if (status.IsTerminating()) { Stop(); } } else // Status change for some other silo { if (status.IsTerminating()) { RemoveServer(updatedSilo); } else if (status == SiloStatus.Active) // do not do anything with SiloStatus.Created or SiloStatus.Joining -- wait until it actually becomes active { AddServer(updatedSilo); } } } /// <summary> /// Finds the silo that owns the given hash value. /// This routine will always return a non-null silo address unless the excludeThisSiloIfStopping parameter is true, /// this is the only silo known, and this silo is stopping. /// </summary> /// <param name="hash"></param> /// <param name="excludeThisSiloIfStopping"></param> /// <returns></returns> public SiloAddress CalculateTargetSilo(uint hash, bool excludeThisSiloIfStopping = true) { SiloAddress siloAddress = null; lock (membershipRingList) { // excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method. bool excludeMySelf = excludeThisSiloIfStopping && !isRunning; if (membershipRingList.Count == 0) { // If the membership ring is empty, then we're the owner by default unless we're stopping. return excludeMySelf ? null : MyAddress; } // use clockwise ... current code in membershipOracle.CalculateTargetSilo() does counter-clockwise ... // if you want to stick to counter-clockwise, change the responsibility definition in 'In()' method & responsibility defs in OrleansReminderMemory // need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes for (int index = 0; index < membershipRingList.Count; ++index) { var siloAddr = membershipRingList[index]; if (IsSiloNextInTheRing(siloAddr, hash, excludeMySelf)) { siloAddress = siloAddr; break; } } if (siloAddress == null) { // if not found in traversal, then first silo should be returned (we are on a ring) // if you go back to their counter-clockwise policy, then change the 'In()' method in OrleansReminderMemory siloAddress = membershipRingList[0]; // vs [membershipRingList.Count - 1]; for counter-clockwise policy // Make sure it's not us... if (siloAddress.Equals(MyAddress) && excludeMySelf) { // vs [membershipRingList.Count - 2]; for counter-clockwise policy siloAddress = membershipRingList.Count > 1 ? membershipRingList[1] : null; } } } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Silo {0} calculated ring partition owner silo {1} for key {2}: {3} --> {4}", MyAddress, siloAddress, hash, hash, siloAddress.GetConsistentHashCode()); return siloAddress; } private bool IsSiloNextInTheRing(SiloAddress siloAddr, uint hash, bool excludeMySelf) { return siloAddr.GetConsistentHashCode() >= hash && (!siloAddr.Equals(MyAddress) || !excludeMySelf); } } }
// 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 Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryNullableEqualTests { #region Test methods [Fact] public static void CheckNullableBoolEqualTest() { bool?[] array = new bool?[] { null, true, false }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableBoolEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableByteEqualTest() { byte?[] array = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableByteEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableCharEqualTest() { char?[] array = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableCharEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableDecimalEqualTest() { decimal?[] array = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDecimalEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableDoubleEqualTest() { double?[] array = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDoubleEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableFloatEqualTest() { float?[] array = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableFloatEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableIntEqualTest() { int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableIntEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableLongEqualTest() { long?[] array = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableLongEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableSByteEqualTest() { sbyte?[] array = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableSByteEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableShortEqualTest() { short?[] array = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableShortEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableUIntEqualTest() { uint?[] array = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUIntEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableULongEqualTest() { ulong?[] array = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableULongEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableUShortEqualTest() { ushort?[] array = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUShortEqual(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyNullableBoolEqual(bool? a, bool? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a == b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableByteEqual(byte? a, byte? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a == b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableCharEqual(char? a, char? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a == b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableDecimalEqual(decimal? a, decimal? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a == b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableDoubleEqual(double? a, double? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a == b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableFloatEqual(float? a, float? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a == b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableIntEqual(int? a, int? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a == b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableLongEqual(long? a, long? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a == b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableSByteEqual(sbyte? a, sbyte? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a == b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableShortEqual(short? a, short? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a == b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableUIntEqual(uint? a, uint? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a == b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableULongEqual(ulong? a, ulong? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a == b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableUShortEqual(ushort? a, ushort? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a == b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } #endregion } }
//------------------------------------------------------------------------------ // Copyright (c) 2014-2016 the original author or authors. All Rights Reserved. // // NOTICE: You are permitted to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. //------------------------------------------------------------------------------ using Moq; using Robotlegs.Bender.Framework.API; using NUnit.Framework; using Robotlegs.Bender.Framework.Impl; using Robotlegs.Bender.Extensions.Mediation.API; using Robotlegs.Bender.Extensions.ViewManagement.Support; using Robotlegs.Bender.Extensions.Matching; using System; using System.Collections.Generic; using Robotlegs.Bender.Extensions.Mediation.Support; using Robotlegs.Bender.Framework.Impl.HookSupport; using Robotlegs.Bender.Framework.Impl.GuardSupport; using Robotlegs.Bender.Extensions.Mediation.DSL; namespace Robotlegs.Bender.Extensions.Mediation.Impl { public class MediatorFactoryTest { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ public Mock<IMediatorManager> manager; /*============================================================================*/ /* Private Properties */ /*============================================================================*/ private IInjector injector; private MediatorFactory factory; /*============================================================================*/ /* Test Setup and Teardown */ /*============================================================================*/ [SetUp] public void Setup() { injector = new RobotlegsInjector(); factory = new MediatorFactory(injector); manager = new Mock<IMediatorManager> (); } /*============================================================================*/ /* Tests */ /*============================================================================*/ [Test] public void Mediator_Is_Created() { IMediatorMapping mapping = new MediatorMapping(CreateTypeFilter( new Type[1] {typeof(SupportView)} ), typeof(CallbackMediator)); object mediator = factory.CreateMediators(new SupportView(), typeof(SupportView), new List<IMediatorMapping>{mapping})[0]; Assert.That(mediator, Is.InstanceOf(typeof(CallbackMediator))); } [Test] public void Mediator_Is_Injected_Into() { int expected = 128; IMediatorMapping mapping = new MediatorMapping(CreateTypeFilter(new Type[1] { typeof(SupportView) }), typeof(InjectedMediator)); injector.Map(typeof(int)).ToValue(expected); InjectedMediator mediator = factory.CreateMediators (new SupportView (), typeof(SupportView), new List<IMediatorMapping> { mapping }) [0] as InjectedMediator; Assert.That(mediator.number, Is.EqualTo(expected)); } [Test] public void mediatedItem_is_injected_as_exact_type_into_mediator() { SupportView expected = new SupportView(); IMediatorMapping mapping = new MediatorMapping(CreateTypeFilter(new Type[1]{ typeof(SupportView) }), typeof(ViewInjectedMediator)); ViewInjectedMediator mediator = factory.CreateMediators(expected, typeof(SupportView), new List<IMediatorMapping> {mapping})[0] as ViewInjectedMediator; Assert.That(mediator.mediatedItem, Is.EqualTo(expected)); } [Test] public void mediatedItem_is_injected_as_requested_type_into_mediator() { SupportView expected = new SupportView(); IMediatorMapping mapping = new MediatorMapping(CreateTypeFilter( new Type[1]{ typeof(SupportContainer) }), typeof(ViewInjectedMediator)); ViewInjectedMediator mediator = factory.CreateMediators( expected, typeof(SupportView), new List<IMediatorMapping> {mapping})[0] as ViewInjectedMediator; Assert.That(mediator.mediatedItem, Is.EqualTo(expected)); } [Test] public void hooks_are_called() { Assert.That (HookCallCount (typeof(CallbackHook), typeof(CallbackHook)), Is.EqualTo (2)); } [Test] public void hook_receives_mediator_and_mediatedItem() { SupportView mediatedItem = new SupportView(); object injectedMediator = null; object injectedView = null; injector.Map(typeof(Action<MediatorHook>), "callback").ToValue((Action<MediatorHook>)delegate(MediatorHook hook) { injectedMediator = hook.mediator; injectedView = hook.mediatedItem; }); MediatorMapping mapping = new MediatorMapping(CreateTypeFilter( new Type[1]{ typeof(SupportView) }), typeof(ViewInjectedMediator)); mapping.WithHooks(typeof(MediatorHook)); factory.CreateMediators(mediatedItem, typeof(SupportView), new List<IMediatorMapping> {mapping}); Assert.That(injectedMediator, Is.InstanceOf<ViewInjectedMediator>()); Assert.That(injectedView, Is.EqualTo(mediatedItem)); } [Test] public void mediator_is_created_when_the_guard_allows() { Assert.That(MediatorsCreatedWithGuards(typeof(HappyGuard)), Is.EqualTo(1)); } [Test] public void mediator_is_created_when_all_guards_allow() { Assert.That(MediatorsCreatedWithGuards(typeof(HappyGuard), typeof(HappyGuard)), Is.EqualTo(1)); } [Test] public void mediator_is_not_created_when_the_guard_denies() { Assert.That(MediatorsCreatedWithGuards(typeof(GrumpyGuard)), Is.EqualTo(0)); } [Test] public void mediator_is_not_created_when_any_guards_denies() { Assert.That(MediatorsCreatedWithGuards(typeof(HappyGuard), typeof(GrumpyGuard)), Is.EqualTo(0)); } [Test] public void mediator_is_not_created_when_all_guards_deny() { Assert.That(MediatorsCreatedWithGuards(typeof(GrumpyGuard), typeof(GrumpyGuard)), Is.EqualTo(0)); } [Test] public void same_mediators_are_returned_for_mappings_and_mediatedItem() { SupportView mediatedItem = new SupportView(); MediatorMapping mapping1 = new MediatorMapping(CreateTypeFilter(new Type[1]{typeof(SupportView)}), typeof(ViewInjectedMediator)); MediatorMapping mapping2 = new MediatorMapping(CreateTypeFilter(new Type[1]{typeof(SupportContainer)}), typeof(ViewInjectedAsRequestedMediator)); List<object> mediators1 = factory.CreateMediators(mediatedItem, typeof(SupportView), new List<IMediatorMapping>{mapping1, mapping2}); List<object> mediators2 = factory.CreateMediators(mediatedItem, typeof(SupportView), new List<IMediatorMapping>{mapping1, mapping2}); Assert.That (mediators1, Is.EqualTo (mediators2).AsCollection); } [Test] public void expected_number_of_mediators_are_returned_for_mappings_and_mediatedItem() { SupportView mediatedItem = new SupportView(); MediatorMapping mapping1 = new MediatorMapping(CreateTypeFilter(new Type[1]{typeof(SupportView)}), typeof(ViewInjectedMediator)); MediatorMapping mapping2 = new MediatorMapping(CreateTypeFilter(new Type[1]{typeof(SupportContainer)}), typeof(ViewInjectedAsRequestedMediator)); List<object> mediators = factory.CreateMediators(mediatedItem, typeof(SupportView), new List<IMediatorMapping> {mapping1, mapping2}); Assert.That(mediators.Count, Is.EqualTo(2)); } [Test] public void getMediator() { SupportView mediatedItem = new SupportView(); IMediatorMapping mapping = new MediatorMapping(CreateTypeFilter(new Type[1]{typeof(SupportView)}), typeof(CallbackMediator)); factory.CreateMediators(mediatedItem, typeof(SupportView), new List<IMediatorMapping> {mapping}); Assert.That (factory.GetMediator (mediatedItem, mapping), Is.Not.Null); } [Test] public void removeMediator() { SupportView mediatedItem = new SupportView(); IMediatorMapping mapping = new MediatorMapping(CreateTypeFilter(new Type[1]{typeof(SupportView)}), typeof(CallbackMediator)); factory.CreateMediators(mediatedItem, typeof(SupportView), new List<IMediatorMapping> {mapping}); factory.RemoveMediators(mediatedItem); Assert.That (factory.GetMediator (mediatedItem, mapping), Is.Null); } [Test] public void creating_mediator_gives_mediator_to_mediator_manager() { SupportView mediatedItem = new SupportView(); IMediatorMapping mapping = new MediatorMapping(CreateTypeFilter(new Type[1]{typeof(SupportView)}), typeof(CallbackMediator)); injector.Map<IMediatorManager> ().ToValue (manager.Object); factory = new MediatorFactory (injector); factory.CreateMediators(mediatedItem, typeof(SupportView), new List<IMediatorMapping> {mapping}); factory.CreateMediators(mediatedItem, typeof(SupportView), new List<IMediatorMapping> {mapping}); manager.Verify(_manager=>_manager.AddMediator(It.IsAny<CallbackMediator>(), It.Is<SupportView>(arg2=>arg2 == mediatedItem), It.Is<IMediatorMapping>(arg3=>arg3 == mapping)), Times.Once); } [Test] public void removeMediator_removes_mediator_from_manager() { SupportView mediatedItem = new SupportView(); IMediatorMapping mapping = new MediatorMapping(CreateTypeFilter(new Type[1]{typeof(SupportView)}), typeof(CallbackMediator)); injector.Map<IMediatorManager> ().ToValue (manager.Object); factory = new MediatorFactory(injector); factory.CreateMediators(mediatedItem, typeof(SupportView), new List<IMediatorMapping> {mapping}); factory.RemoveMediators(mediatedItem); factory.RemoveMediators(mediatedItem); manager.Verify (_manager => _manager.RemoveMediator (It.IsAny<CallbackMediator> (), It.Is<object> (arg2 => arg2 == mediatedItem), It.Is<IMediatorMapping> (arg3 => arg3 == mapping)), Times.Once); } [Test] public void removeAllMediators_removes_all_mediators_from_manager() { SupportView mediatedItem1 = new SupportView(); SupportView mediatedItem2 = new SupportView(); IMediatorMapping mapping1 = new MediatorMapping(CreateTypeFilter(new Type[1]{typeof(SupportView)}), typeof(CallbackMediator)); IMediatorMapping mapping2 = new MediatorMapping(CreateTypeFilter(new Type[1]{typeof(SupportContainer)}), typeof(ViewInjectedAsRequestedMediator)); injector.Map<IMediatorManager> ().ToValue (manager.Object); factory = new MediatorFactory (injector); factory.CreateMediators (mediatedItem1, typeof(SupportView), new List<IMediatorMapping>{ mapping1, mapping2 }); factory.CreateMediators (mediatedItem2, typeof(SupportView), new List<IMediatorMapping>{ mapping1, mapping2 }); factory.RemoveAllMediators(); manager.Verify(_manager=>_manager.RemoveMediator( It.IsAny<CallbackMediator>(), It.Is<object>(arg2=>arg2==mediatedItem1), It.Is<IMediatorMapping>(arg3=>arg3==mapping1)), Times.Once); manager.Verify(_manager=>_manager.RemoveMediator( It.IsAny<ViewInjectedAsRequestedMediator>(), It.Is<object>(arg2=>arg2==mediatedItem1), It.Is<IMediatorMapping>(arg3=>arg3==mapping2)), Times.Once); manager.Verify(_manager=>_manager.RemoveMediator( It.IsAny<CallbackMediator>(), It.Is<object>(arg2=>arg2==mediatedItem2), It.Is<IMediatorMapping>(arg3=>arg3==mapping1)), Times.Once); manager.Verify(_manager=>_manager.RemoveMediator( It.IsAny<ViewInjectedAsRequestedMediator>(), It.Is<object>(arg2=>arg2==mediatedItem2), It.Is<IMediatorMapping>(arg3=>arg3==mapping2)), Times.Once); } /*============================================================================*/ /* Private Functions */ /*============================================================================*/ private int HookCallCount(params object[] hooks) { int hookCallCount = 0; Action hookCallback = delegate() { hookCallCount++; }; injector.Map(typeof(Action), "hookCallback").ToValue(hookCallback); MediatorMapping mapping = new MediatorMapping(CreateTypeFilter(new Type[1]{typeof(SupportView)}), typeof(CallbackMediator)); mapping.WithHooks(hooks); factory.CreateMediators(new SupportView(), typeof(SupportView), new List<IMediatorMapping>{mapping}); return hookCallCount; } private int MediatorsCreatedWithGuards(params object[] guards) { MediatorMapping mapping = new MediatorMapping(CreateTypeFilter(new Type[1]{typeof(SupportView)}), typeof(CallbackMediator)); mapping.WithGuards(guards); List<object> mediators = factory.CreateMediators(new SupportView(), typeof(SupportView), new List<IMediatorMapping> {mapping}); return mediators.Count; } private ITypeFilter CreateTypeFilter(Type[] allOf, Type[] anyOf = null, Type[] noneOf = null) { TypeMatcher matcher = new TypeMatcher(); if (allOf != null) matcher.AllOf(allOf); if (anyOf != null) matcher.AnyOf(anyOf); if (noneOf != null) matcher.NoneOf(noneOf); return matcher.CreateTypeFilter(); } } class InjectedMediator { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ [Inject] public int number; } class ViewInjectedMediator { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ [Inject] public SupportView mediatedItem; } class ViewInjectedAsRequestedMediator { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ [Inject] public SupportContainer mediatedItem; } class MediatorHook { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ [Inject] public SupportView mediatedItem; [Inject] public ViewInjectedMediator mediator; [Inject(true, "callback")] public Action<MediatorHook> callback; /*============================================================================*/ /* Public Functions */ /*============================================================================*/ public void Hook() { if(callback != null) { callback(this); } } } }
// 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.IO; using System.Linq; using EventStore.Common.Utils; namespace EventStore.Core.TransactionLog.LogRecords { [Flags] public enum PrepareFlags: ushort { None = 0x00, Data = 0x01, // prepare contains data TransactionBegin = 0x02, // prepare starts transaction TransactionEnd = 0x04, // prepare ends transaction StreamDelete = 0x08, // prepare deletes stream IsCommitted = 0x20, // prepare should be considered committed immediately, no commit will follow in TF //Update = 0x30, // prepare updates previous instance of the same event, DANGEROUS! IsJson = 0x100, // indicates data & metadata are valid json // aggregate flag set DeleteTombstone = TransactionBegin | TransactionEnd | StreamDelete, SingleWrite = Data | TransactionBegin | TransactionEnd } public static class PrepareFlagsExtensions { public static bool HasAllOf(this PrepareFlags flags, PrepareFlags flagSet) { return (flags & flagSet) == flagSet; } public static bool HasAnyOf(this PrepareFlags flags, PrepareFlags flagSet) { return (flags & flagSet) != 0; } public static bool HasNoneOf(this PrepareFlags flags, PrepareFlags flagSet) { return (flags & flagSet) == 0; } } public class PrepareLogRecord: LogRecord, IEquatable<PrepareLogRecord> { public const byte PrepareRecordVersion = 0; public readonly PrepareFlags Flags; public readonly long TransactionPosition; public readonly int TransactionOffset; public readonly int ExpectedVersion; // if IsCommitted is set, this is final EventNumber public readonly string EventStreamId; public readonly Guid EventId; public readonly Guid CorrelationId; public readonly DateTime TimeStamp; public readonly string EventType; public readonly byte[] Data; public readonly byte[] Metadata; public long InMemorySize { get { return sizeof(LogRecordType) + 1 + 8 + sizeof(PrepareFlags) + 8 + 4 + 4 + IntPtr.Size + EventStreamId.Length * 2 + 16 + 16 + 8 + IntPtr.Size + EventType.Length*2 + IntPtr.Size + Data.Length + IntPtr.Size + Metadata.Length; } } public PrepareLogRecord(long logPosition, Guid correlationId, Guid eventId, long transactionPosition, int transactionOffset, string eventStreamId, int expectedVersion, DateTime timeStamp, PrepareFlags flags, string eventType, byte[] data, byte[] metadata) : base(LogRecordType.Prepare, PrepareRecordVersion, logPosition) { Ensure.NotEmptyGuid(correlationId, "correlationId"); Ensure.NotEmptyGuid(eventId, "eventId"); Ensure.Nonnegative(transactionPosition, "transactionPosition"); if (transactionOffset < -1) throw new ArgumentOutOfRangeException("transactionOffset"); Ensure.NotNullOrEmpty(eventStreamId, "eventStreamId"); if (expectedVersion < Core.Data.ExpectedVersion.Any) throw new ArgumentOutOfRangeException("expectedVersion"); Ensure.NotNull(data, "data"); Flags = flags; TransactionPosition = transactionPosition; TransactionOffset = transactionOffset; ExpectedVersion = expectedVersion; EventStreamId = eventStreamId; EventId = eventId; CorrelationId = correlationId; TimeStamp = timeStamp; EventType = eventType ?? string.Empty; Data = data; Metadata = metadata ?? NoData; } internal PrepareLogRecord(BinaryReader reader, byte version, long logPosition): base(LogRecordType.Prepare, version, logPosition) { if (version != PrepareRecordVersion) throw new ArgumentException(string.Format( "PrepareRecord version {0} is incorrect. Supported version: {1}.", version, PrepareRecordVersion)); Flags = (PrepareFlags) reader.ReadUInt16(); TransactionPosition = reader.ReadInt64(); TransactionOffset = reader.ReadInt32(); ExpectedVersion = reader.ReadInt32(); EventStreamId = reader.ReadString(); EventId = new Guid(reader.ReadBytes(16)); CorrelationId = new Guid(reader.ReadBytes(16)); TimeStamp = new DateTime(reader.ReadInt64()); EventType = reader.ReadString(); var dataCount = reader.ReadInt32(); Data = dataCount == 0 ? NoData : reader.ReadBytes(dataCount); var metadataCount = reader.ReadInt32(); Metadata = metadataCount == 0 ? NoData : reader.ReadBytes(metadataCount); } public override void WriteTo(BinaryWriter writer) { base.WriteTo(writer); writer.Write((ushort) Flags); writer.Write(TransactionPosition); writer.Write(TransactionOffset); writer.Write(ExpectedVersion); writer.Write(EventStreamId); writer.Write(EventId.ToByteArray()); writer.Write(CorrelationId.ToByteArray()); writer.Write(TimeStamp.Ticks); writer.Write(EventType); writer.Write(Data.Length); writer.Write(Data); writer.Write(Metadata.Length); writer.Write(Metadata); } public bool Equals(PrepareLogRecord other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return other.LogPosition == LogPosition && other.Flags == Flags && other.TransactionPosition == TransactionPosition && other.TransactionOffset == TransactionOffset && other.ExpectedVersion == ExpectedVersion && other.EventStreamId.Equals(EventStreamId) && other.EventId == EventId && other.CorrelationId == CorrelationId && other.TimeStamp.Equals(TimeStamp) && other.EventType.Equals(EventType) && other.Data.SequenceEqual(Data) && other.Metadata.SequenceEqual(Metadata); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(PrepareLogRecord)) return false; return Equals((PrepareLogRecord)obj); } public override int GetHashCode() { unchecked { int result = LogPosition.GetHashCode(); result = (result * 397) ^ Flags.GetHashCode(); result = (result * 397) ^ TransactionPosition.GetHashCode(); result = (result * 397) ^ TransactionOffset; result = (result * 397) ^ ExpectedVersion; result = (result * 397) ^ EventStreamId.GetHashCode(); result = (result * 397) ^ EventId.GetHashCode(); result = (result * 397) ^ CorrelationId.GetHashCode(); result = (result * 397) ^ TimeStamp.GetHashCode(); result = (result * 397) ^ EventType.GetHashCode(); result = (result * 397) ^ Data.GetHashCode(); result = (result * 397) ^ Metadata.GetHashCode(); return result; } } public static bool operator ==(PrepareLogRecord left, PrepareLogRecord right) { return Equals(left, right); } public static bool operator !=(PrepareLogRecord left, PrepareLogRecord right) { return !Equals(left, right); } public override string ToString() { return string.Format("LogPosition: {0}, " + "Flags: {1}, " + "TransactionPosition: {2}, " + "TransactionOffset: {3}, " + "ExpectedVersion: {4}, " + "EventStreamId: {5}, " + "EventId: {6}, " + "CorrelationId: {7}, " + "TimeStamp: {8}, " + "EventType: {9}, " + "InMemorySize: {10}", LogPosition, Flags, TransactionPosition, TransactionOffset, ExpectedVersion, EventStreamId, EventId, CorrelationId, TimeStamp, EventType, InMemorySize); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace GuidGenerator.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.Contracts; namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyCopyrightAttribute : Attribute { private String _copyright; public AssemblyCopyrightAttribute(String copyright) { _copyright = copyright; } public String Copyright { get { return _copyright; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyTrademarkAttribute : Attribute { private String _trademark; public AssemblyTrademarkAttribute(String trademark) { _trademark = trademark; } public String Trademark { get { return _trademark; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyProductAttribute : Attribute { private String _product; public AssemblyProductAttribute(String product) { _product = product; } public String Product { get { return _product; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyCompanyAttribute : Attribute { private String _company; public AssemblyCompanyAttribute(String company) { _company = company; } public String Company { get { return _company; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyDescriptionAttribute : Attribute { private String _description; public AssemblyDescriptionAttribute(String description) { _description = description; } public String Description { get { return _description; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyTitleAttribute : Attribute { private String _title; public AssemblyTitleAttribute(String title) { _title = title; } public String Title { get { return _title; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyConfigurationAttribute : Attribute { private String _configuration; public AssemblyConfigurationAttribute(String configuration) { _configuration = configuration; } public String Configuration { get { return _configuration; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyDefaultAliasAttribute : Attribute { private String _defaultAlias; public AssemblyDefaultAliasAttribute(String defaultAlias) { _defaultAlias = defaultAlias; } public String DefaultAlias { get { return _defaultAlias; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyInformationalVersionAttribute : Attribute { private String _informationalVersion; public AssemblyInformationalVersionAttribute(String informationalVersion) { _informationalVersion = informationalVersion; } public String InformationalVersion { get { return _informationalVersion; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyFileVersionAttribute : Attribute { private String _version; public AssemblyFileVersionAttribute(String version) { if (version == null) throw new ArgumentNullException("version"); Contract.EndContractBlock(); _version = version; } public String Version { get { return _version; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class AssemblyCultureAttribute : Attribute { private String _culture; public AssemblyCultureAttribute(String culture) { _culture = culture; } public String Culture { get { return _culture; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class AssemblyVersionAttribute : Attribute { private String _version; public AssemblyVersionAttribute(String version) { _version = version; } public String Version { get { return _version; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyKeyFileAttribute : Attribute { private String _keyFile; public AssemblyKeyFileAttribute(String keyFile) { _keyFile = keyFile; } public String KeyFile { get { return _keyFile; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyDelaySignAttribute : Attribute { private bool _delaySign; public AssemblyDelaySignAttribute(bool delaySign) { _delaySign = delaySign; } public bool DelaySign { get { return _delaySign; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class AssemblyFlagsAttribute : Attribute { private AssemblyNameFlags _flags; // This, of course, should be typed as AssemblyNameFlags. The compat police don't allow such changes. public int AssemblyFlags { get { return (int)_flags; } } public AssemblyFlagsAttribute(AssemblyNameFlags assemblyFlags) { _flags = assemblyFlags; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] public sealed class AssemblyMetadataAttribute : Attribute { private String _key; private String _value; public AssemblyMetadataAttribute(string key, string value) { _key = key; _value = value; } public string Key { get { return _key; } } public string Value { get { return _value; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] public sealed class AssemblySignatureKeyAttribute : Attribute { private String _publicKey; private String _countersignature; public AssemblySignatureKeyAttribute(String publicKey, String countersignature) { _publicKey = publicKey; _countersignature = countersignature; } public String PublicKey { get { return _publicKey; } } public String Countersignature { get { return _countersignature; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyKeyNameAttribute : Attribute { private String _keyName; public AssemblyKeyNameAttribute(String keyName) { _keyName = keyName; } public String KeyName { get { return _keyName; } } } }
// <copyright file="SvdTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 Math.NET // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Double; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double.Factorization { /// <summary> /// Svd factorization tests for a dense matrix. /// </summary> [TestFixture, Category("LAFactorization")] public class SvdTests { /// <summary> /// Can factorize identity matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void CanFactorizeIdentity(int order) { var matrixI = Matrix<double>.Build.DenseIdentity(order); var factorSvd = matrixI.Svd(); var u = factorSvd.U; var vt = factorSvd.VT; var w = factorSvd.W; Assert.AreEqual(matrixI.RowCount, u.RowCount); Assert.AreEqual(matrixI.RowCount, u.ColumnCount); Assert.AreEqual(matrixI.ColumnCount, vt.RowCount); Assert.AreEqual(matrixI.ColumnCount, vt.ColumnCount); Assert.AreEqual(matrixI.RowCount, w.RowCount); Assert.AreEqual(matrixI.ColumnCount, w.ColumnCount); for (var i = 0; i < w.RowCount; i++) { for (var j = 0; j < w.ColumnCount; j++) { Assert.AreEqual(i == j ? 1.0 : 0.0, w[i, j]); } } } /// <summary> /// Can factorize a random matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(10, 6)] [TestCase(50, 48)] [TestCase(100, 98)] public void CanFactorizeRandomMatrix(int row, int column) { var matrixA = Matrix<double>.Build.Random(row, column, 1); var factorSvd = matrixA.Svd(); var u = factorSvd.U; var vt = factorSvd.VT; var w = factorSvd.W; // Make sure the U has the right dimensions. Assert.AreEqual(row, u.RowCount); Assert.AreEqual(row, u.ColumnCount); // Make sure the VT has the right dimensions. Assert.AreEqual(column, vt.RowCount); Assert.AreEqual(column, vt.ColumnCount); // Make sure the W has the right dimensions. Assert.AreEqual(row, w.RowCount); Assert.AreEqual(column, w.ColumnCount); // Make sure the U*W*VT is the original matrix. var matrix = u*w*vt; for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(matrixA[i, j], matrix[i, j], 1.0e-11); } } } /// <summary> /// Can check rank of a non-square matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(10, 8)] [TestCase(48, 52)] [TestCase(100, 93)] public void CanCheckRankOfNonSquare(int row, int column) { var matrixA = Matrix<double>.Build.Random(row, column, 1); var factorSvd = matrixA.Svd(); var mn = Math.Min(row, column); Assert.AreEqual(factorSvd.Rank, mn); } /// <summary> /// Can check rank of a square matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(9)] [TestCase(50)] [TestCase(90)] public void CanCheckRankSquare(int order) { var matrixA = Matrix<double>.Build.Random(order, order, 1); var factorSvd = matrixA.Svd(); if (factorSvd.Determinant != 0) { Assert.AreEqual(factorSvd.Rank, order); } else { Assert.AreEqual(factorSvd.Rank, order - 1); } } /// <summary> /// Can check rank of a square singular matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanCheckRankOfSquareSingular(int order) { var matrixA = Matrix<double>.Build.Dense(order, order); matrixA[0, 0] = 1; matrixA[order - 1, order - 1] = 1; for (var i = 1; i < order - 1; i++) { matrixA[i, i - 1] = 1; matrixA[i, i + 1] = 1; matrixA[i - 1, i] = 1; matrixA[i + 1, i] = 1; } var factorSvd = matrixA.Svd(); Assert.AreEqual(factorSvd.Determinant, 0); Assert.AreEqual(factorSvd.Rank, order - 1); } /// <summary> /// Solve for matrix if vectors are not computed throws <c>InvalidOperationException</c>. /// </summary> [Test] public void SolveMatrixIfVectorsNotComputedThrowsInvalidOperationException() { var matrixA = Matrix<double>.Build.Random(10, 10, 1); var factorSvd = matrixA.Svd(false); var matrixB = Matrix<double>.Build.Random(10, 10, 1); Assert.That(() => factorSvd.Solve(matrixB), Throws.InvalidOperationException); } /// <summary> /// Solve for vector if vectors are not computed throws <c>InvalidOperationException</c>. /// </summary> [Test] public void SolveVectorIfVectorsNotComputedThrowsInvalidOperationException() { var matrixA = Matrix<double>.Build.Random(10, 10, 1); var factorSvd = matrixA.Svd(false); var vectorb = Vector<double>.Build.Random(10, 1); Assert.That(() => factorSvd.Solve(vectorb), Throws.InvalidOperationException); } /// <summary> /// Can solve a system of linear equations for a random vector (Ax=b). /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(9, 10)] [TestCase(50, 50)] [TestCase(90, 100)] public void CanSolveForRandomVector(int row, int column) { var matrixA = Matrix<double>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var vectorb = Vector<double>.Build.Random(row, 1); var resultx = factorSvd.Solve(vectorb); Assert.AreEqual(matrixA.ColumnCount, resultx.Count); var matrixBReconstruct = matrixA*resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1.0e-11); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B). /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(4, 4)] [TestCase(7, 8)] [TestCase(10, 10)] [TestCase(45, 50)] [TestCase(80, 100)] public void CanSolveForRandomMatrix(int row, int column) { var matrixA = Matrix<double>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var matrixB = Matrix<double>.Build.Random(row, column, 1); var matrixX = factorSvd.Solve(matrixB); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA*matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-11); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve for a random vector into a result vector. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(9, 10)] [TestCase(50, 50)] [TestCase(90, 100)] public void CanSolveForRandomVectorWhenResultVectorGiven(int row, int column) { var matrixA = Matrix<double>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var vectorb = Vector<double>.Build.Random(row, 1); var vectorbCopy = vectorb.Clone(); var resultx = new DenseVector(column); factorSvd.Solve(vectorb, resultx); var matrixBReconstruct = matrixA*resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1.0e-11); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure b didn't change. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorbCopy[i], vectorb[i]); } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(4, 4)] [TestCase(7, 8)] [TestCase(10, 10)] [TestCase(45, 50)] [TestCase(80, 100)] public void CanSolveForRandomMatrixWhenResultMatrixGiven(int row, int column) { var matrixA = Matrix<double>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var matrixB = Matrix<double>.Build.Random(row, column, 1); var matrixBCopy = matrixB.Clone(); var matrixX = Matrix<double>.Build.Dense(column, column); factorSvd.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA*matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-11); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Test.Common; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { [Trait("IPv4", "true")] [Trait("IPv6", "true")] public class DualMode { // Ports 8 and 8887 are unassigned as per https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt private const int UnusedPort = 8; private const int UnusedBindablePort = 8887; private readonly ITestOutputHelper _log; private static IPAddress[] ValidIPv6Loopbacks = new IPAddress[] { new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 127, 0, 0, 1 }, 0), // ::127.0.0.1 IPAddress.Loopback.MapToIPv6(), // ::ffff:127.0.0.1 IPAddress.IPv6Loopback // ::1 }; public DualMode(ITestOutputHelper output) { _log = TestLogging.GetInstance(); Assert.True(Capability.IPv4Support() && Capability.IPv6Support()); } #region Constructor and Property [Fact] public void DualModeConstructor_InterNetworkV6Default() { Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); Assert.Equal(AddressFamily.InterNetworkV6, socket.AddressFamily); } [Fact] public void DualModeUdpConstructor_DualModeConfgiured() { Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp); Assert.Equal(AddressFamily.InterNetworkV6, socket.AddressFamily); } #endregion Constructor and Property #region ConnectAsync #region ConnectAsync to IPEndPoint [Fact] // Base case public void Socket_ConnectAsyncV4IPEndPointToV4Host_Throws() { Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, UnusedPort); Assert.Throws<NotSupportedException>(() => { socket.ConnectAsync(args); }); } [Fact] public void ConnectAsyncV4IPEndPointToV4Host_Success() { DualModeConnectAsync_IPEndPointToHost_Helper(IPAddress.Loopback, IPAddress.Loopback, false); } [Fact] public void ConnectAsyncV6IPEndPointToV6Host_Success() { DualModeConnectAsync_IPEndPointToHost_Helper(IPAddress.IPv6Loopback, IPAddress.IPv6Loopback, false); } [Fact] public void ConnectAsyncV4IPEndPointToV6Host_Fails() { Assert.Throws<SocketException>(() => { DualModeConnectAsync_IPEndPointToHost_Helper(IPAddress.Loopback, IPAddress.IPv6Loopback, false); }); } [Fact] public void ConnectAsyncV6IPEndPointToV4Host_Fails() { Assert.Throws<SocketException>(() => { DualModeConnectAsync_IPEndPointToHost_Helper(IPAddress.IPv6Loopback, IPAddress.Loopback, false); }); } [Fact] public void ConnectAsyncV4IPEndPointToDualHost_Success() { DualModeConnectAsync_IPEndPointToHost_Helper(IPAddress.Loopback, IPAddress.IPv6Any, true); } [Fact] public void ConnectAsyncV6IPEndPointToDualHost_Success() { DualModeConnectAsync_IPEndPointToHost_Helper(IPAddress.IPv6Loopback, IPAddress.IPv6Any, true); } private void DualModeConnectAsync_IPEndPointToHost_Helper(IPAddress connectTo, IPAddress listenOn, bool dualModeServer) { int port; Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); using (SocketServer server = new SocketServer(_log, listenOn, dualModeServer, out port)) { ManualResetEvent waitHandle = new ManualResetEvent(false); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += new EventHandler<SocketAsyncEventArgs>(AsyncCompleted); args.RemoteEndPoint = new IPEndPoint(connectTo, port); args.UserToken = waitHandle; socket.ConnectAsync(args); Assert.True(waitHandle.WaitOne(5000), "Timed out while waiting for connection"); if (args.SocketError != SocketError.Success) { throw new SocketException((int)args.SocketError); } Assert.True(socket.Connected); } } #endregion ConnectAsync to IPAddress #region ConnectAsync to DnsEndPoint [Theory] [MemberData(nameof(DualMode_Connect_IPAddress_DualMode_Data))] [PlatformSpecific(PlatformID.Windows)] public void DualModeConnectAsync_DnsEndPointToHost_Helper(IPAddress listenOn, bool dualModeServer) { int port; using (Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp)) using (SocketServer server = new SocketServer(_log, listenOn, dualModeServer, out port)) { ManualResetEvent waitHandle = new ManualResetEvent(false); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += new EventHandler<SocketAsyncEventArgs>(AsyncCompleted); args.RemoteEndPoint = new DnsEndPoint("localhost", port); args.UserToken = waitHandle; socket.ConnectAsync(args); waitHandle.WaitOne(); if (args.SocketError != SocketError.Success) { throw new SocketException((int)args.SocketError); } Assert.True(socket.Connected); } } #endregion ConnectAsync to DnsEndPoint #endregion ConnectAsync #region Accept #region Bind [Fact] // Base case // "The system detected an invalid pointer address in attempting to use a pointer argument in a call" public void Socket_BindV4IPEndPoint_Throws() { Assert.Throws<SocketException>(() => { using (Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, UnusedBindablePort)); } }); } [Fact] // Base Case; BSoD on Win7, Win8 with IPv4 uninstalled public void BindMappedV4IPEndPoint_Success() { using (Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp)) { socket.BindToAnonymousPort(IPAddress.Loopback.MapToIPv6()); } } [Fact] // BSoD on Win7, Win8 with IPv4 uninstalled public void BindV4IPEndPoint_Success() { using (Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp)) { socket.BindToAnonymousPort(IPAddress.Loopback); } } [Fact] public void BindV6IPEndPoint_Success() { using (Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp)) { socket.BindToAnonymousPort(IPAddress.IPv6Loopback); } } [Fact] public void Socket_BindDnsEndPoint_Throws() { Assert.Throws<ArgumentException>(() => { using (Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new DnsEndPoint("localhost", UnusedBindablePort)); } }); } #endregion Bind #region Accept Async/Event [Fact] public void AcceptAsyncV4BoundToSpecificV4_Success() { DualModeConnect_AcceptAsync_Helper(IPAddress.Loopback, IPAddress.Loopback); } [Fact] public void AcceptAsyncV4BoundToAnyV4_Success() { DualModeConnect_AcceptAsync_Helper(IPAddress.Any, IPAddress.Loopback); } [Fact] public void AcceptAsyncV6BoundToSpecificV6_Success() { DualModeConnect_AcceptAsync_Helper(IPAddress.IPv6Loopback, IPAddress.IPv6Loopback); } [Fact] public void AcceptAsyncV6BoundToAnyV6_Success() { DualModeConnect_AcceptAsync_Helper(IPAddress.IPv6Any, IPAddress.IPv6Loopback); } [Fact] public void AcceptAsyncV6BoundToSpecificV4_CantConnect() { Assert.Throws<SocketException>(() => { DualModeConnect_AcceptAsync_Helper(IPAddress.Loopback, IPAddress.IPv6Loopback); }); } [Fact] public void AcceptAsyncV4BoundToSpecificV6_CantConnect() { Assert.Throws<SocketException>(() => { DualModeConnect_AcceptAsync_Helper(IPAddress.IPv6Loopback, IPAddress.Loopback); }); } [Fact] public void AcceptAsyncV6BoundToAnyV4_CantConnect() { Assert.Throws<SocketException>(() => { DualModeConnect_AcceptAsync_Helper(IPAddress.Any, IPAddress.IPv6Loopback); }); } [Fact] public void AcceptAsyncV4BoundToAnyV6_Success() { DualModeConnect_AcceptAsync_Helper(IPAddress.IPv6Any, IPAddress.Loopback); } private void DualModeConnect_AcceptAsync_Helper(IPAddress listenOn, IPAddress connectTo) { using (Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp)) { int port = serverSocket.BindToAnonymousPort(listenOn); serverSocket.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += AsyncCompleted; ManualResetEvent waitHandle = new ManualResetEvent(false); args.UserToken = waitHandle; args.SocketError = SocketError.SocketError; _log.WriteLine(args.GetHashCode() + " SocketAsyncEventArgs with manual event " + waitHandle.GetHashCode()); if (!serverSocket.AcceptAsync(args)) { throw new SocketException((int)args.SocketError); } SocketClient client = new SocketClient(_log, serverSocket, connectTo, port); var waitHandles = new WaitHandle[2]; waitHandles[0] = waitHandle; waitHandles[1] = client.WaitHandle; int completedHandle = WaitHandle.WaitAny(waitHandles, 5000); if (completedHandle == WaitHandle.WaitTimeout) { throw new TimeoutException("Timed out while waiting for either of client and server connections..."); } if (completedHandle == 1) // Client finished { if (client.Error != SocketError.Success) { // Client SocketException throw new SocketException((int)client.Error); } if (!waitHandle.WaitOne(5000)) // Now wait for the server. { throw new TimeoutException("Timed out while waiting for the server accept..."); } } _log.WriteLine(args.SocketError.ToString()); if (args.SocketError != SocketError.Success) { throw new SocketException((int)args.SocketError); } Socket clientSocket = args.AcceptSocket; Assert.NotNull(clientSocket); Assert.True(clientSocket.Connected); Assert.Equal(AddressFamily.InterNetworkV6, clientSocket.AddressFamily); if (connectTo == IPAddress.Loopback) Assert.Contains(((IPEndPoint)clientSocket.LocalEndPoint).Address, ValidIPv6Loopbacks); else Assert.Equal(connectTo.MapToIPv6(), ((IPEndPoint)clientSocket.LocalEndPoint).Address); clientSocket.Dispose(); } } #endregion Accept Async/Event #endregion Accept #region Connectionless #region SendTo Async/Event [Fact] // Base case public void Socket_SendToAsyncV4IPEndPointToV4Host_Throws() { Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, UnusedPort); args.SetBuffer(new byte[1], 0, 1); bool async = socket.SendToAsync(args); Assert.False(async); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(SocketError.Fault, args.SocketError); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { // NOTE: on Linux, this API returns ENETUNREACH instead of EFAULT: this platform // checks the family of the provided socket address before checking its size // (as long as the socket address is large enough to store an address family). Assert.Equal(SocketError.NetworkUnreachable, args.SocketError); } else { // NOTE: on other Unix platforms, this API returns EINVAL instead of EFAULT. Assert.Equal(SocketError.InvalidArgument, args.SocketError); } } [Fact] // Base case // "The parameter remoteEP must not be of type DnsEndPoint." public void Socket_SendToAsyncDnsEndPoint_Throws() { Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", UnusedPort); args.SetBuffer(new byte[1], 0, 1); Assert.Throws<ArgumentException>(() => { socket.SendToAsync(args); }); } [Fact] public void SendToAsyncV4IPEndPointToV4Host_Success() { DualModeSendToAsync_IPEndPointToHost_Helper(IPAddress.Loopback, IPAddress.Loopback, false); } [Fact] public void SendToAsyncV6IPEndPointToV6Host_Success() { DualModeSendToAsync_IPEndPointToHost_Helper(IPAddress.IPv6Loopback, IPAddress.IPv6Loopback, false); } [Fact] public void SendToAsyncV4IPEndPointToV6Host_NotReceived() { Assert.Throws<TimeoutException>(() => { DualModeSendToAsync_IPEndPointToHost_Helper(IPAddress.Loopback, IPAddress.IPv6Loopback, false); }); } [Fact] public void SendToAsyncV6IPEndPointToV4Host_NotReceived() { Assert.Throws<TimeoutException>(() => { DualModeSendToAsync_IPEndPointToHost_Helper(IPAddress.IPv6Loopback, IPAddress.Loopback, false); }); } [Fact] [PlatformSpecific(~PlatformID.OSX)] public void SendToAsyncV4IPEndPointToDualHost_Success() { DualModeSendToAsync_IPEndPointToHost_Helper(IPAddress.Loopback, IPAddress.IPv6Any, true); } [Fact] [PlatformSpecific(~PlatformID.OSX)] public void SendToAsyncV6IPEndPointToDualHost_Success() { DualModeSendToAsync_IPEndPointToHost_Helper(IPAddress.IPv6Loopback, IPAddress.IPv6Any, true); } private void DualModeSendToAsync_IPEndPointToHost_Helper(IPAddress connectTo, IPAddress listenOn, bool dualModeServer) { int port; ManualResetEvent waitHandle = new ManualResetEvent(false); Socket client = new Socket(SocketType.Dgram, ProtocolType.Udp); using (SocketUdpServer server = new SocketUdpServer(_log, listenOn, dualModeServer, out port)) { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(connectTo, port); args.SetBuffer(new byte[1], 0, 1); args.UserToken = waitHandle; args.Completed += AsyncCompleted; bool async = client.SendToAsync(args); if (async) { Assert.True(waitHandle.WaitOne(5000), "Timeout while waiting for connection"); } Assert.Equal(1, args.BytesTransferred); if (args.SocketError != SocketError.Success) { throw new SocketException((int)args.SocketError); } bool success = server.WaitHandle.WaitOne(Configuration.FailingTestTimeout); // Make sure the bytes were received if (!success) { throw new TimeoutException(); } } } #endregion SendTo Async/Event #region ReceiveFrom Async/Event [Fact] // Base case // "The supplied EndPoint of AddressFamily InterNetwork is not valid for this Socket, use InterNetworkV6 instead." public void Socket_ReceiveFromAsyncV4IPEndPointFromV4Client_Throws() { Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, UnusedPort); args.SetBuffer(new byte[1], 0, 1); Assert.Throws<ArgumentException>(() => { socket.ReceiveFromAsync(args); }); } [Fact] // Base case [PlatformSpecific(~PlatformID.OSX)] // "The parameter remoteEP must not be of type DnsEndPoint." public void Socket_ReceiveFromAsyncDnsEndPoint_Throws() { using (Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp)) { int port = socket.BindToAnonymousPort(IPAddress.IPv6Loopback); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", port, AddressFamily.InterNetworkV6); args.SetBuffer(new byte[1], 0, 1); Assert.Throws<ArgumentException>(() => { socket.ReceiveFromAsync(args); }); } } [Fact] [PlatformSpecific(~PlatformID.OSX)] public void ReceiveFromAsyncV4BoundToSpecificV4_Success() { ReceiveFromAsync_Helper(IPAddress.Loopback, IPAddress.Loopback); } [Fact] [PlatformSpecific(~PlatformID.OSX)] public void ReceiveFromAsyncV4BoundToAnyV4_Success() { ReceiveFromAsync_Helper(IPAddress.Any, IPAddress.Loopback); } [Fact] [PlatformSpecific(~PlatformID.OSX)] public void ReceiveFromAsyncV6BoundToSpecificV6_Success() { ReceiveFromAsync_Helper(IPAddress.IPv6Loopback, IPAddress.IPv6Loopback); } [Fact] [PlatformSpecific(~PlatformID.OSX)] public void ReceiveFromAsyncV6BoundToAnyV6_Success() { ReceiveFromAsync_Helper(IPAddress.IPv6Any, IPAddress.IPv6Loopback); } [Fact] [PlatformSpecific(~PlatformID.OSX)] public void ReceiveFromAsyncV6BoundToSpecificV4_NotReceived() { Assert.Throws<TimeoutException>(() => { ReceiveFromAsync_Helper(IPAddress.Loopback, IPAddress.IPv6Loopback); }); } [Fact] [PlatformSpecific(~PlatformID.OSX)] public void ReceiveFromAsyncV4BoundToSpecificV6_NotReceived() { Assert.Throws<TimeoutException>(() => { ReceiveFromAsync_Helper(IPAddress.IPv6Loopback, IPAddress.Loopback); }); } [Fact] [PlatformSpecific(~PlatformID.OSX)] public void ReceiveFromAsyncV6BoundToAnyV4_NotReceived() { Assert.Throws<TimeoutException>(() => { ReceiveFromAsync_Helper(IPAddress.Any, IPAddress.IPv6Loopback); }); } [Fact] [PlatformSpecific(~PlatformID.OSX)] public void ReceiveFromAsyncV4BoundToAnyV6_Success() { ReceiveFromAsync_Helper(IPAddress.IPv6Any, IPAddress.Loopback); } private void ReceiveFromAsync_Helper(IPAddress listenOn, IPAddress connectTo) { using (Socket serverSocket = new Socket(SocketType.Dgram, ProtocolType.Udp)) { int port = serverSocket.BindToAnonymousPort(listenOn); ManualResetEvent waitHandle = new ManualResetEvent(false); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(listenOn, port); args.SetBuffer(new byte[1], 0, 1); args.UserToken = waitHandle; args.Completed += AsyncCompleted; bool async = serverSocket.ReceiveFromAsync(args); SocketUdpClient client = new SocketUdpClient(_log, serverSocket, connectTo, port); if (async && !waitHandle.WaitOne(200)) { throw new TimeoutException(); } if (args.SocketError != SocketError.Success) { throw new SocketException((int)args.SocketError); } Assert.Equal(1, args.BytesTransferred); Assert.Equal<Type>(args.RemoteEndPoint.GetType(), typeof(IPEndPoint)); IPEndPoint remoteEndPoint = args.RemoteEndPoint as IPEndPoint; Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily); Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address); } } #endregion ReceiveFrom Async/Event [Fact] [PlatformSpecific(PlatformID.OSX)] public void ReceiveFrom_NotSupported() { using (Socket sock = new Socket(SocketType.Dgram, ProtocolType.Udp)) { EndPoint ep = new IPEndPoint(IPAddress.Any, 0); sock.Bind(ep); byte[] buf = new byte[1]; Assert.Throws<PlatformNotSupportedException>(() => sock.ReceiveFrom(buf, ref ep)); Assert.Throws<PlatformNotSupportedException>(() => sock.ReceiveFrom(buf, SocketFlags.None, ref ep)); Assert.Throws<PlatformNotSupportedException>(() => sock.ReceiveFrom(buf, buf.Length, SocketFlags.None, ref ep)); Assert.Throws<PlatformNotSupportedException>(() => sock.ReceiveFrom(buf, 0, buf.Length, SocketFlags.None, ref ep)); } } [Fact] [PlatformSpecific(PlatformID.OSX)] public void ReceiveMessageFrom_NotSupported() { using (Socket sock = new Socket(SocketType.Dgram, ProtocolType.Udp)) { EndPoint ep = new IPEndPoint(IPAddress.Any, 0); sock.Bind(ep); byte[] buf = new byte[1]; SocketFlags flags = SocketFlags.None; IPPacketInformation packetInfo; Assert.Throws<PlatformNotSupportedException>(() => sock.ReceiveMessageFrom(buf, 0, buf.Length, ref flags, ref ep, out packetInfo)); } } [Fact] [PlatformSpecific(PlatformID.OSX)] public void ReceiveFromAsync_NotSupported() { using (Socket sock = new Socket(SocketType.Dgram, ProtocolType.Udp)) { byte[] buf = new byte[1]; EndPoint ep = new IPEndPoint(IPAddress.Any, 0); sock.Bind(ep); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.SetBuffer(buf, 0, buf.Length); args.RemoteEndPoint = ep; Assert.Throws<PlatformNotSupportedException>(() => sock.ReceiveFromAsync(args)); } } [Fact] [PlatformSpecific(PlatformID.OSX)] public void ReceiveMessageFromAsync_NotSupported() { using (Socket sock = new Socket(SocketType.Dgram, ProtocolType.Udp)) { byte[] buf = new byte[1]; EndPoint ep = new IPEndPoint(IPAddress.Any, 0); sock.Bind(ep); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.SetBuffer(buf, 0, buf.Length); args.RemoteEndPoint = ep; Assert.Throws<PlatformNotSupportedException>(() => sock.ReceiveMessageFromAsync(args)); } } #endregion Connectionless #region GC Finalizer test // This test assumes sequential execution of tests and that it is going to be executed after other tests // that used Sockets. [Fact] public void TestFinalizers() { // Making several passes through the FReachable list. for (int i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } } #endregion #region Helpers public static readonly object[][] DualMode_Connect_IPAddress_DualMode_Data = { new object[] { IPAddress.Loopback, false }, new object[] { IPAddress.IPv6Loopback, false }, new object[] { IPAddress.IPv6Any, true }, }; private class SocketServer : IDisposable { private readonly ITestOutputHelper _output; private Socket _server; private Socket _acceptedSocket; private EventWaitHandle _waitHandle = new AutoResetEvent(false); public EventWaitHandle WaitHandle { get { return _waitHandle; } } public SocketServer(ITestOutputHelper output, IPAddress address, bool dualMode, out int port) { _output = output; if (dualMode) { _server = new Socket(SocketType.Stream, ProtocolType.Tcp); } else { _server = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); } port = _server.BindToAnonymousPort(address); _server.Listen(1); IPAddress remoteAddress = address.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any; EndPoint remote = new IPEndPoint(remoteAddress, 0); SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.RemoteEndPoint = remote; e.Completed += new EventHandler<SocketAsyncEventArgs>(Accepted); e.UserToken = _waitHandle; _server.AcceptAsync(e); } private void Accepted(object sender, SocketAsyncEventArgs e) { EventWaitHandle handle = (EventWaitHandle)e.UserToken; _output.WriteLine( "Accepted: " + e.GetHashCode() + " SocketAsyncEventArgs with manual event " + handle.GetHashCode() + " error: " + e.SocketError); _acceptedSocket = e.AcceptSocket; handle.Set(); } public void Dispose() { try { _server.Dispose(); if (_acceptedSocket != null) _acceptedSocket.Dispose(); } catch (Exception) { } } } private class SocketClient { private IPAddress _connectTo; private Socket _serverSocket; private int _port; private readonly ITestOutputHelper _output; private EventWaitHandle _waitHandle = new AutoResetEvent(false); public EventWaitHandle WaitHandle { get { return _waitHandle; } } public SocketError Error { get; private set; } public SocketClient(ITestOutputHelper output, Socket serverSocket, IPAddress connectTo, int port) { _output = output; _connectTo = connectTo; _serverSocket = serverSocket; _port = port; Error = SocketError.Success; Task.Run(() => ConnectClient(null)); } private void ConnectClient(object state) { try { Socket socket = new Socket(_connectTo.AddressFamily, SocketType.Stream, ProtocolType.Tcp); SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.Completed += new EventHandler<SocketAsyncEventArgs>(Connected); e.RemoteEndPoint = new IPEndPoint(_connectTo, _port); e.UserToken = _waitHandle; socket.ConnectAsync(e); } catch (SocketException ex) { Error = ex.SocketErrorCode; _serverSocket.Dispose(); // Cancels the test } } private void Connected(object sender, SocketAsyncEventArgs e) { EventWaitHandle handle = (EventWaitHandle)e.UserToken; _output.WriteLine( "Connected: " + e.GetHashCode() + " SocketAsyncEventArgs with manual event " + handle.GetHashCode() + " error: " + e.SocketError); Error = e.SocketError; handle.Set(); } } private class SocketUdpServer : IDisposable { private readonly ITestOutputHelper _output; private Socket _server; private EventWaitHandle _waitHandle = new AutoResetEvent(false); public EventWaitHandle WaitHandle { get { return _waitHandle; } } public SocketUdpServer(ITestOutputHelper output, IPAddress address, bool dualMode, out int port) { _output = output; if (dualMode) { _server = new Socket(SocketType.Dgram, ProtocolType.Udp); } else { _server = new Socket(address.AddressFamily, SocketType.Dgram, ProtocolType.Udp); } port = _server.BindToAnonymousPort(address); IPAddress remoteAddress = address.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any; EndPoint remote = new IPEndPoint(remoteAddress, 0); SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.RemoteEndPoint = remote; e.SetBuffer(new byte[1], 0, 1); e.Completed += new EventHandler<SocketAsyncEventArgs>(Received); e.UserToken = _waitHandle; _server.ReceiveFromAsync(e); } private void Received(object sender, SocketAsyncEventArgs e) { EventWaitHandle handle = (EventWaitHandle)e.UserToken; _output.WriteLine( "Received: " + e.GetHashCode() + " SocketAsyncEventArgs with manual event " + handle.GetHashCode() + " error: " + e.SocketError); handle.Set(); } public void Dispose() { try { _server.Dispose(); } catch (Exception) { } } } private class SocketUdpClient { private readonly ITestOutputHelper _output; private int _port; private IPAddress _connectTo; private Socket _serverSocket; public SocketUdpClient(ITestOutputHelper output, Socket serverSocket, IPAddress connectTo, int port) { _output = output; _connectTo = connectTo; _port = port; _serverSocket = serverSocket; Task.Run(() => ClientSend(null)); } private void ClientSend(object state) { try { Socket socket = new Socket(_connectTo.AddressFamily, SocketType.Dgram, ProtocolType.Udp); SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.RemoteEndPoint = new IPEndPoint(_connectTo, _port); e.SetBuffer(new byte[1], 0, 1); socket.SendToAsync(e); } catch (SocketException) { _serverSocket.Dispose(); // Cancels the test } } } private void AsyncCompleted(object sender, SocketAsyncEventArgs e) { EventWaitHandle handle = (EventWaitHandle)e.UserToken; _log.WriteLine( "AsyncCompleted: " + e.GetHashCode() + " SocketAsyncEventArgs with manual event " + handle.GetHashCode() + " error: " + e.SocketError); handle.Set(); } #endregion Helpers } }
using System; using Gdk; using Gtk; using GLib; using System.Runtime.InteropServices;// InteropService; using Cairo; using Moscrif.IDE.Editors.ImageView; using MessageDialogs = Moscrif.IDE.Controls.MessageDialog; using Moscrif.IDE.Tool; using System.Collections.Generic; using System.IO; using Moscrif.IDE.Components; using Moscrif.IDE.Iface.Entities; namespace Moscrif.IDE.Editors { public class ImageEditor : IEditor { private Gtk.VBox vbox = null; private Gtk.ActionGroup editorAction = null; private string fileName = String.Empty; private string fileBarierName = String.Empty; List<BarierPoint> listPoint; private bool modified = false; private ImageCanvas ic; //private ImageToolBarControl itc; private ImageToolBarControl itc; private string statusFormat ="X: {0}; Y: {1}; W {2}; H {3}"; public ImageEditor(string filePath) { fileName =filePath; fileBarierName = fileName+".mso"; if(System.IO.File.Exists(fileBarierName)){ string barierFile; try { using (StreamReader file = new StreamReader(fileBarierName)) { barierFile = file.ReadToEnd(); file.Close(); file.Dispose(); } if(!string.IsNullOrEmpty(barierFile)){ //listPoint = JsonConvert.DeserializeObject<List<BarierPoint>>(barierFile); System.Web.Script.Serialization.JavaScriptSerializer jss= new System.Web.Script.Serialization.JavaScriptSerializer(); jss.RegisterConverters(new[]{new BarierPointJavaScriptConverter()} ); listPoint = jss.Deserialize<List<BarierPoint>>(barierFile); } } catch (Exception ex) { MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("file_cannot_open", fileBarierName), ex.Message, Gtk.MessageType.Error,null); ms.ShowDialog(); } } editorAction = new Gtk.ActionGroup("imageeditor"); //ic = new ImageCanvas(filePath,listPoint); ic = new ImageCanvas(filePath,listPoint) { Name = "canvas", CanDefault = true, CanFocus = true, Events = (Gdk.EventMask)16134 }; vbox = new Gtk.VBox(); /*Gdk.Color col = new Gdk.Color(255,255,0); vbox.ModifyBg(StateType.Normal, col);*/ itc = new ImageToolBarControl (ic);//new ImageToolBarControl(ic); itc.DeleteBarierLayerEvent+= delegate(object sender, EventArgs e) { if(System.IO.File.Exists(fileBarierName) ){ try{ System.IO.File.Delete(fileBarierName); OnModifiedChanged(false); ic.DeleteBarier(); }catch (Exception ex){ MessageDialogs mdd = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("cannot_delete_file",fileBarierName),ex.Message, Gtk.MessageType.Error); mdd.ShowDialog(); } } else { ic.DeleteBarier(); } }; vbox.PackStart(itc,false,false,0); ScrolledWindow sw = new Gtk.ScrolledWindow(); sw.ShadowType = Gtk.ShadowType.Out; sw.Hadjustment.ValueChanged += delegate(object sender, EventArgs e) { //Console.WriteLine("sw.Hadjustment -> {0}",sw.Hadjustment.Value); }; sw.Vadjustment.ValueChanged += delegate(object sender, EventArgs e) { //Console.WriteLine("sw.Vadjustment -> {0}",sw.Vadjustment.Value); }; Viewport vp = new Viewport () { ShadowType = ShadowType.None }; vp.ScrollEvent+= delegate(object o, ScrollEventArgs args) { if (args.Event.State == ModifierType.ControlMask) { switch (args.Event.Direction) { case ScrollDirection.Down: case ScrollDirection.Right: itc.ZoomOut(); return ; case ScrollDirection.Left: case ScrollDirection.Up: itc.ZoomIn(); return ; } } }; vp.MotionNotifyEvent+= delegate(object o, MotionNotifyEventArgs args) { Cairo.PointD offset = new Cairo.PointD(sw.Hadjustment.Value,sw.Vadjustment.Value); int x =(int)args.Event.X; int y =(int)args.Event.Y; if(ic.ConvertPointToCanvasPoint(offset, ref x, ref y)){ OnWriteToStatusbar(String.Format(statusFormat,x,y,ic.WidthImage,ic.HeightImage)); } if(itc.ToolState == ImageToolBarControl.ToolStateEnum.nothing ) return; if(itc.ToolState == ImageToolBarControl.ToolStateEnum.editpoint){ ic.StepMovingPoint((int)args.Event.X,(int)args.Event.Y,offset); //OnModifiedChanged(true); } }; vp.ButtonReleaseEvent+= delegate(object o, ButtonReleaseEventArgs args) { //Console.WriteLine("1_ButtonReleaseEvent"); if (args.Event.Button != 1) return; if(itc.ToolState == ImageToolBarControl.ToolStateEnum.nothing ) return; Cairo.PointD offset = new Cairo.PointD(sw.Hadjustment.Value,sw.Vadjustment.Value); if(itc.ToolState == ImageToolBarControl.ToolStateEnum.editpoint){ ic.EndMovingPoint((int)args.Event.X,(int)args.Event.Y,offset); OnModifiedChanged(true); } }; vp.ButtonPressEvent+= delegate(object o, ButtonPressEventArgs args) { if (args.Event.Button != 1) return; if(itc.ToolState == ImageToolBarControl.ToolStateEnum.nothing ) return; Cairo.PointD offset = new Cairo.PointD(sw.Hadjustment.Value,sw.Vadjustment.Value); if(itc.ToolState == ImageToolBarControl.ToolStateEnum.addpoint){ ic.AddPoint((int)args.Event.X,(int)args.Event.Y,offset); OnModifiedChanged(true); } else if(itc.ToolState == ImageToolBarControl.ToolStateEnum.deletepoint){ ic.DeletePoint((int)args.Event.X,(int)args.Event.Y,offset); OnModifiedChanged(true); } else if(itc.ToolState == ImageToolBarControl.ToolStateEnum.moviepoint){ ic.StartMovingPoint((int)args.Event.X,(int)args.Event.Y,offset); OnModifiedChanged(true); } else if(itc.ToolState == ImageToolBarControl.ToolStateEnum.editpoint){ if (args.Event.State == ModifierType.ShiftMask){ ic.DeletePoint((int)args.Event.X,(int)args.Event.Y,offset); OnModifiedChanged(true); return; } ic.EditPoint((int)args.Event.X,(int)args.Event.Y,offset); OnModifiedChanged(true); } }; sw.Add(vp); vp.Add (ic); vbox.PackEnd(sw,true,true,0); ic.Show (); vp.Show (); vbox.ShowAll(); } #region IEditor implementation public void Rename(string newName){ fileName = newName; } public bool RefreshSettings(){ ic.RefreshSetting(); return true; } public object GetSelected(){ return null; } public bool Save () { if ((!modified) || (ic.ListPoint== null)) return true; try { //string json = JsonConvert.SerializeObject(ic.ListPoint, Formatting.Indented); string json=""; System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); oSerializer.RegisterConverters(new[]{new BarierPointJavaScriptConverter()} ); string sJSON = oSerializer.Serialize(ic.ShapeListPoint); sJSON = sJSON.Replace("\"x\"","x"); sJSON = sJSON.Replace("\"y\"","y"); json = sJSON; using (StreamWriter file = new StreamWriter(fileBarierName)) { file.Write(json); file.Close(); file.Dispose(); } OnModifiedChanged(false); } catch (Exception ex) { MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("cannot_save_file",fileName), ex.Message, Gtk.MessageType.Error); ms.ShowDialog(); return false; } // do save return true; } public bool SaveAs (string newPath) { if (System.IO.File.Exists(newPath)) { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.YesNo, "", MainClass.Languages.Translate("overwrite_file", newPath), Gtk.MessageType.Question); int result = md.ShowDialog(); if (result != (int)Gtk.ResponseType.Yes) return false; } try { System.IO.File.Copy(fileName,newPath); fileName = newPath; } catch (Exception ex) { MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("cannot_save_file", newPath), ex.Message, Gtk.MessageType.Error); ms.ShowDialog(); return false; } // do save return true; //return true; //throw new NotImplementedException (); } public void Close() { } public bool SearchExpression (SearchPattern expresion){ return false; //throw new NotImplementedException (); } public bool SearchNext(SearchPattern expresion){ return false; //throw new NotImplementedException (); } public bool SearchPreviu(SearchPattern expresion){ return false; //throw new NotImplementedException (); } public bool Replace(SearchPattern expresion){ return false; //throw new NotImplementedException (); } public bool ReplaceAll(SearchPattern expresion){ return false; //throw new NotImplementedException (); } public List<FindResult> FindReplaceAll(SearchPattern expresion) { return null; } public bool Undo(){ return false; //throw new NotImplementedException (); } public bool Redo(){ return false; //throw new NotImplementedException (); } public string Caption { get { return System.IO.Path.GetFileName(fileName); } } public string FileName { get { return fileName; } } public bool Modified { get { return modified; } } public void GoToPosition(object position){ } public Gtk.Widget Control { get { return vbox; } } public Gtk.ActionGroup EditorAction { get {return editorAction;} } public void ActivateEditor(bool updateStatus){ if(updateStatus){ OnWriteToStatusbar(String.Format(statusFormat,0,0,ic.WidthImage,ic.HeightImage)); } } public event EventHandler<ModifiedChangedEventArgs> ModifiedChanged; public event EventHandler<WriteStatusEventArgs> WriteStatusChange; void OnModifiedChanged(bool newModified) { if (newModified != modified) modified = newModified; else return; ModifiedChangedEventArgs mchEventArg = new ModifiedChangedEventArgs(modified); if (ModifiedChanged != null) ModifiedChanged(this, mchEventArg); } void OnWriteToStatusbar(string message) { WriteStatusEventArgs mchEventArg = new WriteStatusEventArgs(message); if (WriteStatusChange != null) WriteStatusChange(this, mchEventArg); } #endregion } public class CairoGraphic : Gtk.DrawingArea { ImageSurface src; public CairoGraphic (ImageSurface src) { this.src = src; } protected override bool OnExposeEvent (Gdk.EventExpose args) { using (Context g = Gdk.CairoHelper.Create (args.Window)){ g.Source = new SurfacePattern (src); g.Paint (); } return true; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; using Newtonsoft.Json.Utilities.LinqBridge; namespace Newtonsoft.Json.Utilities { internal static class JavaScriptUtils { internal static readonly bool[] SingleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] DoubleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] HtmlCharEscapeFlags = new bool[128]; static JavaScriptUtils() { IList<char> escapeChars = new List<char> { '\n', '\r', '\t', '\\', '\f', '\b', }; for (int i = 0; i < ' '; i++) { escapeChars.Add((char)i); } foreach (var escapeChar in escapeChars.Union(new[] { '\'' })) { SingleQuoteCharEscapeFlags[escapeChar] = true; } foreach (var escapeChar in escapeChars.Union(new[] { '"' })) { DoubleQuoteCharEscapeFlags[escapeChar] = true; } foreach (var escapeChar in escapeChars.Union(new[] { '"', '\'', '<', '>', '&' })) { HtmlCharEscapeFlags[escapeChar] = true; } } private const string EscapedUnicodeText = "!"; public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandling, char quoteChar) { if (stringEscapeHandling == StringEscapeHandling.EscapeHtml) return HtmlCharEscapeFlags; if (quoteChar == '"') return DoubleQuoteCharEscapeFlags; return SingleQuoteCharEscapeFlags; } public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags) { if (s == null) return false; foreach (char c in s) { if (c >= charEscapeFlags.Length || charEscapeFlags[c]) return true; } return false; } public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, ref char[] writeBuffer) { // leading delimiter if (appendDelimiters) writer.Write(delimiter); if (s != null) { int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { var c = s[i]; if (c < charEscapeFlags.Length && !charEscapeFlags[c]) continue; string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; default: if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\'"; } else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\"""; } else { if (writeBuffer == null) writeBuffer = new char[6]; StringUtils.ToCharAsUnicode(c, writeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } } else { escapedValue = null; } break; } if (escapedValue == null) continue; bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText); if (i > lastWritePosition) { int length = i - lastWritePosition + ((isEscapedUnicodeText) ? 6 : 0); int start = (isEscapedUnicodeText) ? 6 : 0; if (writeBuffer == null || writeBuffer.Length < length) { char[] newBuffer = new char[length]; // the unicode text is already in the buffer // copy it over when creating new buffer if (isEscapedUnicodeText) Array.Copy(writeBuffer, newBuffer, 6); writeBuffer = newBuffer; } s.CopyTo(lastWritePosition, writeBuffer, start, length - start); // write unchanged chars before writing escaped text writer.Write(writeBuffer, start, length - start); } lastWritePosition = i + 1; if (!isEscapedUnicodeText) writer.Write(escapedValue); else writer.Write(writeBuffer, 0, 6); } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { int length = s.Length - lastWritePosition; if (writeBuffer == null || writeBuffer.Length < length) writeBuffer = new char[length]; s.CopyTo(lastWritePosition, writeBuffer, 0, length); // write remaining text writer.Write(writeBuffer, 0, length); } } // trailing delimiter if (appendDelimiters) writer.Write(delimiter); } public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters) { return ToEscapedJavaScriptString(value, delimiter, appendDelimiters, StringEscapeHandling.Default); } public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling) { bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter); using (StringWriter w = StringUtils.CreateStringWriter(StringUtils.GetLength(value) ?? 16)) { char[] buffer = null; WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, ref buffer); return w.ToString(); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; namespace Microsoft.Azure.Management.Sql { /// <summary> /// The Windows Azure SQL Database management API provides a RESTful set of /// web services that interact with Windows Azure SQL Database services to /// manage your databases. The API enables users to create, retrieve, /// update, and delete databases and servers. /// </summary> public static partial class ServerCommunicationLinkOperationsExtensions { /// <summary> /// Begins creating a new or updating an existing Azure SQL Database /// Server communication. To determine the status of the operation /// call GetServerCommunicationLinkOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='communicationLinkName'> /// Required. The name of the Azure SQL Database Server communication /// link to be operated on (Updated or created). /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating a /// Server communication link. /// </param> /// <returns> /// Response for long running Azure Sql Database server communication /// link operation. /// </returns> public static ServerCommunicationLinkCreateOrUpdateResponse BeginCreateOrUpdate(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IServerCommunicationLinkOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins creating a new or updating an existing Azure SQL Database /// Server communication. To determine the status of the operation /// call GetServerCommunicationLinkOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='communicationLinkName'> /// Required. The name of the Azure SQL Database Server communication /// link to be operated on (Updated or created). /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating a /// Server communication link. /// </param> /// <returns> /// Response for long running Azure Sql Database server communication /// link operation. /// </returns> public static Task<ServerCommunicationLinkCreateOrUpdateResponse> BeginCreateOrUpdateAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters, CancellationToken.None); } /// <summary> /// Creates a new or updates an existing Azure SQL Database Server /// communication link. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='communicationLinkName'> /// Required. The name of the Azure SQL Database Server communication /// link to be operated on (Updated or created). /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating a /// Server communication link. /// </param> /// <returns> /// Response for long running Azure Sql Database server communication /// link operation. /// </returns> public static ServerCommunicationLinkCreateOrUpdateResponse CreateOrUpdate(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IServerCommunicationLinkOperations)s).CreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new or updates an existing Azure SQL Database Server /// communication link. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='communicationLinkName'> /// Required. The name of the Azure SQL Database Server communication /// link to be operated on (Updated or created). /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating a /// Server communication link. /// </param> /// <returns> /// Response for long running Azure Sql Database server communication /// link operation. /// </returns> public static Task<ServerCommunicationLinkCreateOrUpdateResponse> CreateOrUpdateAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters, CancellationToken.None); } /// <summary> /// Deletes the Azure SQL Database server communication link with the /// given name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the server. /// </param> /// <param name='communicationLinkName'> /// Required. The name of the Azure SQL Database server communication /// link to be retrieved. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName) { return Task.Factory.StartNew((object s) => { return ((IServerCommunicationLinkOperations)s).DeleteAsync(resourceGroupName, serverName, communicationLinkName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the Azure SQL Database server communication link with the /// given name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the server. /// </param> /// <param name='communicationLinkName'> /// Required. The name of the Azure SQL Database server communication /// link to be retrieved. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName) { return operations.DeleteAsync(resourceGroupName, serverName, communicationLinkName, CancellationToken.None); } /// <summary> /// Returns information about an Azure SQL Database Server /// communication links. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the server to retrieve. /// </param> /// <param name='communicationLinkName'> /// Required. The name of the Azure SQL Database server communication /// link to be retrieved. /// </param> /// <returns> /// Represents the response to a get server communication link request. /// </returns> public static ServerCommunicationLinkGetResponse Get(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName) { return Task.Factory.StartNew((object s) => { return ((IServerCommunicationLinkOperations)s).GetAsync(resourceGroupName, serverName, communicationLinkName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns information about an Azure SQL Database Server /// communication links. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the server to retrieve. /// </param> /// <param name='communicationLinkName'> /// Required. The name of the Azure SQL Database server communication /// link to be retrieved. /// </param> /// <returns> /// Represents the response to a get server communication link request. /// </returns> public static Task<ServerCommunicationLinkGetResponse> GetAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName) { return operations.GetAsync(resourceGroupName, serverName, communicationLinkName, CancellationToken.None); } /// <summary> /// Gets the status of an Azure Sql Database Server communication link /// create or update operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <returns> /// Response for long running Azure Sql Database server communication /// link operation. /// </returns> public static ServerCommunicationLinkCreateOrUpdateResponse GetServerCommunicationLinkOperationStatus(this IServerCommunicationLinkOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IServerCommunicationLinkOperations)s).GetServerCommunicationLinkOperationStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the status of an Azure Sql Database Server communication link /// create or update operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <returns> /// Response for long running Azure Sql Database server communication /// link operation. /// </returns> public static Task<ServerCommunicationLinkCreateOrUpdateResponse> GetServerCommunicationLinkOperationStatusAsync(this IServerCommunicationLinkOperations operations, string operationStatusLink) { return operations.GetServerCommunicationLinkOperationStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Returns information about Azure SQL Database Server communication /// links. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server. /// </param> /// <returns> /// Represents the response to a List Azure Sql Server communication /// link request. /// </returns> public static ServerCommunicationLinkListResponse List(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName) { return Task.Factory.StartNew((object s) => { return ((IServerCommunicationLinkOperations)s).ListAsync(resourceGroupName, serverName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns information about Azure SQL Database Server communication /// links. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerCommunicationLinkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server. /// </param> /// <returns> /// Represents the response to a List Azure Sql Server communication /// link request. /// </returns> public static Task<ServerCommunicationLinkListResponse> ListAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName) { return operations.ListAsync(resourceGroupName, serverName, CancellationToken.None); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Vegvesen.Web.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections; using System.Globalization; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.CryptoPro; using Org.BouncyCastle.Asn1.Kisa; using Org.BouncyCastle.Asn1.Misc; using Org.BouncyCastle.Asn1.Nist; using Org.BouncyCastle.Asn1.Ntt; using Org.BouncyCastle.Asn1.Oiw; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Security { public sealed class ParameterUtilities { private ParameterUtilities() { } private static readonly Hashtable algorithms = new Hashtable(); static ParameterUtilities() { AddAlgorithm("AES", "AESWRAP"); AddAlgorithm("AES128", "2.16.840.1.101.3.4.2", NistObjectIdentifiers.IdAes128Cbc, NistObjectIdentifiers.IdAes128Cfb, NistObjectIdentifiers.IdAes128Ecb, NistObjectIdentifiers.IdAes128Ofb, NistObjectIdentifiers.IdAes128Wrap); AddAlgorithm("AES192", "2.16.840.1.101.3.4.22", NistObjectIdentifiers.IdAes192Cbc, NistObjectIdentifiers.IdAes192Cfb, NistObjectIdentifiers.IdAes192Ecb, NistObjectIdentifiers.IdAes192Ofb, NistObjectIdentifiers.IdAes192Wrap); AddAlgorithm("AES256", "2.16.840.1.101.3.4.42", NistObjectIdentifiers.IdAes256Cbc, NistObjectIdentifiers.IdAes256Cfb, NistObjectIdentifiers.IdAes256Ecb, NistObjectIdentifiers.IdAes256Ofb, NistObjectIdentifiers.IdAes256Wrap); AddAlgorithm("BLOWFISH", "1.3.6.1.4.1.3029.1.2"); AddAlgorithm("CAMELLIA", "CAMELLIAWRAP"); AddAlgorithm("CAMELLIA128", NttObjectIdentifiers.IdCamellia128Cbc, NttObjectIdentifiers.IdCamellia128Wrap); AddAlgorithm("CAMELLIA192", NttObjectIdentifiers.IdCamellia192Cbc, NttObjectIdentifiers.IdCamellia192Wrap); AddAlgorithm("CAMELLIA256", NttObjectIdentifiers.IdCamellia256Cbc, NttObjectIdentifiers.IdCamellia256Wrap); AddAlgorithm("CAST5", "1.2.840.113533.7.66.10"); AddAlgorithm("CAST6"); AddAlgorithm("DES", OiwObjectIdentifiers.DesCbc, OiwObjectIdentifiers.DesCfb, OiwObjectIdentifiers.DesEcb, OiwObjectIdentifiers.DesOfb); AddAlgorithm("DESEDE", "DESEDEWRAP", OiwObjectIdentifiers.DesEde, PkcsObjectIdentifiers.IdAlgCms3DesWrap); AddAlgorithm("DESEDE3", PkcsObjectIdentifiers.DesEde3Cbc); AddAlgorithm("GOST28147", "GOST", "GOST-28147", CryptoProObjectIdentifiers.GostR28147Cbc); AddAlgorithm("HC128"); AddAlgorithm("HC256"); AddAlgorithm("IDEA", "1.3.6.1.4.1.188.7.1.1.2"); AddAlgorithm("NOEKEON"); AddAlgorithm("RC2", PkcsObjectIdentifiers.RC2Cbc, PkcsObjectIdentifiers.IdAlgCmsRC2Wrap); AddAlgorithm("RC4", "ARC4", "1.2.840.113549.3.4"); AddAlgorithm("RC5", "RC5-32"); AddAlgorithm("RC5-64"); AddAlgorithm("RC6"); AddAlgorithm("RIJNDAEL"); AddAlgorithm("SALSA20"); AddAlgorithm("SEED", KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap, KisaObjectIdentifiers.IdSeedCbc); AddAlgorithm("SERPENT"); AddAlgorithm("SKIPJACK"); AddAlgorithm("TEA"); AddAlgorithm("TWOFISH"); AddAlgorithm("VMPC"); AddAlgorithm("VMPC-KSA3"); AddAlgorithm("XTEA"); } private static void AddAlgorithm( string canonicalName, params object[] aliases) { algorithms[canonicalName] = canonicalName; foreach (object alias in aliases) { algorithms[alias.ToString()] = canonicalName; } } public static string GetCanonicalAlgorithmName( string algorithm) { return (string) algorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)]; } public static KeyParameter CreateKeyParameter( DerObjectIdentifier algOid, byte[] keyBytes) { return CreateKeyParameter(algOid.Id, keyBytes, 0, keyBytes.Length); } public static KeyParameter CreateKeyParameter( string algorithm, byte[] keyBytes) { return CreateKeyParameter(algorithm, keyBytes, 0, keyBytes.Length); } public static KeyParameter CreateKeyParameter( DerObjectIdentifier algOid, byte[] keyBytes, int offset, int length) { return CreateKeyParameter(algOid.Id, keyBytes, offset, length); } public static KeyParameter CreateKeyParameter( string algorithm, byte[] keyBytes, int offset, int length) { if (algorithm == null) throw new ArgumentNullException("algorithm"); string canonical = GetCanonicalAlgorithmName(algorithm); if (canonical == null) throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised."); switch (canonical) { case "DES": return new DesParameters(keyBytes, offset, length); case "DESEDE": case "DESEDE3": return new DesEdeParameters(keyBytes, offset, length); case "RC2": return new RC2Parameters(keyBytes, offset, length); default: return new KeyParameter(keyBytes, offset, length); } } public static ICipherParameters GetCipherParameters( DerObjectIdentifier algOid, ICipherParameters key, Asn1Object asn1Params) { return GetCipherParameters(algOid.Id, key, asn1Params); } public static ICipherParameters GetCipherParameters( string algorithm, ICipherParameters key, Asn1Object asn1Params) { if (algorithm == null) throw new ArgumentNullException("algorithm"); string canonical = GetCanonicalAlgorithmName(algorithm); if (canonical == null) throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised."); byte[] iv = null; try { switch (canonical) { case "AES": case "AES128": case "AES192": case "AES256": case "BLOWFISH": case "CAMELLIA": case "CAMELLIA128": case "CAMELLIA192": case "CAMELLIA256": case "DES": case "DESEDE": case "DESEDE3": case "NOEKEON": case "RIJNDAEL": case "SEED": case "SKIPJACK": case "TWOFISH": iv = ((Asn1OctetString) asn1Params).GetOctets(); break; case "RC2": iv = RC2CbcParameter.GetInstance(asn1Params).GetIV(); break; case "IDEA": iv = IdeaCbcPar.GetInstance(asn1Params).GetIV(); break; case "CAST5": iv = Cast5CbcParameters.GetInstance(asn1Params).GetIV(); break; } } catch (Exception e) { throw new ArgumentException("Could not process ASN.1 parameters", e); } if (iv != null) { return new ParametersWithIV(key, iv); } throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised."); } public static Asn1Encodable GenerateParameters( DerObjectIdentifier algID, SecureRandom random) { return GenerateParameters(algID.Id, random); } public static Asn1Encodable GenerateParameters( string algorithm, SecureRandom random) { if (algorithm == null) throw new ArgumentNullException("algorithm"); string canonical = GetCanonicalAlgorithmName(algorithm); if (canonical == null) throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised."); switch (canonical) { // TODO These algorithms support an IV (see GetCipherParameters) // but JCE doesn't seem to provide an AlgorithmParametersGenerator for them // case "RIJNDAEL": // case "SKIPJACK": // case "TWOFISH": case "AES": case "AES128": case "AES192": case "AES256": return CreateIVOctetString(random, 16); case "BLOWFISH": return CreateIVOctetString(random, 8); case "CAMELLIA": case "CAMELLIA128": case "CAMELLIA192": case "CAMELLIA256": return CreateIVOctetString(random, 16); case "CAST5": return new Cast5CbcParameters(CreateIV(random, 8), 128); case "DES": case "DESEDE": case "DESEDE3": return CreateIVOctetString(random, 8); case "IDEA": return new IdeaCbcPar(CreateIV(random, 8)); case "NOEKEON": return CreateIVOctetString(random, 16); case "RC2": return new RC2CbcParameter(CreateIV(random, 8)); case "SEED": return CreateIVOctetString(random, 16); } throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised."); } private static Asn1OctetString CreateIVOctetString( SecureRandom random, int ivLength) { return new DerOctetString(CreateIV(random, ivLength)); } private static byte[] CreateIV( SecureRandom random, int ivLength) { byte[] iv = new byte[ivLength]; random.NextBytes(iv); return iv; } } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonClasses.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using UnityEngine; /// <summary>Class for constants. Defines photon-event-codes for PUN usage.</summary> internal class PunEvent { public const byte RPC = 200; public const byte SendSerialize = 201; public const byte Instantiation = 202; public const byte CloseConnection = 203; public const byte Destroy = 204; public const byte RemoveCachedRPCs = 205; public const byte SendSerializeReliable = 206; // TS: added this but it's not really needed anymore public const byte DestroyPlayer = 207; // TS: added to make others remove all GOs of a player public const byte AssignMaster = 208; // TS: added to assign someone master client (overriding the current) } /// <summary>Enum of "target" options for RPCs. These define which remote clients get your RPC call. </summary> /// \ingroup publicApi public enum PhotonTargets { All, Others, MasterClient, AllBuffered, OthersBuffered } //.MasterClientBuffered? .Server? /// <summary>Used to define the level of logging output created by the PUN classes. Either log errors, info (some more) or full.</summary> /// \ingroup publicApi public enum PhotonLogLevel { ErrorsOnly, Informational, Full } namespace Photon { /// <summary> /// This class adds the property photonView, while logging a warning when your game still uses the networkView. /// </summary> public class MonoBehaviour : UnityEngine.MonoBehaviour { public PhotonView photonView { get { return PhotonView.Get(this); } } new public PhotonView networkView { get { Debug.LogWarning("Why are you still using networkView? should be PhotonView?"); return PhotonView.Get(this); } } } } /// <summary> /// Container class for info about a particular message, RPC or update. /// </summary> /// \ingroup publicApi public class PhotonMessageInfo { private int timeInt; public PhotonPlayer sender; public PhotonView photonView; /// <summary> /// Initializes a new instance of the <see cref="PhotonMessageInfo"/> class. /// To create an empty messageinfo only! /// </summary> public PhotonMessageInfo() { this.sender = PhotonNetwork.player; this.timeInt = (int)(PhotonNetwork.time * 1000); this.photonView = null; } public PhotonMessageInfo(PhotonPlayer player, int timestamp, PhotonView view) { this.sender = player; this.timeInt = timestamp; this.photonView = view; } public double timestamp { get { return ((double)(uint)this.timeInt) / 1000.0f; } } public override string ToString() { return string.Format("[PhotonMessageInfo: player='{1}' timestamp={0}]", this.timestamp, this.sender); } } public class PBitStream { List<byte> streamBytes; private int currentByte; private int totalBits = 0; public int ByteCount { get { return BytesForBits(this.totalBits); } } public int BitCount { get { return this.totalBits; } private set { this.totalBits = value; } } public PBitStream() { this.streamBytes = new List<byte>(1); } public PBitStream(int bitCount) { this.streamBytes = new List<byte>(BytesForBits(bitCount)); } public PBitStream(IEnumerable<byte> bytes, int bitCount) { this.streamBytes = new List<byte>(bytes); this.BitCount = bitCount; } public static int BytesForBits(int bitCount) { if (bitCount <= 0) { return 0; } return ((bitCount - 1) / 8) + 1; } public void Add(bool val) { int bytePos = this.totalBits / 8; if (bytePos > this.streamBytes.Count-1 || totalBits == 0) { this.streamBytes.Add(0); } if (val) { int currentByteBit = 7 - (this.totalBits % 8); this.streamBytes[bytePos] |= (byte)(1 << currentByteBit); } this.totalBits++; } public byte[] ToBytes() { return streamBytes.ToArray(); } public int Position { get; set; } public bool GetNext() { if (this.Position > this.totalBits) { throw new Exception("End of PBitStream reached. Can't read more."); } return Get(this.Position++); } public bool Get(int bitIndex) { int byteIndex = bitIndex / 8; int bitInByIndex = 7 - (bitIndex % 8); return ((streamBytes[byteIndex] & (byte)(1 << bitInByIndex)) > 0); } public void Set(int bitIndex, bool value) { int byteIndex = bitIndex / 8; int bitInByIndex = 7 - (bitIndex % 8); this.streamBytes[byteIndex] |= (byte)(1 << bitInByIndex); } } /// <summary> /// This "container" class is used to carry your data as written by OnPhotonSerializeView. /// </summary> /// <seealso cref="PhotonNetworkingMessage"/> /// \ingroup publicApi public class PhotonStream { bool write = false; internal List<object> data; byte currentItem = 0; //Used to track the next item to receive. public PhotonStream(bool write, object[] incomingData) { this.write = write; if (incomingData == null) { this.data = new List<object>(); } else { this.data = new List<object>(incomingData); } } public bool isWriting { get { return this.write; } } public bool isReading { get { return !this.write; } } public int Count { get { return data.Count; } } public object ReceiveNext() { if (this.write) { Debug.LogError("Error: you cannot read this stream that you are writing!"); return null; } object obj = this.data[this.currentItem]; this.currentItem++; return obj; } public void SendNext(object obj) { if (!this.write) { Debug.LogError("Error: you cannot write/send to this stream that you are reading!"); return; } this.data.Add(obj); } public object[] ToArray() { return this.data.ToArray(); } public void Serialize(ref bool myBool) { if (this.write) { this.data.Add(myBool); } else { if (this.data.Count > currentItem) { myBool = (bool)data[currentItem]; this.currentItem++; } } } public void Serialize(ref int myInt) { if (write) { this.data.Add(myInt); } else { if (this.data.Count > currentItem) { myInt = (int)data[currentItem]; currentItem++; } } } public void Serialize(ref string value) { if (write) { this.data.Add(value); } else { if (this.data.Count > currentItem) { value = (string)data[currentItem]; currentItem++; } } } public void Serialize(ref char value) { if (write) { this.data.Add(value); } else { if (this.data.Count > currentItem) { value = (char)data[currentItem]; currentItem++; } } } public void Serialize(ref short value) { if (write) { this.data.Add(value); } else { if (this.data.Count > currentItem) { value = (short)data[currentItem]; currentItem++; } } } public void Serialize(ref float obj) { if (write) { this.data.Add(obj); } else { if (this.data.Count > currentItem) { obj = (float)data[currentItem]; currentItem++; } } } public void Serialize(ref PhotonPlayer obj) { if (write) { this.data.Add(obj); } else { if (this.data.Count > currentItem) { obj = (PhotonPlayer)data[currentItem]; currentItem++; } } } public void Serialize(ref Vector3 obj) { if (write) { this.data.Add(obj); } else { if (this.data.Count > currentItem) { obj = (Vector3)data[currentItem]; currentItem++; } } } public void Serialize(ref Vector2 obj) { if (write) { this.data.Add(obj); } else { if (this.data.Count > currentItem) { obj = (Vector2)data[currentItem]; currentItem++; } } } public void Serialize(ref Quaternion obj) { if (write) { this.data.Add(obj); } else { if (this.data.Count > currentItem) { obj = (Quaternion)data[currentItem]; currentItem++; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Screens; using osu.Framework.Threading; using osu.Game.Audio; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.Spectator; using osu.Game.Overlays.BeatmapListing.Panels; using osu.Game.Overlays.Settings; using osu.Game.Rulesets; using osu.Game.Screens.OnlinePlay.Match.Components; using osu.Game.Screens.Spectate; using osu.Game.Users; using osuTK; namespace osu.Game.Screens.Play { [Cached(typeof(IPreviewTrackOwner))] public class SoloSpectator : SpectatorScreen, IPreviewTrackOwner { [NotNull] private readonly User targetUser; [Resolved] private IAPIProvider api { get; set; } [Resolved] private PreviewTrackManager previewTrackManager { get; set; } [Resolved] private RulesetStore rulesets { get; set; } [Resolved] private BeatmapManager beatmaps { get; set; } private Container beatmapPanelContainer; private TriangleButton watchButton; private SettingsCheckbox automaticDownload; private BeatmapSetInfo onlineBeatmap; /// <summary> /// The player's immediate online gameplay state. /// This doesn't always reflect the gameplay state being watched. /// </summary> private GameplayState immediateGameplayState; private GetBeatmapSetRequest onlineBeatmapRequest; public SoloSpectator([NotNull] User targetUser) : base(targetUser.Id) { this.targetUser = targetUser; } [BackgroundDependencyLoader] private void load(OsuColour colours, OsuConfigManager config) { InternalChild = new Container { Masking = true, CornerRadius = 20, AutoSizeAxes = Axes.Both, AutoSizeDuration = 500, AutoSizeEasing = Easing.OutQuint, Anchor = Anchor.Centre, Origin = Anchor.Centre, Children = new Drawable[] { new Box { Colour = colours.GreySeafoamDark, RelativeSizeAxes = Axes.Both, }, new FillFlowContainer { Margin = new MarginPadding(20), AutoSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Anchor = Anchor.Centre, Origin = Anchor.Centre, Spacing = new Vector2(15), Children = new Drawable[] { new OsuSpriteText { Text = "Spectator Mode", Font = OsuFont.Default.With(size: 30), Anchor = Anchor.Centre, Origin = Anchor.Centre, }, new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Anchor = Anchor.Centre, Origin = Anchor.Centre, Spacing = new Vector2(15), Children = new Drawable[] { new UserGridPanel(targetUser) { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Height = 145, Width = 290, }, new SpriteIcon { Size = new Vector2(40), Icon = FontAwesome.Solid.ArrowRight, Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, }, beatmapPanelContainer = new Container { AutoSizeAxes = Axes.Both, Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, }, } }, automaticDownload = new SettingsCheckbox { LabelText = "Automatically download beatmaps", Current = config.GetBindable<bool>(OsuSetting.AutomaticallyDownloadWhenSpectating), Anchor = Anchor.Centre, Origin = Anchor.Centre, }, watchButton = new PurpleTriangleButton { Text = "Start Watching", Width = 250, Anchor = Anchor.Centre, Origin = Anchor.Centre, Action = () => scheduleStart(immediateGameplayState), Enabled = { Value = false } } } } } }; } protected override void LoadComplete() { base.LoadComplete(); automaticDownload.Current.BindValueChanged(_ => checkForAutomaticDownload()); } protected override void OnUserStateChanged(int userId, SpectatorState spectatorState) { clearDisplay(); showBeatmapPanel(spectatorState); } protected override void StartGameplay(int userId, GameplayState gameplayState) { immediateGameplayState = gameplayState; watchButton.Enabled.Value = true; scheduleStart(gameplayState); } protected override void EndGameplay(int userId) { scheduledStart?.Cancel(); immediateGameplayState = null; watchButton.Enabled.Value = false; clearDisplay(); } private void clearDisplay() { watchButton.Enabled.Value = false; onlineBeatmapRequest?.Cancel(); beatmapPanelContainer.Clear(); previewTrackManager.StopAnyPlaying(this); } private ScheduledDelegate scheduledStart; private void scheduleStart(GameplayState gameplayState) { // This function may be called multiple times in quick succession once the screen becomes current again. scheduledStart?.Cancel(); scheduledStart = Schedule(() => { if (this.IsCurrentScreen()) start(); else scheduleStart(gameplayState); }); void start() { Beatmap.Value = gameplayState.Beatmap; Ruleset.Value = gameplayState.Ruleset.RulesetInfo; this.Push(new SpectatorPlayerLoader(gameplayState.Score)); } } private void showBeatmapPanel(SpectatorState state) { Debug.Assert(state.BeatmapID != null); onlineBeatmapRequest = new GetBeatmapSetRequest(state.BeatmapID.Value, BeatmapSetLookupType.BeatmapId); onlineBeatmapRequest.Success += res => Schedule(() => { onlineBeatmap = res.ToBeatmapSet(rulesets); beatmapPanelContainer.Child = new GridBeatmapPanel(onlineBeatmap); checkForAutomaticDownload(); }); api.Queue(onlineBeatmapRequest); } private void checkForAutomaticDownload() { if (onlineBeatmap == null) return; if (!automaticDownload.Current.Value) return; if (beatmaps.IsAvailableLocally(onlineBeatmap)) return; beatmaps.Download(onlineBeatmap); } public override bool OnExiting(IScreen next) { previewTrackManager.StopAnyPlaying(this); return base.OnExiting(next); } } }
namespace Gu.State.Tests { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using NUnit.Framework; public static partial class ChangeTrackerTests { public static class ObservableCollectionOfInt { [TestCase(ReferenceHandling.Throw)] [TestCase(ReferenceHandling.Structural)] [TestCase(ReferenceHandling.References)] public static void CreateAndDispose(ReferenceHandling referenceHandling) { var source = new ObservableCollection<int>(); var propertyChanges = new List<string>(); var changes = new List<EventArgs>(); using (var tracker = Track.Changes(source, referenceHandling)) { tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName); tracker.Changed += (_, e) => changes.Add(e); Assert.AreEqual(0, tracker.Changes); CollectionAssert.IsEmpty(propertyChanges); CollectionAssert.IsEmpty(changes); source.Add(1); Assert.AreEqual(1, tracker.Changes); CollectionAssert.AreEqual(new[] { "Changes" }, propertyChanges); var node = ChangeTrackerNode.GetOrCreate((INotifyCollectionChanged)source, tracker.Settings, isRoot: false).Value; var expected = new[] { RootChangeEventArgs.Create(node, new AddEventArgs(source, 0)) }; CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default); source.Add(2); Assert.AreEqual(2, tracker.Changes); CollectionAssert.AreEqual(new[] { "Changes", "Changes" }, propertyChanges); expected = new[] { RootChangeEventArgs.Create(node, new AddEventArgs(source, 0)), RootChangeEventArgs.Create(node, new AddEventArgs(source, 1)), }; CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default); #pragma warning disable IDISP016 // Don't use disposed instance. tracker.Dispose(); #pragma warning restore IDISP016 // Don't use disposed instance. source.Add(3); Assert.AreEqual(2, tracker.Changes); CollectionAssert.AreEqual(new[] { "Changes", "Changes" }, propertyChanges); CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default); } source.Add(4); CollectionAssert.AreEqual(new[] { "Changes", "Changes" }, propertyChanges); } [TestCase(ReferenceHandling.Throw)] [TestCase(ReferenceHandling.Structural)] [TestCase(ReferenceHandling.References)] public static void Add(ReferenceHandling referenceHandling) { var source = new ObservableCollection<int>(); var propertyChanges = new List<string>(); var changes = new List<EventArgs>(); using var tracker = Track.Changes(source, referenceHandling); tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName); tracker.Changed += (_, e) => changes.Add(e); Assert.AreEqual(0, tracker.Changes); CollectionAssert.IsEmpty(propertyChanges); CollectionAssert.IsEmpty(changes); source.Add(1); Assert.AreEqual(1, tracker.Changes); CollectionAssert.AreEqual(new[] { "Changes" }, propertyChanges); var node = ChangeTrackerNode.GetOrCreate((INotifyCollectionChanged)source, tracker.Settings, isRoot: false).Value; var expected = new[] { RootChangeEventArgs.Create(node, new AddEventArgs(source, 0)) }; CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default); source.Add(2); Assert.AreEqual(2, tracker.Changes); CollectionAssert.AreEqual(new[] { "Changes", "Changes" }, propertyChanges); expected = new[] { RootChangeEventArgs.Create(node, new AddEventArgs(source, 0)), RootChangeEventArgs.Create(node, new AddEventArgs(source, 1)), }; CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default); } [TestCase(ReferenceHandling.Throw)] [TestCase(ReferenceHandling.Structural)] [TestCase(ReferenceHandling.References)] public static void Remove(ReferenceHandling referenceHandling) { var source = new ObservableCollection<int> { 1, 2 }; var propertyChanges = new List<string>(); var changes = new List<EventArgs>(); using var tracker = Track.Changes(source, referenceHandling); tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName); tracker.Changed += (_, e) => changes.Add(e); Assert.AreEqual(0, tracker.Changes); CollectionAssert.IsEmpty(propertyChanges); CollectionAssert.IsEmpty(changes); source.RemoveAt(1); Assert.AreEqual(1, tracker.Changes); CollectionAssert.AreEqual(new[] { "Changes" }, propertyChanges); var node = ChangeTrackerNode.GetOrCreate((INotifyCollectionChanged)source, tracker.Settings, isRoot: false).Value; var expected = new[] { RootChangeEventArgs.Create(node, new RemoveEventArgs(source, 1)) }; CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default); source.RemoveAt(0); Assert.AreEqual(2, tracker.Changes); CollectionAssert.AreEqual(new[] { "Changes", "Changes" }, propertyChanges); expected = new[] { RootChangeEventArgs.Create(node, new RemoveEventArgs(source, 1)), RootChangeEventArgs.Create(node, new RemoveEventArgs(source, 0)), }; CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default); } [TestCase(ReferenceHandling.Throw)] [TestCase(ReferenceHandling.Structural)] [TestCase(ReferenceHandling.References)] public static void Clear(ReferenceHandling referenceHandling) { var source = new ObservableCollection<int> { 1, 2 }; var propertyChanges = new List<string>(); var changes = new List<EventArgs>(); using var tracker = Track.Changes(source, referenceHandling); tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName); tracker.Changed += (_, e) => changes.Add(e); Assert.AreEqual(0, tracker.Changes); CollectionAssert.IsEmpty(propertyChanges); CollectionAssert.IsEmpty(changes); source.Clear(); Assert.AreEqual(1, tracker.Changes); CollectionAssert.AreEqual(new[] { "Changes" }, propertyChanges); var node = ChangeTrackerNode.GetOrCreate((INotifyCollectionChanged)source, tracker.Settings, isRoot: false).Value; var expected = new[] { RootChangeEventArgs.Create(node, new ResetEventArgs(source)) }; CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default); source.Clear(); Assert.AreEqual(2, tracker.Changes); CollectionAssert.AreEqual(new[] { "Changes", "Changes" }, propertyChanges); expected = new[] { RootChangeEventArgs.Create(node, new ResetEventArgs(source)), RootChangeEventArgs.Create(node, new ResetEventArgs(source)), }; CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default); } [TestCase(ReferenceHandling.Throw)] [TestCase(ReferenceHandling.Structural)] [TestCase(ReferenceHandling.References)] public static void Replace(ReferenceHandling referenceHandling) { var source = new ObservableCollection<int> { 1, 2 }; var propertyChanges = new List<string>(); var changes = new List<EventArgs>(); using var tracker = Track.Changes(source, referenceHandling); tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName); tracker.Changed += (_, e) => changes.Add(e); Assert.AreEqual(0, tracker.Changes); CollectionAssert.IsEmpty(propertyChanges); CollectionAssert.IsEmpty(changes); source[0] = 3; Assert.AreEqual(1, tracker.Changes); CollectionAssert.AreEqual(new[] { "Changes" }, propertyChanges); var node = ChangeTrackerNode.GetOrCreate((INotifyCollectionChanged)source, tracker.Settings, isRoot: false).Value; var expected = new[] { RootChangeEventArgs.Create(node, new ReplaceEventArgs(source, 0)) }; CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default); } [TestCase(ReferenceHandling.Throw)] [TestCase(ReferenceHandling.Structural)] [TestCase(ReferenceHandling.References)] public static void Move(ReferenceHandling referenceHandling) { var source = new ObservableCollection<int> { 1, 2 }; var propertyChanges = new List<string>(); var changes = new List<EventArgs>(); using var tracker = Track.Changes(source, referenceHandling); tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName); tracker.Changed += (_, e) => changes.Add(e); Assert.AreEqual(0, tracker.Changes); CollectionAssert.IsEmpty(propertyChanges); CollectionAssert.IsEmpty(changes); source.Move(1, 0); Assert.AreEqual(1, tracker.Changes); CollectionAssert.AreEqual(new[] { "Changes" }, propertyChanges); var node = ChangeTrackerNode.GetOrCreate((INotifyCollectionChanged)source, tracker.Settings, isRoot: false).Value; var expected = new[] { RootChangeEventArgs.Create(node, new MoveEventArgs(source, 1, 0)) }; CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default); } } } }
// 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.Globalization; using System.IO; using System.Text.Encodings.Web; using System.Text.Unicode; using Xunit; namespace Microsoft.Framework.WebEncoders { public partial class JavaScriptStringEncoderTests { [Fact] public void TestSurrogate_Relaxed() { Assert.Equal("\\uD83D\\uDCA9", JavaScriptEncoder.UnsafeRelaxedJsonEscaping.Encode("\U0001f4a9")); using var writer = new StringWriter(); JavaScriptEncoder.UnsafeRelaxedJsonEscaping.Encode(writer, "\U0001f4a9"); Assert.Equal("\\uD83D\\uDCA9", writer.GetStringBuilder().ToString()); } [Fact] public void Relaxed_EquivalentToAll_WithExceptions() { // Arrange JavaScriptStringEncoder controlEncoder = new JavaScriptStringEncoder(UnicodeRanges.All); JavaScriptStringEncoder testEncoder = JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping; // Act & assert for (int i = 0; i <= char.MaxValue; i++) { if (i == '"' || i == '&' || i == '<' || i == '>' || i == '+' || i == '\'' || i == '`') { string input = new string((char)i, 1); Assert.NotEqual(controlEncoder.JavaScriptStringEncode(input), testEncoder.JavaScriptStringEncode(input)); continue; } if (!IsSurrogateCodePoint(i)) { string input = new string((char)i, 1); Assert.Equal(controlEncoder.JavaScriptStringEncode(input), testEncoder.JavaScriptStringEncode(input)); } } } [Fact] public void JavaScriptStringEncode_Relaxed_StillEncodesForbiddenChars_Simple_Escaping() { // The following two calls could be simply InlineData to the Theory below // Unfortunately, the xUnit logger fails to escape the inputs when logging the test results, // and so the suite fails despite all tests passing. // TODO: I will try to fix it in xUnit, but for now this is a workaround to enable these tests. JavaScriptStringEncode_Relaxed_StillEncodesForbiddenChars_Simple("\b", @"\b"); JavaScriptStringEncode_Relaxed_StillEncodesForbiddenChars_Simple("\f", @"\f"); } [Theory] [InlineData("\"", "\\\"")] [InlineData("\\", @"\\")] [InlineData("\n", @"\n")] [InlineData("\t", @"\t")] [InlineData("\r", @"\r")] public void JavaScriptStringEncode_Relaxed_StillEncodesForbiddenChars_Simple(string input, string expected) { // Arrange JavaScriptStringEncoder encoder = JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping; // Act string retVal = encoder.JavaScriptStringEncode(input); // Assert Assert.Equal(expected, retVal); } [Fact] public void JavaScriptStringEncode_Relaxed_StillEncodesForbiddenChars_Extended() { // Arrange JavaScriptStringEncoder encoder = JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping; // Act & assert - BMP chars for (int i = 0; i <= 0xFFFF; i++) { string input = new string((char)i, 1); string expected; if (IsSurrogateCodePoint(i)) { expected = "\uFFFD"; // unpaired surrogate -> Unicode replacement char } else { if (input == "\b") { expected = @"\b"; } else if (input == "\t") { expected = @"\t"; } else if (input == "\n") { expected = @"\n"; } else if (input == "\f") { expected = @"\f"; } else if (input == "\r") { expected = @"\r"; } else if (input == "\\") { expected = @"\\"; } else if (input == "\"") { expected = "\\\""; } else { bool mustEncode = false; if (i <= 0x001F || (0x007F <= i && i <= 0x9F)) { mustEncode = true; // control char } else if (!UnicodeTestHelpers.IsCharacterDefined((char)i)) { mustEncode = true; // undefined (or otherwise disallowed) char } if (mustEncode) { expected = string.Format(CultureInfo.InvariantCulture, @"\u{0:X4}", i); } else { expected = input; // no encoding } } } string retVal = encoder.JavaScriptStringEncode(input); Assert.Equal(expected, retVal); } // Act & assert - astral chars for (int i = 0x10000; i <= 0x10FFFF; i++) { string input = char.ConvertFromUtf32(i); string expected = string.Format(CultureInfo.InvariantCulture, @"\u{0:X4}\u{1:X4}", (uint)input[0], (uint)input[1]); string retVal = encoder.JavaScriptStringEncode(input); Assert.Equal(expected, retVal); } } [Fact] public void JavaScriptStringEncode_BadSurrogates_ReturnsUnicodeReplacementChar_Relaxed() { // Arrange JavaScriptStringEncoder encoder = JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping; // allow all codepoints // "a<unpaired leading>b<unpaired trailing>c<trailing before leading>d<unpaired trailing><valid>e<high at end of string>" const string input = "a\uD800b\uDFFFc\uDFFF\uD800d\uDFFF\uD800\uDFFFe\uD800"; const string expected = "a\uFFFDb\uFFFDc\uFFFD\uFFFDd\uFFFD\\uD800\\uDFFFe\uFFFD"; // 'D800' 'DFFF' was preserved since it's valid // Act string retVal = encoder.JavaScriptStringEncode(input); // Assert Assert.Equal(expected, retVal); } [Fact] public void JavaScriptStringEncode_EmptyStringInput_ReturnsEmptyString_Relaxed() { // Arrange JavaScriptStringEncoder encoder = JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping; // Act & assert Assert.Equal("", encoder.JavaScriptStringEncode("")); } [Fact] public void JavaScriptStringEncode_InputDoesNotRequireEncoding_ReturnsOriginalStringInstance_Relaxed() { // Arrange JavaScriptStringEncoder encoder = JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping; string input = "Hello, there!"; // Act & assert Assert.Same(input, encoder.JavaScriptStringEncode(input)); } [Fact] public void JavaScriptStringEncode_NullInput_Throws_Relaxed() { // Arrange JavaScriptStringEncoder encoder = JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping; Assert.Throws<ArgumentNullException>(() => { encoder.JavaScriptStringEncode(null); }); } [Fact] public void JavaScriptStringEncode_WithCharsRequiringEncodingAtBeginning_Relaxed() { Assert.Equal(@"\\Hello, there!", JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping.JavaScriptStringEncode("\\Hello, there!")); } [Fact] public void JavaScriptStringEncode_WithCharsRequiringEncodingAtEnd_Relaxed() { Assert.Equal(@"Hello, there!\\", JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping.JavaScriptStringEncode("Hello, there!\\")); } [Fact] public void JavaScriptStringEncode_WithCharsRequiringEncodingInMiddle_Relaxed() { Assert.Equal(@"Hello, \\there!", JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping.JavaScriptStringEncode("Hello, \\there!")); } [Fact] public void JavaScriptStringEncode_WithCharsRequiringEncodingInterspersed_Relaxed() { Assert.Equal("Hello, \\\\there\\\"!", JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping.JavaScriptStringEncode("Hello, \\there\"!")); } [Fact] public void JavaScriptStringEncode_CharArray_Relaxed() { // Arrange JavaScriptStringEncoder encoder = JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping; using var output = new StringWriter(); // Act encoder.JavaScriptStringEncode("Hello\\world!".ToCharArray(), 3, 5, output); // Assert Assert.Equal(@"lo\\wo", output.ToString()); } [Fact] public void JavaScriptStringEncode_StringSubstring_Relaxed() { // Arrange JavaScriptStringEncoder encoder = JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping; using var output = new StringWriter(); // Act encoder.JavaScriptStringEncode("Hello\\world!", 3, 5, output); // Assert Assert.Equal(@"lo\\wo", output.ToString()); } [Theory] [InlineData("\"", "\\\"")] [InlineData("'", "'")] public void JavaScriptStringEncode_Quotes_Relaxed(string input, string expected) { // Arrange JavaScriptStringEncoder encoder = JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping; // Act string retVal = encoder.JavaScriptStringEncode(input); // Assert Assert.Equal(expected, retVal); } [Theory] [InlineData("hello+world", "hello+world")] [InlineData("hello<world>", "hello<world>")] [InlineData("hello&world", "hello&world")] public void JavaScriptStringEncode_DoesOutputHtmlSensitiveCharacters_Relaxed(string input, string expected) { // Arrange JavaScriptStringEncoder encoder = JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping; // Act string retVal = encoder.JavaScriptStringEncode(input); // Assert Assert.Equal(expected, retVal); } [Fact] public void JavaScriptStringEncode_AboveAscii_Relaxed() { // Arrange JavaScriptStringEncoder encoder = JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping; // Act & assert for (int i = 0x128; i <= 0xFFFF; i++) { if (IsSurrogateCodePoint(i)) { continue; // surrogates don't matter here } UnicodeCategory category = char.GetUnicodeCategory((char)i); if (category != UnicodeCategory.NonSpacingMark) { continue; // skip undefined characters like U+0378, or spacing characters like U+2028 } string javaScriptStringEncoded = encoder.JavaScriptStringEncode(char.ConvertFromUtf32(i)); Assert.True(char.ConvertFromUtf32(i) == javaScriptStringEncoded, i.ToString()); } } [Fact] public void JavaScriptStringEncode_ControlCharacters_Relaxed() { // Arrange JavaScriptStringEncoder encoder = JavaScriptStringEncoder.UnsafeRelaxedJsonEscaping; // Act & assert for (int i = 0; i <= 0x1F; i++) { // Skip characters that are escaped using '\\' since they are covered in other tests. if (i == '\b' || i == '\f' || i == '\n' || i == '\r' || i == '\t') { continue; } string javaScriptStringEncoded = encoder.JavaScriptStringEncode(char.ConvertFromUtf32(i)); string expected = string.Format("\\u00{0:X2}", i); Assert.Equal(expected, javaScriptStringEncoded); } } } }
// Copyright 2018 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.Tasks.Offline; using Esri.ArcGISRuntime.UI; using System; using System.Drawing; using System.IO; using System.Linq; using System.Threading.Tasks; using Windows.UI.Popups; using Windows.UI.Xaml; namespace ArcGISRuntime.UWP.Samples.ExportTiles { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Export tiles", category: "Layers", description: "Download tiles to a local tile cache file stored on the device.", instructions: "Pan and zoom into the desired area, making sure the area is within the red boundary. Click the 'Export tiles' button to start the process. On successful completion you will see a preview of the downloaded tile package.", tags: new[] { "cache", "download", "export", "local", "offline", "package", "tiles" })] public partial class ExportTiles { // URL to the service that tiles will be exported from. private Uri _serviceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer"); // Path to the tile package on disk. private string _tilePath; public ExportTiles() { InitializeComponent(); // Call a function to set up the map. Initialize(); } private async void Initialize() { // Create the tile layer. try { ArcGISTiledLayer myLayer = new ArcGISTiledLayer(_serviceUri); // Load the layer. await myLayer.LoadAsync(); // Create the basemap with the layer. Map myMap = new Map(new Basemap(myLayer)) { // Set the min and max scale - export task fails if the scale is too big or small. MaxScale = 5000000, MinScale = 10000000 }; // Assign the map to the mapview. MyMapView.Map = myMap; // Create a new symbol for the extent graphic. // This is the red box that visualizes the extent for which tiles will be exported. SimpleLineSymbol myExtentSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 2); // Create a graphics overlay for the extent graphic and apply a renderer. GraphicsOverlay extentOverlay = new GraphicsOverlay { Renderer = new SimpleRenderer(myExtentSymbol) }; // Add the graphics overlay to the map view. MyMapView.GraphicsOverlays.Add(extentOverlay); // Subscribe to changes in the mapview's viewpoint so the preview box can be kept in position. MyMapView.ViewpointChanged += MyMapView_ViewpointChanged; // Update the extent graphic so that it is valid before user interaction. UpdateMapExtentGraphic(); // Enable the export tile button once sample is ready. MyExportButton.IsEnabled = true; // Set viewpoint of the map. MyMapView.SetViewpoint(new Viewpoint(-4.853791, 140.983598, myMap.MinScale)); } catch (Exception ex) { ShowStatusMessage(ex.ToString()); } } private void MyMapView_ViewpointChanged(object sender, EventArgs e) { UpdateMapExtentGraphic(); } /// <summary> /// Function used to keep the overlaid preview area marker in position /// This is called by MyMapView_ViewpointChanged every time the user pans/zooms /// and updates the red box graphic to outline 80% of the current view /// </summary> private void UpdateMapExtentGraphic() { // Return if mapview is null. if (MyMapView == null) { return; } // Get the new viewpoint. Viewpoint myViewPoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry); // Return if viewpoint is null. if (myViewPoint == null) { return; } // Get the updated extent for the new viewpoint. Envelope extent = myViewPoint.TargetGeometry as Envelope; // Return if extent is null. if (extent == null) { return; } // Create an envelope that is a bit smaller than the extent. EnvelopeBuilder envelopeBldr = new EnvelopeBuilder(extent); envelopeBldr.Expand(0.80); // Get the (only) graphics overlay in the map view. GraphicsOverlay extentOverlay = MyMapView.GraphicsOverlays.FirstOrDefault(); // Return if the extent overlay is null. if (extentOverlay == null) { return; } // Get the extent graphic. Graphic extentGraphic = extentOverlay.Graphics.FirstOrDefault(); // Create the extent graphic and add it to the overlay if it doesn't exist. if (extentGraphic == null) { extentGraphic = new Graphic(envelopeBldr.ToGeometry()); extentOverlay.Graphics.Add(extentGraphic); } else { // Otherwise, update the graphic's geometry. extentGraphic.Geometry = envelopeBldr.ToGeometry(); } } private async Task StartExport() { // Get the parameters for the job. ExportTileCacheParameters parameters = GetExportParameters(); // Create the task. ExportTileCacheTask exportTask = await ExportTileCacheTask.CreateAsync(_serviceUri); // Get the tile cache path. _tilePath = $"{Path.GetTempFileName()}.tpk"; // Create the export job. ExportTileCacheJob job = exportTask.ExportTileCache(parameters, _tilePath); // Start the export job. job.Start(); // Get the result. TileCache cache = await job.GetResultAsync(); // Do the rest of the work. await HandleExportComplete(job, cache); } private async Task HandleExportComplete(ExportTileCacheJob job, TileCache cache) { // Update the view if the job is complete. if (job.Status == Esri.ArcGISRuntime.Tasks.JobStatus.Succeeded) { // Show the exported tiles on the preview map. await UpdatePreviewMap(cache); // Show the preview window. MyPreviewMapView.Visibility = Visibility.Visible; // Show the 'close preview' button. MyClosePreviewButton.Visibility = Visibility.Visible; // Hide the 'export tiles' button. MyExportButton.Visibility = Visibility.Collapsed; // Hide the progress bar. MyProgressBar.Visibility = Visibility.Collapsed; // Enable the 'export tiles' button. MyExportButton.IsEnabled = true; } else if (job.Status == Esri.ArcGISRuntime.Tasks.JobStatus.Failed) { // Notify the user. ShowStatusMessage("Job failed"); // Hide the progress bar. MyProgressBar.Visibility = Visibility.Collapsed; } } private ExportTileCacheParameters GetExportParameters() { // Create a new parameters instance. ExportTileCacheParameters parameters = new ExportTileCacheParameters(); // Get the (only) graphics overlay in the map view. GraphicsOverlay extentOverlay = MyMapView.GraphicsOverlays.First(); // Get the area selection graphic's extent. Graphic extentGraphic = extentOverlay.Graphics.First(); // Set the area for the export. parameters.AreaOfInterest = extentGraphic.Geometry; // Set the highest possible export quality. parameters.CompressionQuality = 100; // Add level IDs 1-9. // Note: Failing to add at least one Level ID will result in job failure. for (int x = 1; x < 10; x++) { parameters.LevelIds.Add(x); } // Return the parameters. return parameters; } private async Task UpdatePreviewMap(TileCache cache) { // Load the cache. await cache.LoadAsync(); // Create a tile layer with the cache. ArcGISTiledLayer myLayer = new ArcGISTiledLayer(cache); // Apply the map to the preview mapview. MyPreviewMapView.Map = new Map(new Basemap(myLayer)); } private async void MyExportButton_Click(object sender, RoutedEventArgs e) { try { MyExportButton.IsEnabled = false; // Show the progress bar. MyProgressBar.Visibility = Visibility.Visible; // Hide the preview window if not already hidden. MyPreviewMapView.Visibility = Visibility.Collapsed; // Hide the 'close preview' button if not already hidden. MyClosePreviewButton.Visibility = Visibility.Collapsed; // Show the 'export tiles' button. MyExportButton.Visibility = Visibility.Visible; // Start the export. await StartExport(); } catch (Exception ex) { ShowStatusMessage(ex.ToString()); } } private async void ShowStatusMessage(string message) { // Display the message to the user. await new MessageDialog(message).ShowAsync(); } private void ClosePreview_Click(object sender, RoutedEventArgs e) { // Hide the preview map. MyPreviewMapView.Visibility = Visibility.Collapsed; // Hide the 'close preview' button. MyClosePreviewButton.Visibility = Visibility.Collapsed; // Show the 'export tiles' button. MyExportButton.Visibility = Visibility.Visible; } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; #if WCF_SUPPORTED using System.ServiceModel; using System.ServiceModel.Channels; #endif using System.Threading; #if SILVERLIGHT using System.Windows; using System.Windows.Threading; #endif using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; using NLog.LogReceiverService; /// <summary> /// Sends log messages to a NLog Receiver Service (using WCF or Web Services). /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/LogReceiverService-target">Documentation on NLog Wiki</seealso> [Target("LogReceiverService")] public class LogReceiverWebServiceTarget : Target { private LogEventInfoBuffer buffer = new LogEventInfoBuffer(10000, false, 10000); private bool inCall; /// <summary> /// Initializes a new instance of the <see cref="LogReceiverWebServiceTarget"/> class. /// </summary> public LogReceiverWebServiceTarget() { this.Parameters = new List<MethodCallParameter>(); } /// <summary> /// Gets or sets the endpoint address. /// </summary> /// <value>The endpoint address.</value> /// <docgen category='Connection Options' order='10' /> [RequiredParameter] public virtual string EndpointAddress { get; set; } #if WCF_SUPPORTED /// <summary> /// Gets or sets the name of the endpoint configuration in WCF configuration file. /// </summary> /// <value>The name of the endpoint configuration.</value> /// <docgen category='Connection Options' order='10' /> public string EndpointConfigurationName { get; set; } /// <summary> /// Gets or sets a value indicating whether to use binary message encoding. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool UseBinaryEncoding { get; set; } /// <summary> /// Gets or sets a value indicating whether to use a WCF service contract that is one way (fire and forget) or two way (request-reply) /// </summary> /// <docgen category='Connection Options' order='10' /> public bool UseOneWayContract { get; set; } #endif /// <summary> /// Gets or sets the client ID. /// </summary> /// <value>The client ID.</value> /// <docgen category='Payload Options' order='10' /> public Layout ClientId { get; set; } /// <summary> /// Gets the list of parameters. /// </summary> /// <value>The parameters.</value> /// <docgen category='Payload Options' order='10' /> [ArrayParameter(typeof(MethodCallParameter), "parameter")] public IList<MethodCallParameter> Parameters { get; private set; } /// <summary> /// Gets or sets a value indicating whether to include per-event properties in the payload sent to the server. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeEventProperties { get; set; } /// <summary> /// Called when log events are being sent (test hook). /// </summary> /// <param name="events">The events.</param> /// <param name="asyncContinuations">The async continuations.</param> /// <returns>True if events should be sent, false to stop processing them.</returns> protected internal virtual bool OnSend(NLogEvents events, IEnumerable<AsyncLogEventInfo> asyncContinuations) { return true; } /// <summary> /// Writes logging event to the log target. Must be overridden in inheriting /// classes. /// </summary> /// <param name="logEvent">Logging event to be written out.</param> protected override void Write(AsyncLogEventInfo logEvent) { this.Write(new[] { logEvent }); } /// <summary> /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Append" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected override void Write(AsyncLogEventInfo[] logEvents) { // if web service call is being processed, buffer new events and return // lock is being held here if (this.inCall) { foreach (var ev in logEvents) { this.buffer.Append(ev); } return; } var networkLogEvents = this.TranslateLogEvents(logEvents); this.Send(networkLogEvents, logEvents); } /// <summary> /// Flush any pending log messages asynchronously (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { this.SendBufferedEvents(); asyncContinuation(null); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } asyncContinuation(exception); } } private static int AddValueAndGetStringOrdinal(NLogEvents context, Dictionary<string, int> stringTable, string value) { int stringIndex; if (!stringTable.TryGetValue(value, out stringIndex)) { stringIndex = context.Strings.Count; stringTable.Add(value, stringIndex); context.Strings.Add(value); } return stringIndex; } private NLogEvents TranslateLogEvents(AsyncLogEventInfo[] logEvents) { if (logEvents.Length == 0 && !LogManager.ThrowExceptions) { InternalLogger.Error("LogEvents array is empty, sending empty event..."); return new NLogEvents(); } string clientID = string.Empty; if (this.ClientId != null) { clientID = this.ClientId.Render(logEvents[0].LogEvent); } var networkLogEvents = new NLogEvents { ClientName = clientID, LayoutNames = new StringCollection(), Strings = new StringCollection(), BaseTimeUtc = logEvents[0].LogEvent.TimeStamp.ToUniversalTime().Ticks }; var stringTable = new Dictionary<string, int>(); for (int i = 0; i < this.Parameters.Count; ++i) { networkLogEvents.LayoutNames.Add(this.Parameters[i].Name); } if (this.IncludeEventProperties) { for (int i = 0; i < logEvents.Length; ++i) { var ev = logEvents[i].LogEvent; // add all event-level property names in 'LayoutNames' collection. foreach (var prop in ev.Properties) { string propName = prop.Key as string; if (propName != null) { if (!networkLogEvents.LayoutNames.Contains(propName)) { networkLogEvents.LayoutNames.Add(propName); } } } } } networkLogEvents.Events = new NLogEvent[logEvents.Length]; for (int i = 0; i < logEvents.Length; ++i) { networkLogEvents.Events[i] = this.TranslateEvent(logEvents[i].LogEvent, networkLogEvents, stringTable); } return networkLogEvents; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Client is disposed asynchronously.")] private void Send(NLogEvents events, IEnumerable<AsyncLogEventInfo> asyncContinuations) { if (!this.OnSend(events, asyncContinuations)) { return; } #if WCF_SUPPORTED var client = CreateWcfLogReceiverClient(); client.ProcessLogMessagesCompleted += (sender, e) => { // report error to the callers foreach (var ev in asyncContinuations) { ev.Continuation(e.Error); } // send any buffered events this.SendBufferedEvents(); }; this.inCall = true; #if SILVERLIGHT if (!Deployment.Current.Dispatcher.CheckAccess()) { Deployment.Current.Dispatcher.BeginInvoke(() => client.ProcessLogMessagesAsync(events)); } else { client.ProcessLogMessagesAsync(events); } #else client.ProcessLogMessagesAsync(events); #endif #else var client = new SoapLogReceiverClient(this.EndpointAddress); this.inCall = true; client.BeginProcessLogMessages( events, result => { Exception exception = null; try { client.EndProcessLogMessages(result); } catch (Exception ex) { if (ex.MustBeRethrown()) { throw; } exception = ex; } // report error to the callers foreach (var ev in asyncContinuations) { ev.Continuation(exception); } // send any buffered events this.SendBufferedEvents(); }, null); #endif } #if WCF_SUPPORTED /// <summary> /// Creating a new instance of WcfLogReceiverClient /// /// Inheritors can override this method and provide their own /// service configuration - binding and endpoint address /// </summary> /// <returns></returns> protected virtual WcfLogReceiverClientFacade CreateWcfLogReceiverClient() { WcfLogReceiverClientFacade client; if (string.IsNullOrEmpty(this.EndpointConfigurationName)) { // endpoint not specified - use BasicHttpBinding Binding binding; if (this.UseBinaryEncoding) { binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement()); } else { binding = new BasicHttpBinding(); } client = new WcfLogReceiverClientFacade(UseOneWayContract, binding, new EndpointAddress(this.EndpointAddress)); } else { client = new WcfLogReceiverClientFacade(UseOneWayContract, this.EndpointConfigurationName, new EndpointAddress(this.EndpointAddress)); } client.ProcessLogMessagesCompleted += ClientOnProcessLogMessagesCompleted; return client; } private void ClientOnProcessLogMessagesCompleted(object sender, AsyncCompletedEventArgs asyncCompletedEventArgs) { var client = sender as WcfLogReceiverClientFacade; if (client != null && client.State == CommunicationState.Opened) { client.CloseCommunicationObject(); } } #endif private void SendBufferedEvents() { lock (this.SyncRoot) { // clear inCall flag AsyncLogEventInfo[] bufferedEvents = this.buffer.GetEventsAndClear(); if (bufferedEvents.Length > 0) { var networkLogEvents = this.TranslateLogEvents(bufferedEvents); this.Send(networkLogEvents, bufferedEvents); } else { // nothing in the buffer, clear in-call flag this.inCall = false; } } } private NLogEvent TranslateEvent(LogEventInfo eventInfo, NLogEvents context, Dictionary<string, int> stringTable) { var nlogEvent = new NLogEvent(); nlogEvent.Id = eventInfo.SequenceID; nlogEvent.MessageOrdinal = AddValueAndGetStringOrdinal(context, stringTable, eventInfo.FormattedMessage); nlogEvent.LevelOrdinal = eventInfo.Level.Ordinal; nlogEvent.LoggerOrdinal = AddValueAndGetStringOrdinal(context, stringTable, eventInfo.LoggerName); nlogEvent.TimeDelta = eventInfo.TimeStamp.ToUniversalTime().Ticks - context.BaseTimeUtc; for (int i = 0; i < this.Parameters.Count; ++i) { var param = this.Parameters[i]; var value = param.Layout.Render(eventInfo); int stringIndex = AddValueAndGetStringOrdinal(context, stringTable, value); nlogEvent.ValueIndexes.Add(stringIndex); } // layout names beyond Parameters.Count are per-event property names. for (int i = this.Parameters.Count; i < context.LayoutNames.Count; ++i) { string value; object propertyValue; if (eventInfo.Properties.TryGetValue(context.LayoutNames[i], out propertyValue)) { value = Convert.ToString(propertyValue, CultureInfo.InvariantCulture); } else { value = string.Empty; } int stringIndex = AddValueAndGetStringOrdinal(context, stringTable, value); nlogEvent.ValueIndexes.Add(stringIndex); } if (eventInfo.Exception != null) { nlogEvent.ValueIndexes.Add(AddValueAndGetStringOrdinal(context, stringTable, eventInfo.Exception.ToString())); } return nlogEvent; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // This file contains the primary interface and management of tasks and queues. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Threading.Tasks { /// <summary> /// Represents an abstract scheduler for tasks. /// </summary> /// <remarks> /// <para> /// <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> acts as the extension point for all /// pluggable scheduling logic. This includes mechanisms such as how to schedule a task for execution, and /// how scheduled tasks should be exposed to debuggers. /// </para> /// <para> /// All members of the abstract <see cref="TaskScheduler"/> type are thread-safe /// and may be used from multiple threads concurrently. /// </para> /// </remarks> [DebuggerDisplay("Id={Id}")] [DebuggerTypeProxy(typeof(SystemThreadingTasks_TaskSchedulerDebugView))] public abstract class TaskScheduler { //////////////////////////////////////////////////////////// // // User Provided Methods and Properties // /// <summary> /// Queues a <see cref="T:System.Threading.Tasks.Task">Task</see> to the scheduler. /// </summary> /// <remarks> /// <para> /// A class derived from <see cref="T:System.Threading.Tasks.TaskScheduler">TaskScheduler</see> /// implements this method to accept tasks being scheduled on the scheduler. /// A typical implementation would store the task in an internal data structure, which would /// be serviced by threads that would execute those tasks at some time in the future. /// </para> /// <para> /// This method is only meant to be called by the .NET Framework and /// should not be called directly by the derived class. This is necessary /// for maintaining the consistency of the system. /// </para> /// </remarks> /// <param name="task">The <see cref="T:System.Threading.Tasks.Task">Task</see> to be queued.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="task"/> argument is null.</exception> protected internal abstract void QueueTask(Task task); /// <summary> /// Determines whether the provided <see cref="T:System.Threading.Tasks.Task">Task</see> /// can be executed synchronously in this call, and if it can, executes it. /// </summary> /// <remarks> /// <para> /// A class derived from <see cref="TaskScheduler">TaskScheduler</see> implements this function to /// support inline execution of a task on a thread that initiates a wait on that task object. Inline /// execution is optional, and the request may be rejected by returning false. However, better /// scalability typically results the more tasks that can be inlined, and in fact a scheduler that /// inlines too little may be prone to deadlocks. A proper implementation should ensure that a /// request executing under the policies guaranteed by the scheduler can successfully inline. For /// example, if a scheduler uses a dedicated thread to execute tasks, any inlining requests from that /// thread should succeed. /// </para> /// <para> /// If a scheduler decides to perform the inline execution, it should do so by calling to the base /// TaskScheduler's /// <see cref="TryExecuteTask">TryExecuteTask</see> method with the provided task object, propagating /// the return value. It may also be appropriate for the scheduler to remove an inlined task from its /// internal data structures if it decides to honor the inlining request. Note, however, that under /// some circumstances a scheduler may be asked to inline a task that was not previously provided to /// it with the <see cref="QueueTask"/> method. /// </para> /// <para> /// The derived scheduler is responsible for making sure that the calling thread is suitable for /// executing the given task as far as its own scheduling and execution policies are concerned. /// </para> /// </remarks> /// <param name="task">The <see cref="T:System.Threading.Tasks.Task">Task</see> to be /// executed.</param> /// <param name="taskWasPreviouslyQueued">A Boolean denoting whether or not task has previously been /// queued. If this parameter is True, then the task may have been previously queued (scheduled); if /// False, then the task is known not to have been queued, and this call is being made in order to /// execute the task inline without queueing it.</param> /// <returns>A Boolean value indicating whether the task was executed inline.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="task"/> argument is /// null.</exception> /// <exception cref="T:System.InvalidOperationException">The <paramref name="task"/> was already /// executed.</exception> protected abstract bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued); /// <summary> /// Generates an enumerable of <see cref="T:System.Threading.Tasks.Task">Task</see> instances /// currently queued to the scheduler waiting to be executed. /// </summary> /// <remarks> /// <para> /// A class derived from <see cref="TaskScheduler"/> implements this method in order to support /// integration with debuggers. This method will only be invoked by the .NET Framework when the /// debugger requests access to the data. The enumerable returned will be traversed by debugging /// utilities to access the tasks currently queued to this scheduler, enabling the debugger to /// provide a representation of this information in the user interface. /// </para> /// <para> /// It is important to note that, when this method is called, all other threads in the process will /// be frozen. Therefore, it's important to avoid synchronization with other threads that may lead to /// blocking. If synchronization is necessary, the method should prefer to throw a <see /// cref="System.NotSupportedException"/> /// than to block, which could cause a debugger to experience delays. Additionally, this method and /// the enumerable returned must not modify any globally visible state. /// </para> /// <para> /// The returned enumerable should never be null. If there are currently no queued tasks, an empty /// enumerable should be returned instead. /// </para> /// <para> /// For developers implementing a custom debugger, this method shouldn't be called directly, but /// rather this functionality should be accessed through the internal wrapper method /// GetScheduledTasksForDebugger: /// <c>internal Task[] GetScheduledTasksForDebugger()</c>. This method returns an array of tasks, /// rather than an enumerable. In order to retrieve a list of active schedulers, a debugger may use /// another internal method: <c>internal static TaskScheduler[] GetTaskSchedulersForDebugger()</c>. /// This static method returns an array of all active TaskScheduler instances. /// GetScheduledTasksForDebugger then may be used on each of these scheduler instances to retrieve /// the list of scheduled tasks for each. /// </para> /// </remarks> /// <returns>An enumerable that allows traversal of tasks currently queued to this scheduler. /// </returns> /// <exception cref="T:System.NotSupportedException"> /// This scheduler is unable to generate a list of queued tasks at this time. /// </exception> protected abstract IEnumerable<Task> GetScheduledTasks(); /// <summary> /// Indicates the maximum concurrency level this /// <see cref="TaskScheduler"/> is able to support. /// </summary> public virtual Int32 MaximumConcurrencyLevel { get { return Int32.MaxValue; } } //////////////////////////////////////////////////////////// // // Internal overridable methods // /// <summary> /// Attempts to execute the target task synchronously. /// </summary> /// <param name="task">The task to run.</param> /// <param name="taskWasPreviouslyQueued">True if the task may have been previously queued, /// false if the task was absolutely not previously queued.</param> /// <returns>True if it ran, false otherwise.</returns> internal bool TryRunInline(Task task, bool taskWasPreviouslyQueued) { // Do not inline unstarted tasks (i.e., task.ExecutingTaskScheduler == null). // Do not inline TaskCompletionSource-style (a.k.a. "promise") tasks. // No need to attempt inlining if the task body was already run (i.e. either TASK_STATE_DELEGATE_INVOKED or TASK_STATE_CANCELED bits set) TaskScheduler ets = task.ExecutingTaskScheduler; // Delegate cross-scheduler inlining requests to target scheduler if (ets != this && ets != null) return ets.TryRunInline(task, taskWasPreviouslyQueued); StackGuard currentStackGuard; if ((ets == null) || (task.m_action == null) || task.IsDelegateInvoked || task.IsCanceled || (currentStackGuard = Task.CurrentStackGuard).TryBeginInliningScope() == false) { return false; } // Task class will still call into TaskScheduler.TryRunInline rather than TryExecuteTaskInline() so that // 1) we can adjust the return code from TryExecuteTaskInline in case a buggy custom scheduler lies to us // 2) we maintain a mechanism for the TLS lookup optimization that we used to have for the ConcRT scheduler (will potentially introduce the same for TP) bool bInlined = false; try { bInlined = TryExecuteTaskInline(task, taskWasPreviouslyQueued); } finally { currentStackGuard.EndInliningScope(); } // If the custom scheduler returned true, we should either have the TASK_STATE_DELEGATE_INVOKED or TASK_STATE_CANCELED bit set // Otherwise the scheduler is buggy if (bInlined && !(task.IsDelegateInvoked || task.IsCanceled)) { throw new InvalidOperationException(SR.TaskScheduler_InconsistentStateAfterTryExecuteTaskInline); } return bInlined; } /// <summary> /// Attempts to dequeue a <see cref="T:System.Threading.Tasks.Task">Task</see> that was previously queued to /// this scheduler. /// </summary> /// <param name="task">The <see cref="T:System.Threading.Tasks.Task">Task</see> to be dequeued.</param> /// <returns>A Boolean denoting whether the <paramref name="task"/> argument was successfully dequeued.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="task"/> argument is null.</exception> protected internal virtual bool TryDequeue(Task task) { return false; } /// <summary> /// Notifies the scheduler that a work item has made progress. /// </summary> internal virtual void NotifyWorkItemProgress() { } /// <summary> /// Indicates whether this is a custom scheduler, in which case the safe code paths will be taken upon task entry /// using a CAS to transition from queued state to executing. /// </summary> internal virtual bool RequiresAtomicStartTransition { get { return true; } } //////////////////////////////////////////////////////////// // // Member variables // // The global container that keeps track of TaskScheduler instances for debugging purposes. private static ConditionalWeakTable<TaskScheduler, object> s_activeTaskSchedulers; // An AppDomain-wide default manager. private static readonly TaskScheduler s_defaultTaskScheduler = new ThreadPoolTaskScheduler(); //static counter used to generate unique TaskScheduler IDs internal static int s_taskSchedulerIdCounter; // this TaskScheduler's unique ID private volatile int m_taskSchedulerId; //////////////////////////////////////////////////////////// // // Constructors and public properties // /// <summary> /// Initializes the <see cref="System.Threading.Tasks.TaskScheduler"/>. /// </summary> protected TaskScheduler() { #if false // Debugger support // Register the scheduler in the active scheduler list. This is only relevant when debugging, // so we only pay the cost if the debugger is attached when the scheduler is created. This // means that the internal TaskScheduler.GetTaskSchedulersForDebugger() will only include // schedulers created while the debugger is attached. if (Debugger.IsAttached) { AddToActiveTaskSchedulers(); } #endif } /// <summary>Adds this scheduler ot the active schedulers tracking collection for debugging purposes.</summary> private void AddToActiveTaskSchedulers() { ConditionalWeakTable<TaskScheduler, object> activeTaskSchedulers = s_activeTaskSchedulers; if (activeTaskSchedulers == null) { Interlocked.CompareExchange(ref s_activeTaskSchedulers, new ConditionalWeakTable<TaskScheduler, object>(), null); activeTaskSchedulers = s_activeTaskSchedulers; } activeTaskSchedulers.Add(this, null); } /// <summary> /// Gets the default <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> instance. /// </summary> public static TaskScheduler Default { get { return s_defaultTaskScheduler; } } /// <summary> /// Gets the <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> /// associated with the currently executing task. /// </summary> /// <remarks> /// When not called from within a task, <see cref="Current"/> will return the <see cref="Default"/> scheduler. /// </remarks> public static TaskScheduler Current { get { TaskScheduler current = InternalCurrent; return current ?? TaskScheduler.Default; } } /// <summary> /// Gets the <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> /// associated with the currently executing task. /// </summary> /// <remarks> /// When not called from within a task, <see cref="InternalCurrent"/> will return null. /// </remarks> internal static TaskScheduler InternalCurrent { get { Task currentTask = Task.InternalCurrent; return ((currentTask != null) && ((currentTask.CreationOptions & TaskCreationOptions.HideScheduler) == 0) ) ? currentTask.ExecutingTaskScheduler : null; } } /// <summary> /// Creates a <see cref="TaskScheduler"/> /// associated with the current <see cref="T:System.Threading.SynchronizationContext"/>. /// </summary> /// <remarks> /// All <see cref="System.Threading.Tasks.Task">Task</see> instances queued to /// the returned scheduler will be executed through a call to the /// <see cref="System.Threading.SynchronizationContext.Post">Post</see> method /// on that context. /// </remarks> /// <returns> /// A <see cref="TaskScheduler"/> associated with /// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see>, as /// determined by <see cref="System.Threading.SynchronizationContext.Current">SynchronizationContext.Current</see>. /// </returns> /// <exception cref="T:System.InvalidOperationException"> /// The current SynchronizationContext may not be used as a TaskScheduler. /// </exception> public static TaskScheduler FromCurrentSynchronizationContext() { return new SynchronizationContextTaskScheduler(); } /// <summary> /// Gets the unique ID for this <see cref="TaskScheduler"/>. /// </summary> public Int32 Id { get { if (m_taskSchedulerId == 0) { int newId = 0; // We need to repeat if Interlocked.Increment wraps around and returns 0. // Otherwise next time this scheduler's Id is queried it will get a new value do { newId = Interlocked.Increment(ref s_taskSchedulerIdCounter); } while (newId == 0); Interlocked.CompareExchange(ref m_taskSchedulerId, newId, 0); } return m_taskSchedulerId; } } /// <summary> /// Attempts to execute the provided <see cref="T:System.Threading.Tasks.Task">Task</see> /// on this scheduler. /// </summary> /// <remarks> /// <para> /// Scheduler implementations are provided with <see cref="T:System.Threading.Tasks.Task">Task</see> /// instances to be executed through either the <see cref="QueueTask"/> method or the /// <see cref="TryExecuteTaskInline"/> method. When the scheduler deems it appropriate to run the /// provided task, <see cref="TryExecuteTask"/> should be used to do so. TryExecuteTask handles all /// aspects of executing a task, including action invocation, exception handling, state management, /// and lifecycle control. /// </para> /// <para> /// <see cref="TryExecuteTask"/> must only be used for tasks provided to this scheduler by the .NET /// Framework infrastructure. It should not be used to execute arbitrary tasks obtained through /// custom mechanisms. /// </para> /// </remarks> /// <param name="task"> /// A <see cref="T:System.Threading.Tasks.Task">Task</see> object to be executed.</param> /// <exception cref="T:System.InvalidOperationException"> /// The <paramref name="task"/> is not associated with this scheduler. /// </exception> /// <returns>A Boolean that is true if <paramref name="task"/> was successfully executed, false if it /// was not. A common reason for execution failure is that the task had previously been executed or /// is in the process of being executed by another thread.</returns> protected bool TryExecuteTask(Task task) { if (task.ExecutingTaskScheduler != this) { throw new InvalidOperationException(SR.TaskScheduler_ExecuteTask_WrongTaskScheduler); } return task.ExecuteEntry(true); } //////////////////////////////////////////////////////////// // // Events // private static EventHandler<UnobservedTaskExceptionEventArgs> _unobservedTaskException; private static readonly Lock _unobservedTaskExceptionLockObject = new Lock(); /// <summary> /// Occurs when a faulted <see cref="System.Threading.Tasks.Task"/>'s unobserved exception is about to trigger exception escalation /// policy, which, by default, would terminate the process. /// </summary> /// <remarks> /// This AppDomain-wide event provides a mechanism to prevent exception /// escalation policy (which, by default, terminates the process) from triggering. /// Each handler is passed a <see cref="T:System.Threading.Tasks.UnobservedTaskExceptionEventArgs"/> /// instance, which may be used to examine the exception and to mark it as observed. /// </remarks> public static event EventHandler<UnobservedTaskExceptionEventArgs> UnobservedTaskException { add { if (value != null) { using (LockHolder.Hold(_unobservedTaskExceptionLockObject)) { _unobservedTaskException += value; } } } remove { using (LockHolder.Hold(_unobservedTaskExceptionLockObject)) { _unobservedTaskException -= value; } } } //////////////////////////////////////////////////////////// // // Internal methods // // This is called by the TaskExceptionHolder finalizer. internal static void PublishUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs ueea) { // Lock this logic to prevent just-unregistered handlers from being called. using (LockHolder.Hold(_unobservedTaskExceptionLockObject)) { // Since we are under lock, it is technically no longer necessary // to make a copy. It is done here for convenience. EventHandler<UnobservedTaskExceptionEventArgs> handler = _unobservedTaskException; if (handler != null) { handler(sender, ueea); } } } /// <summary> /// Provides an array of all queued <see cref="System.Threading.Tasks.Task">Task</see> instances /// for the debugger. /// </summary> /// <remarks> /// The returned array is populated through a call to <see cref="GetScheduledTasks"/>. /// Note that this function is only meant to be invoked by a debugger remotely. /// It should not be called by any other codepaths. /// </remarks> /// <returns>An array of <see cref="System.Threading.Tasks.Task">Task</see> instances.</returns> /// <exception cref="T:System.NotSupportedException"> /// This scheduler is unable to generate a list of queued tasks at this time. /// </exception> internal Task[] GetScheduledTasksForDebugger() { // this can throw InvalidOperationException indicating that they are unable to provide the info // at the moment. We should let the debugger receive that exception so that it can indicate it in the UI IEnumerable<Task> activeTasksSource = GetScheduledTasks(); if (activeTasksSource == null) return null; // If it can be cast to an array, use it directly Task[] activeTasksArray = activeTasksSource as Task[]; if (activeTasksArray == null) { activeTasksArray = (new LowLevelList<Task>(activeTasksSource)).ToArray(); } // touch all Task.Id fields so that the debugger doesn't need to do a lot of cross-proc calls to generate them foreach (Task t in activeTasksArray) { int tmp = t.Id; } return activeTasksArray; } /// <summary> /// Provides an array of all active <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> /// instances for the debugger. /// </summary> /// <remarks> /// This function is only meant to be invoked by a debugger remotely. /// It should not be called by any other codepaths. /// </remarks> /// <returns>An array of <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> instances.</returns> internal static TaskScheduler[] GetTaskSchedulersForDebugger() { if (s_activeTaskSchedulers == null) { // No schedulers were tracked. Just give back the default. return new TaskScheduler[] { s_defaultTaskScheduler }; } LowLevelList<TaskScheduler> schedulers = new LowLevelList<TaskScheduler>(); foreach (var item in s_activeTaskSchedulers) { schedulers.Add(item.Key); } if (!schedulers.Contains(s_defaultTaskScheduler)) { // Make sure the default is included, in case the debugger attached // after it was created. schedulers.Add(s_defaultTaskScheduler); } var arr = schedulers.ToArray(); foreach (var scheduler in arr) { Debug.Assert(scheduler != null, "Table returned an incorrect Count or CopyTo failed"); int tmp = scheduler.Id; // force Ids for debugger } return arr; } /// <summary> /// Nested class that provides debugger view for TaskScheduler /// </summary> internal sealed class SystemThreadingTasks_TaskSchedulerDebugView { private readonly TaskScheduler m_taskScheduler; public SystemThreadingTasks_TaskSchedulerDebugView(TaskScheduler scheduler) { m_taskScheduler = scheduler; } // returns the scheduler's Id public Int32 Id { get { return m_taskScheduler.Id; } } // returns the scheduler's GetScheduledTasks public IEnumerable<Task> ScheduledTasks { get { return m_taskScheduler.GetScheduledTasks(); } } } } /// <summary> /// A TaskScheduler implementation that executes all tasks queued to it through a call to /// <see cref="System.Threading.SynchronizationContext.Post"/> on the <see cref="T:System.Threading.SynchronizationContext"/> /// that its associated with. The default constructor for this class binds to the current <see cref="T:System.Threading.SynchronizationContext"/> /// </summary> internal sealed class SynchronizationContextTaskScheduler : TaskScheduler { private SynchronizationContext m_synchronizationContext; /// <summary> /// Constructs a SynchronizationContextTaskScheduler associated with <see cref="T:System.Threading.SynchronizationContext.Current"/> /// </summary> /// <exception cref="T:System.InvalidOperationException">This constructor expects <see cref="T:System.Threading.SynchronizationContext.Current"/> to be set.</exception> internal SynchronizationContextTaskScheduler() { SynchronizationContext synContext = SynchronizationContext.Current; // make sure we have a synccontext to work with if (synContext == null) { throw new InvalidOperationException(SR.TaskScheduler_FromCurrentSynchronizationContext_NoCurrent); } m_synchronizationContext = synContext; } /// <summary> /// Implemetation of <see cref="T:System.Threading.Tasks.TaskScheduler.QueueTask"/> for this scheduler class. /// /// Simply posts the tasks to be executed on the associated <see cref="T:System.Threading.SynchronizationContext"/>. /// </summary> /// <param name="task"></param> protected internal override void QueueTask(Task task) { m_synchronizationContext.Post(s_postCallback, (object)task); } /// <summary> /// Implementation of <see cref="T:System.Threading.Tasks.TaskScheduler.TryExecuteTaskInline"/> for this scheduler class. /// /// The task will be executed inline only if the call happens within /// the associated <see cref="T:System.Threading.SynchronizationContext"/>. /// </summary> /// <param name="task"></param> /// <param name="taskWasPreviouslyQueued"></param> protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (SynchronizationContext.Current == m_synchronizationContext) { return TryExecuteTask(task); } else return false; } // not implemented protected override IEnumerable<Task> GetScheduledTasks() { return null; } /// <summary> /// Implementes the <see cref="T:System.Threading.Tasks.TaskScheduler.MaximumConcurrencyLevel"/> property for /// this scheduler class. /// /// By default it returns 1, because a <see cref="T:System.Threading.SynchronizationContext"/> based /// scheduler only supports execution on a single thread. /// </summary> public override Int32 MaximumConcurrencyLevel { get { return 1; } } // preallocated SendOrPostCallback delegate private static readonly SendOrPostCallback s_postCallback = s => ((Task)s).ExecuteEntry(true); // with double-execute check because SC could be buggy } /// <summary> /// Provides data for the event that is raised when a faulted <see cref="System.Threading.Tasks.Task"/>'s /// exception goes unobserved. /// </summary> /// <remarks> /// The Exception property is used to examine the exception without marking it /// as observed, whereas the <see cref="SetObserved"/> method is used to mark the exception /// as observed. Marking the exception as observed prevents it from triggering exception escalation policy /// which, by default, terminates the process. /// </remarks> public class UnobservedTaskExceptionEventArgs : EventArgs { private AggregateException m_exception; internal bool m_observed = false; /// <summary> /// Initializes a new instance of the <see cref="UnobservedTaskExceptionEventArgs"/> class /// with the unobserved exception. /// </summary> /// <param name="exception">The Exception that has gone unobserved.</param> public UnobservedTaskExceptionEventArgs(AggregateException exception) { m_exception = exception; } /// <summary> /// Marks the <see cref="Exception"/> as "observed," thus preventing it /// from triggering exception escalation policy which, by default, terminates the process. /// </summary> public void SetObserved() { m_observed = true; } /// <summary> /// Gets whether this exception has been marked as "observed." /// </summary> public bool Observed { get { return m_observed; } } /// <summary> /// The Exception that went unobserved. /// </summary> public AggregateException Exception { get { return m_exception; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace MvcApplicationTest.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using BrawlLib.SSBB.ResourceNodes; using BrawlManagerLib; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace BrawlSongManager.SongExport { class SongEditor { static readonly string[] GCT_PATHS = { "RSBE01.gct", "/data/gecko/codes/RSBE01.gct", "/codes/RSBE01.gct", "../../../../codes/RSBE01.gct", }; static readonly string[] MUM_PATHS = { "../../menu2/mu_menumain.pac", "../../menu2/mu_menumain_en.pac", "../../../pfmenu2/mu_menumain.pac", "../../../pfmenu2/mu_menumain_en.pac" }; static readonly string[] INFO_PATHS = { "..\\..\\info2\\info.pac", "..\\..\\info2\\info_en.pac", "..\\info.pac" }; static readonly string[] TRNG_PATHS = { "..\\..\\info2\\info_training.pac", "..\\..\\info2\\info_training_en.pac", "..\\info_training.pac" }; // MU_MenuMain Details private string mumPath; private MSBinNode mumMsbn; // INFO Details private string infoPath; private MSBinNode infoMsbn; // TRNG Details private string trngPath; private MSBinNode trngMsbn; // Volume Details private string gctPath; private CustomSongVolumeCodeset gctCsv; public SongEditor() { } public void PrepareAllResources() { PrepareMUM(); PrepareINFO(); PrepareTRNG(); PrepareGCT(); } public Song ReadSong(string filename) { Song mapSong = GetDefaultSong(filename); if (mapSong == null) { return null; } return UpdateSongFromFileData(mapSong); } public Song GetDefaultSong(string filename) { return (from s in SongIDMap.Songs where s.Filename == filename select s).FirstOrDefault(); } public void WriteSong(Song song) { if (song.InfoPacIndex.HasValue) { if (mumMsbn != null) { mumMsbn._strings[song.InfoPacIndex.Value] = song.DefaultName; mumMsbn.SignalPropertyChange(); } if (infoMsbn != null) { infoMsbn._strings[song.InfoPacIndex.Value] = song.DefaultName; infoMsbn.SignalPropertyChange(); } if (trngMsbn != null) { trngMsbn._strings[song.InfoPacIndex.Value] = song.DefaultName; trngMsbn.SignalPropertyChange(); } } if (gctCsv != null) { if (song.DefaultVolume.HasValue) { gctCsv.Settings[song.ID] = song.DefaultVolume.Value; } else if (gctCsv.Settings.ContainsKey(song.ID)) { gctCsv.Settings.Remove(song.ID); } } } public void SaveResources() { if (mumMsbn != null && mumPath != null) { SaveMUM(); } if (infoMsbn != null && infoPath != null) { SaveINFO(); } if (trngMsbn != null && trngPath != null) { SaveTRNG(); } if (gctCsv != null && gctPath != null) { SaveGCT(); } } private Song UpdateSongFromFileData(Song song) { string title = song.DefaultName; if (song.InfoPacIndex.HasValue) { title = mumMsbn._strings[song.InfoPacIndex.Value]; } byte? volume = song.DefaultVolume; if (gctCsv != null && gctCsv.Settings.ContainsKey(song.ID)) { volume = gctCsv.Settings[song.ID]; } return new Song(title, song.Filename, song.ID, volume, song.InfoPacIndex); } public void PrepareMUM() { mumPath = FindFile(MUM_PATHS); mumMsbn = LoadPacMsbn(mumPath, "MiscData[7]"); } public void SaveMUM() { mumMsbn.Rebuild(); SavePacMsbn(mumMsbn, mumPath, "MiscData[7]"); } public void PrepareINFO() { infoPath = FindFile(INFO_PATHS); infoMsbn = LoadPacMsbn(infoPath, "MiscData[140]"); } public void SaveINFO() { infoMsbn.Rebuild(); SavePacMsbn(infoMsbn, infoPath, "MiscData[140]"); } public void PrepareTRNG() { trngPath = FindFile(TRNG_PATHS); trngMsbn = LoadPacMsbn(trngPath, "MiscData[140]"); } public void SaveTRNG() { trngMsbn.Rebuild(); SavePacMsbn(trngMsbn, trngPath, "MiscData[140]"); } public void PrepareGCT() { gctPath = FindFile(GCT_PATHS); gctCsv = new CustomSongVolumeCodeset(File.ReadAllBytes(gctPath)); } public void SaveGCT() { File.WriteAllBytes(gctPath, gctCsv.ExportGCT()); } private MSBinNode LoadPacMsbn(string path, string childNodeName) { using (ResourceNode node = NodeFactory.FromFile(null, path)) { var childNode = node.FindChild(childNodeName, true) as MSBinNode; if (childNode == null) { throw new Exception("Node '" + childNodeName + "' not found in '" + path + "'"); } return childNode; } } private void SavePacMsbn(MSBinNode msbn, string pacPath, string childNodeName) { string tmpPac = Path.GetTempFileName(); string tmpMsbn = Path.GetTempFileName(); msbn.Export(tmpMsbn); File.Copy(pacPath, tmpPac, true); using (ResourceNode tmpPacNode = NodeFactory.FromFile(null, tmpPac)) { MSBinNode tmpPacChildNode = tmpPacNode.FindChild(childNodeName, true) as MSBinNode; if (tmpPacChildNode == null) { throw new Exception("Error saving '" + pacPath + "': The file does not appear to have a '" + childNodeName + "'"); } else { tmpPacChildNode.Replace(tmpMsbn); tmpPacNode.Merge(); tmpPacNode.Export(pacPath); } } File.Delete(tmpPac); File.Delete(tmpMsbn); } private string FindFile(string[] paths) { foreach (string path in paths) { if (File.Exists(path)) { return path; } } throw new FileNotFoundException("Could not find any file in: ['" + string.Join("', '", paths) + "']"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Speakr.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) Microsoft. 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.ComponentModel; using System.Composition; using System.Diagnostics; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Completion; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.Internal.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; using Microsoft.VisualStudio.Settings; using Microsoft.VisualStudio.Shell; using Microsoft.Win32; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { [ExportLanguageSpecificOptionSerializer( LanguageNames.CSharp, OrganizerOptions.FeatureName, CompletionOptions.FeatureName, CSharpCompletionOptions.FeatureName, CSharpCodeStyleOptions.FeatureName, SimplificationOptions.PerLanguageFeatureName, ExtractMethodOptions.FeatureName, CSharpFormattingOptions.IndentFeatureName, CSharpFormattingOptions.NewLineFormattingFeatureName, CSharpFormattingOptions.SpacingFeatureName, CSharpFormattingOptions.WrappingFeatureName, FormattingOptions.InternalTabFeatureName, FeatureOnOffOptions.OptionName, ServiceFeatureOnOffOptions.OptionName), Shared] internal sealed class CSharpSettingsManagerOptionSerializer : AbstractSettingsManagerOptionSerializer { [ImportingConstructor] public CSharpSettingsManagerOptionSerializer(SVsServiceProvider serviceProvider, IOptionService optionService) : base(serviceProvider, optionService) { } private const string WrappingIgnoreSpacesAroundBinaryOperator = nameof(AutomationObject.Wrapping_IgnoreSpacesAroundBinaryOperators); private const string SpaceAroundBinaryOperator = nameof(AutomationObject.Space_AroundBinaryOperator); private const string UnindentLabels = nameof(AutomationObject.Indent_UnindentLabels); private const string FlushLabelsLeft = nameof(AutomationObject.Indent_FlushLabelsLeft); private KeyValuePair<string, IOption> GetOptionInfoForOnOffOptions(FieldInfo fieldInfo) { var value = (IOption)fieldInfo.GetValue(obj: null); return new KeyValuePair<string, IOption>(GetStorageKeyForOption(value), value); } private bool ShouldIncludeOnOffOption(FieldInfo fieldInfo) { return SupportsOnOffOption((IOption)fieldInfo.GetValue(obj: null)); } protected override ImmutableDictionary<string, IOption> CreateStorageKeyToOptionMap() { var result = ImmutableDictionary.Create<string, IOption>(StringComparer.OrdinalIgnoreCase).ToBuilder(); result.AddRange(new[] { new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.IncludeKeywords), CompletionOptions.IncludeKeywords), new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.TriggerOnTypingLetters), CompletionOptions.TriggerOnTypingLetters), }); Type[] types = new[] { typeof(OrganizerOptions), typeof(CSharpCompletionOptions), typeof(SimplificationOptions), typeof(CSharpCodeStyleOptions), typeof(ExtractMethodOptions), typeof(ServiceFeatureOnOffOptions), typeof(CSharpFormattingOptions) }; var bindingFlags = BindingFlags.Public | BindingFlags.Static; result.AddRange(AbstractSettingsManagerOptionSerializer.GetOptionInfoFromTypeFields(types, bindingFlags, this.GetOptionInfo)); types = new[] { typeof(FeatureOnOffOptions) }; result.AddRange(AbstractSettingsManagerOptionSerializer.GetOptionInfoFromTypeFields(types, bindingFlags, this.GetOptionInfoForOnOffOptions, this.ShouldIncludeOnOffOption)); return result.ToImmutable(); } protected override string LanguageName { get { return LanguageNames.CSharp; } } protected override string SettingStorageRoot { get { return "TextEditor.CSharp.Specific."; } } protected override bool SupportsOption(IOption option, string languageName) { if (option == OrganizerOptions.PlaceSystemNamespaceFirst || option == OrganizerOptions.WarnOnBuildErrors || option == CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord || option == CSharpCompletionOptions.IncludeSnippets || option.Feature == CSharpCodeStyleOptions.FeatureName || option.Feature == CSharpFormattingOptions.WrappingFeatureName || option.Feature == CSharpFormattingOptions.IndentFeatureName || option.Feature == CSharpFormattingOptions.SpacingFeatureName || option.Feature == CSharpFormattingOptions.NewLineFormattingFeatureName) { return true; } else if (languageName == LanguageNames.CSharp) { if (option == CompletionOptions.IncludeKeywords || option == CompletionOptions.TriggerOnTypingLetters || option.Feature == SimplificationOptions.PerLanguageFeatureName || option.Feature == ExtractMethodOptions.FeatureName || option.Feature == ServiceFeatureOnOffOptions.OptionName || option.Feature == FormattingOptions.InternalTabFeatureName) { return true; } else if (option.Feature == FeatureOnOffOptions.OptionName) { return SupportsOnOffOption(option); } } return false; } private bool SupportsOnOffOption(IOption option) { return option == FeatureOnOffOptions.AutoFormattingOnCloseBrace || option == FeatureOnOffOptions.AutoFormattingOnSemicolon || option == FeatureOnOffOptions.LineSeparator || option == FeatureOnOffOptions.Outlining || option == FeatureOnOffOptions.ReferenceHighlighting || option == FeatureOnOffOptions.KeywordHighlighting || option == FeatureOnOffOptions.FormatOnPaste || option == FeatureOnOffOptions.AutoXmlDocCommentGeneration || option == FeatureOnOffOptions.RefactoringVerification || option == FeatureOnOffOptions.RenameTracking; } public override bool TryFetch(OptionKey optionKey, out object value) { value = null; if (this.Manager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } if (optionKey.Option == CSharpFormattingOptions.SpacingAroundBinaryOperator) { // Remove space -> Space_AroundBinaryOperator = 0 // Insert space -> Space_AroundBinaryOperator and Wrapping_IgnoreSpacesAroundBinaryOperator both missing // Ignore spacing -> Wrapping_IgnoreSpacesAroundBinaryOperator = 1 object ignoreSpacesAroundBinaryObjectValue = this.Manager.GetValueOrDefault(WrappingIgnoreSpacesAroundBinaryOperator, defaultValue: 0); if (ignoreSpacesAroundBinaryObjectValue.Equals(1)) { value = BinaryOperatorSpacingOptions.Ignore; return true; } object spaceAroundBinaryOperatorObjectValue = this.Manager.GetValueOrDefault(SpaceAroundBinaryOperator, defaultValue: 1); if (spaceAroundBinaryOperatorObjectValue.Equals(0)) { value = BinaryOperatorSpacingOptions.Remove; return true; } value = BinaryOperatorSpacingOptions.Single; return true; } if (optionKey.Option == CSharpFormattingOptions.LabelPositioning) { object flushLabelLeftObjectValue = this.Manager.GetValueOrDefault(FlushLabelsLeft, defaultValue: 0); if (flushLabelLeftObjectValue.Equals(1)) { value = LabelPositionOptions.LeftMost; return true; } object unindentLabelsObjectValue = this.Manager.GetValueOrDefault(UnindentLabels, defaultValue: 1); if (unindentLabelsObjectValue.Equals(0)) { value = LabelPositionOptions.NoIndent; return true; } value = LabelPositionOptions.OneLess; return true; } return base.TryFetch(optionKey, out value); } public override bool TryPersist(OptionKey optionKey, object value) { if (this.Manager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } if (optionKey.Option == CSharpFormattingOptions.SpacingAroundBinaryOperator) { // Remove space -> Space_AroundBinaryOperator = 0 // Insert space -> Space_AroundBinaryOperator and Wrapping_IgnoreSpacesAroundBinaryOperator both missing // Ignore spacing -> Wrapping_IgnoreSpacesAroundBinaryOperator = 1 switch ((BinaryOperatorSpacingOptions)value) { case BinaryOperatorSpacingOptions.Remove: { this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, value: 0, isMachineLocal: false); this.Manager.SetValueAsync(SpaceAroundBinaryOperator, 0, isMachineLocal: false); return true; } case BinaryOperatorSpacingOptions.Ignore: { this.Manager.SetValueAsync(SpaceAroundBinaryOperator, value: 1, isMachineLocal: false); this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, 1, isMachineLocal: false); return true; } case BinaryOperatorSpacingOptions.Single: { this.Manager.SetValueAsync(SpaceAroundBinaryOperator, value: 1, isMachineLocal: false); this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, value: 0, isMachineLocal: false); return true; } } } else if (optionKey.Option == CSharpFormattingOptions.LabelPositioning) { switch ((LabelPositionOptions)value) { case LabelPositionOptions.LeftMost: { this.Manager.SetValueAsync(UnindentLabels, value: 1, isMachineLocal: false); this.Manager.SetValueAsync(FlushLabelsLeft, 1, isMachineLocal: false); return true; } case LabelPositionOptions.NoIndent: { this.Manager.SetValueAsync(FlushLabelsLeft, value: 0, isMachineLocal: false); this.Manager.SetValueAsync(UnindentLabels, 0, isMachineLocal: false); return true; } case LabelPositionOptions.OneLess: { this.Manager.SetValueAsync(FlushLabelsLeft, value: 0, isMachineLocal: false); this.Manager.SetValueAsync(UnindentLabels, value: 1, isMachineLocal: false); return true; } } } return base.TryPersist(optionKey, value); } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecT113R1Point : AbstractF2mPoint { /** * @deprecated Use ECCurve.createPoint to construct points */ public SecT113R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) : this(curve, x, y, false) { } /** * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} */ public SecT113R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) : base(curve, x, y, withCompression) { if ((x == null) != (y == null)) throw new ArgumentException("Exactly one of the field elements is null"); } internal SecT113R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) : base(curve, x, y, zs, withCompression) { } protected override ECPoint Detach() { return new SecT113R1Point(null, AffineXCoord, AffineYCoord); } public override ECFieldElement YCoord { get { ECFieldElement X = RawXCoord, L = RawYCoord; if (this.IsInfinity || X.IsZero) return L; // Y is actually Lambda (X + Y/X) here; convert to affine value on the fly ECFieldElement Y = L.Add(X).Multiply(X); ECFieldElement Z = RawZCoords[0]; if (!Z.IsOne) { Y = Y.Divide(Z); } return Y; } } protected internal override bool CompressionYTilde { get { ECFieldElement X = this.RawXCoord; if (X.IsZero) return false; ECFieldElement Y = this.RawYCoord; // Y is actually Lambda (X + Y/X) here return Y.TestBitZero() != X.TestBitZero(); } } public override ECPoint Add(ECPoint b) { if (this.IsInfinity) return b; if (b.IsInfinity) return this; ECCurve curve = this.Curve; ECFieldElement X1 = this.RawXCoord; ECFieldElement X2 = b.RawXCoord; if (X1.IsZero) { if (X2.IsZero) return curve.Infinity; return b.Add(this); } ECFieldElement L1 = this.RawYCoord, Z1 = this.RawZCoords[0]; ECFieldElement L2 = b.RawYCoord, Z2 = b.RawZCoords[0]; bool Z1IsOne = Z1.IsOne; ECFieldElement U2 = X2, S2 = L2; if (!Z1IsOne) { U2 = U2.Multiply(Z1); S2 = S2.Multiply(Z1); } bool Z2IsOne = Z2.IsOne; ECFieldElement U1 = X1, S1 = L1; if (!Z2IsOne) { U1 = U1.Multiply(Z2); S1 = S1.Multiply(Z2); } ECFieldElement A = S1.Add(S2); ECFieldElement B = U1.Add(U2); if (B.IsZero) { if (A.IsZero) return Twice(); return curve.Infinity; } ECFieldElement X3, L3, Z3; if (X2.IsZero) { // TODO This can probably be optimized quite a bit ECPoint p = this.Normalize(); X1 = p.XCoord; ECFieldElement Y1 = p.YCoord; ECFieldElement Y2 = L2; ECFieldElement L = Y1.Add(Y2).Divide(X1); X3 = L.Square().Add(L).Add(X1).Add(curve.A); if (X3.IsZero) { return new SecT113R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); L3 = Y3.Divide(X3).Add(X3); Z3 = curve.FromBigInteger(BigInteger.One); } else { B = B.Square(); ECFieldElement AU1 = A.Multiply(U1); ECFieldElement AU2 = A.Multiply(U2); X3 = AU1.Multiply(AU2); if (X3.IsZero) { return new SecT113R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); } ECFieldElement ABZ2 = A.Multiply(B); if (!Z2IsOne) { ABZ2 = ABZ2.Multiply(Z2); } L3 = AU2.Add(B).SquarePlusProduct(ABZ2, L1.Add(Z1)); Z3 = ABZ2; if (!Z1IsOne) { Z3 = Z3.Multiply(Z1); } } return new SecT113R1Point(curve, X3, L3, new ECFieldElement[]{ Z3 }, IsCompressed); } public override ECPoint Twice() { if (this.IsInfinity) return this; ECCurve curve = this.Curve; ECFieldElement X1 = this.RawXCoord; if (X1.IsZero) { // A point with X == 0 is it's own Additive inverse return curve.Infinity; } ECFieldElement L1 = this.RawYCoord, Z1 = this.RawZCoords[0]; bool Z1IsOne = Z1.IsOne; ECFieldElement L1Z1 = Z1IsOne ? L1 : L1.Multiply(Z1); ECFieldElement Z1Sq = Z1IsOne ? Z1 : Z1.Square(); ECFieldElement a = curve.A; ECFieldElement aZ1Sq = Z1IsOne ? a : a.Multiply(Z1Sq); ECFieldElement T = L1.Square().Add(L1Z1).Add(aZ1Sq); if (T.IsZero) { return new SecT113R1Point(curve, T, curve.B.Sqrt(), IsCompressed); } ECFieldElement X3 = T.Square(); ECFieldElement Z3 = Z1IsOne ? T : T.Multiply(Z1Sq); ECFieldElement X1Z1 = Z1IsOne ? X1 : X1.Multiply(Z1); ECFieldElement L3 = X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3); return new SecT113R1Point(curve, X3, L3, new ECFieldElement[]{ Z3 }, IsCompressed); } public override ECPoint TwicePlus(ECPoint b) { if (this.IsInfinity) return b; if (b.IsInfinity) return Twice(); ECCurve curve = this.Curve; ECFieldElement X1 = this.RawXCoord; if (X1.IsZero) { // A point with X == 0 is it's own Additive inverse return b; } ECFieldElement X2 = b.RawXCoord, Z2 = b.RawZCoords[0]; if (X2.IsZero || !Z2.IsOne) { return Twice().Add(b); } ECFieldElement L1 = this.RawYCoord, Z1 = this.RawZCoords[0]; ECFieldElement L2 = b.RawYCoord; ECFieldElement X1Sq = X1.Square(); ECFieldElement L1Sq = L1.Square(); ECFieldElement Z1Sq = Z1.Square(); ECFieldElement L1Z1 = L1.Multiply(Z1); ECFieldElement T = curve.A.Multiply(Z1Sq).Add(L1Sq).Add(L1Z1); ECFieldElement L2plus1 = L2.AddOne(); ECFieldElement A = curve.A.Add(L2plus1).Multiply(Z1Sq).Add(L1Sq).MultiplyPlusProduct(T, X1Sq, Z1Sq); ECFieldElement X2Z1Sq = X2.Multiply(Z1Sq); ECFieldElement B = X2Z1Sq.Add(T).Square(); if (B.IsZero) { if (A.IsZero) return b.Twice(); return curve.Infinity; } if (A.IsZero) { return new SecT113R1Point(curve, A, curve.B.Sqrt(), IsCompressed); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3); return new SecT113R1Point(curve, X3, L3, new ECFieldElement[]{ Z3 }, IsCompressed); } public override ECPoint Negate() { if (IsInfinity) return this; ECFieldElement X = this.RawXCoord; if (X.IsZero) return this; // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; return new SecT113R1Point(Curve, X, L.Add(Z), new ECFieldElement[]{ Z }, IsCompressed); } } } #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsHeadExceptions { using Fixtures.Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// HeadExceptionOperations operations. /// </summary> internal partial class HeadExceptionOperations : IServiceOperations<AutoRestHeadExceptionTestServiceClient>, IHeadExceptionOperations { /// <summary> /// Initializes a new instance of the HeadExceptionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal HeadExceptionOperations(AutoRestHeadExceptionTestServiceClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestHeadExceptionTestServiceClient /// </summary> public AutoRestHeadExceptionTestServiceClient Client { get; private set; } /// <summary> /// Return 200 status code if successful /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> Head200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Head200", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/200").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("HEAD"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Return 204 status code if successful /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> Head204WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Head204", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/204").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("HEAD"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Return 404 status code if successful /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> Head404WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Head404", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/404").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("HEAD"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Storage { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// UsageOperations operations. /// </summary> internal partial class UsageOperations : IServiceOperations<StorageManagementClient>, IUsageOperations { /// <summary> /// Initializes a new instance of the UsageOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal UsageOperations(StorageManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the StorageManagementClient /// </summary> public StorageManagementClient Client { get; private set; } /// <summary> /// Gets the current usage count and the limit for the resources under the /// subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<Usage>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Storage/usages").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<Usage>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Usage>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.AdWords.Lib; using Google.Api.Ads.AdWords.v201809; using System; using System.Collections.Generic; namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809 { /// <summary> /// This code example adds campaigns. To get campaigns, run GetCampaigns.cs. /// </summary> public class AddCampaigns : ExampleBase { /// <summary> /// Number of items being added / updated in this code example. /// </summary> private const int NUM_ITEMS = 5; /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { AddCampaigns codeExample = new AddCampaigns(); Console.WriteLine(codeExample.Description); try { codeExample.Run(new AdWordsUser()); } catch (Exception e) { Console.WriteLine("An exception occurred while running this code example. {0}", ExampleUtilities.FormatException(e)); } } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example adds campaigns. To get campaigns, run GetCampaigns.cs."; } } /// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> public void Run(AdWordsUser user) { using (CampaignService campaignService = (CampaignService) user.GetService(AdWordsService.v201809.CampaignService)) { Budget budget = CreateBudget(user); List<CampaignOperation> operations = new List<CampaignOperation>(); for (int i = 0; i < NUM_ITEMS; i++) { // Create the campaign. Campaign campaign = new Campaign { name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(), advertisingChannelType = AdvertisingChannelType.SEARCH, // Recommendation: Set the campaign to PAUSED when creating it to prevent // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve. status = CampaignStatus.PAUSED }; BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration { biddingStrategyType = BiddingStrategyType.MANUAL_CPC }; campaign.biddingStrategyConfiguration = biddingConfig; campaign.budget = new Budget { budgetId = budget.budgetId }; // Set the campaign network options. campaign.networkSetting = new NetworkSetting { targetGoogleSearch = true, targetSearchNetwork = true, targetContentNetwork = false, targetPartnerSearchNetwork = false }; // Set the campaign settings for Advanced location options. GeoTargetTypeSetting geoSetting = new GeoTargetTypeSetting { positiveGeoTargetType = GeoTargetTypeSettingPositiveGeoTargetType.DONT_CARE, negativeGeoTargetType = GeoTargetTypeSettingNegativeGeoTargetType.DONT_CARE }; campaign.settings = new Setting[] { geoSetting }; // Optional: Set the start date. campaign.startDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd"); // Optional: Set the end date. campaign.endDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd"); // Optional: Set the frequency cap. FrequencyCap frequencyCap = new FrequencyCap { impressions = 5, level = Level.ADGROUP, timeUnit = TimeUnit.DAY }; campaign.frequencyCap = frequencyCap; // Create the operation. CampaignOperation operation = new CampaignOperation { @operator = Operator.ADD, operand = campaign }; operations.Add(operation); } try { // Add the campaign. CampaignReturnValue retVal = campaignService.mutate(operations.ToArray()); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { foreach (Campaign newCampaign in retVal.value) { Console.WriteLine( "Campaign with name = '{0}' and id = '{1}' was added.", newCampaign.name, newCampaign.id); } } else { Console.WriteLine("No campaigns were added."); } } catch (Exception e) { throw new System.ApplicationException("Failed to add campaigns.", e); } } } /// <summary> /// Creates the budget for the campaign. /// </summary> /// <param name="user">The AdWords user.</param> /// <returns>The budget instance.</returns> private static Budget CreateBudget(AdWordsUser user) { using (BudgetService budgetService = (BudgetService) user.GetService(AdWordsService.v201809.BudgetService)) { // Create the campaign budget. Budget budget = new Budget { name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString(), deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD, amount = new Money { microAmount = 500000 } }; BudgetOperation budgetOperation = new BudgetOperation { @operator = Operator.ADD, operand = budget }; try { BudgetReturnValue budgetRetval = budgetService.mutate(new BudgetOperation[] { budgetOperation }); return budgetRetval.value[0]; } catch (Exception e) { throw new System.ApplicationException("Failed to add shared budget.", e); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text.RegularExpressions; public class PluginsDummy { // from http://www.dotnetperls.com/word-count public static int CountWords1(string s) { MatchCollection collection = Regex.Matches(s, @"[\S]+"); return collection.Count; } public static int CountWords2(string s) { int c = 0; for (int i = 1; i < s.Length; i++) { if (char.IsWhiteSpace(s[i - 1]) == true) { if (char.IsLetterOrDigit(s[i]) == true || char.IsPunctuation(s[i])) { c++; } } } if (s.Length > 2) { c++; } return c; } // from http://www.dotnetperls.com/array-optimization const int _max = 100000000; public static void ArrayOptimization() { int[] array = new int[12]; Method1(array); Method2(array); var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { Method1(array); } s1.Stop(); var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { Method2(array); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString("0.00 ns")); Console.Read(); } static void Method1(int[] array) { // Initialize each element in for-loop. for (int i = 0; i < array.Length; i++) { array[i] = 1; } } static void Method2(int[] array) { // Initialize each element in separate statement with no enclosing loop. array[0] = 1; array[1] = 1; array[2] = 1; array[3] = 1; array[4] = 1; array[5] = 1; array[6] = 1; array[7] = 1; array[8] = 1; array[9] = 1; array[10] = 1; array[11] = 1; } // from http://www.dotnetperls.com/dictionary public static void Dictionary1() { // Example Dictionary again. Dictionary<string, int> d = new Dictionary<string, int>() { {"cat", 2}, {"dog", 1}, {"llama", 0}, {"iguana", -1} }; // Loop over pairs with foreach. foreach (KeyValuePair<string, int> pair in d) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); } // Use var keyword to enumerate dictionary. foreach (var pair in d) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); } } public static void Dictionary2() { Dictionary<string, int> d = new Dictionary<string, int>() { {"cat", 2}, {"dog", 1}, {"llama", 0}, {"iguana", -1} }; // Store keys in a List List<string> list = new List<string>(d.Keys); // Loop through list foreach (string k in list) { Console.WriteLine("{0}, {1}", k, d[k]); } } // from: http://www.dotnetperls.com/format public static void Format1() { // Declare three variables. // ... The values they have are not important. string value1 = "Dot Net Perls"; int value2 = 10000; DateTime value3 = new DateTime(2015, 11, 1); // Use string.Format method with four arguments. // ... The first argument is the formatting string. // ... It specifies how the next arguments are formatted. string result = string.Format("{0}: {1:0.0} - {2:yyyy}", value1, value2, value3); // Write the result. Console.WriteLine(result); } public static void Format2() { // Format a ratio as a percentage string. // ... You must specify the percentage symbol. // ... It will multiply the value by 100. double ratio = 0.73; string result = string.Format("string = {0:0.0%}", ratio); Console.WriteLine(result); } public static void Format3() { // The constant formatting string. // ... It specifies the padding. // ... A negative number means to left-align. // ... A positive number means to right-align. const string format = "{0,-10} {1,10}"; // Construct the strings. string line1 = string.Format(format, 100, 5); string line2 = string.Format(format, "Carrot", "Giraffe"); // Write the formatted strings. Console.WriteLine(line1); Console.WriteLine(line2); } public static void Format4() { int value1 = 10995; // Write number in hex format. Console.WriteLine("{0:x}", value1); Console.WriteLine("{0:x8}", value1); Console.WriteLine("{0:X}", value1); Console.WriteLine("{0:X8}", value1); // Convert to hex. string hex = value1.ToString("X8"); // Convert from hex to integer. int value2 = int.Parse(hex, NumberStyles.AllowHexSpecifier); Console.WriteLine(value1 == value2); } }
using System; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Threading; using LanguageExt.Common; using LanguageExt.Effects.Traits; // TODO: Retrying // TODO: Folding namespace LanguageExt.Thunks { public static class Thunk { internal const MethodImplOptions mops = MethodImplOptions.AggressiveInlining; public const int NotEvaluated = 0; public const int Evaluating = 1; public const int IsSuccess = 2; public const int IsFailed = 4; public const int IsCancelled = 8; public const int HasEvaluated = IsSuccess | IsFailed | IsCancelled; [Pure, MethodImpl(mops)] public static ThunkAsync<Env, A> Flatten<Env, A>(this ThunkAsync<Env, ThunkAsync<Env, A>> mma) where Env : struct, HasCancel<Env> => mma is null ? throw new ArgumentNullException(nameof(mma)) : ThunkAsync<Env, A>.Lazy( async env => { var ra = await mma.ReValue(env).ConfigureAwait(false); return ra.IsSucc ? await ra.Value.ReValue(env).ConfigureAwait(false) : Fin<A>.Fail(ra.Error); }); [Pure, MethodImpl(Thunk.mops)] public static ThunkAsync<Env, A> Flatten<Env, A>(this ThunkAsync<ThunkAsync<Env, A>> mma) where Env : struct, HasCancel<Env> => mma is null ? throw new ArgumentNullException(nameof(mma)) : ThunkAsync<Env, A>.Lazy( async env => { var ra = await mma.ReValue().ConfigureAwait(false); return ra.IsSucc ? await ra.Value.ReValue(env).ConfigureAwait(false) : Fin<A>.Fail(ra.Error); }); [Pure, MethodImpl(Thunk.mops)] public static ThunkAsync<Env, A> Flatten<Env, A>(this ThunkAsync<Thunk<Env, A>> mma) where Env : struct, HasCancel<Env> => mma is null ? throw new ArgumentNullException(nameof(mma)) : ThunkAsync<Env, A>.Lazy( async env => { var ra = await mma.ReValue().ConfigureAwait(false); return ra.IsSucc ? ra.Value.ReValue(env) : Fin<A>.Fail(ra.Error); }); [Pure, MethodImpl(Thunk.mops)] public static ThunkAsync<Env, A> Flatten<Env, A>(this Thunk<ThunkAsync<Env, A>> mma) where Env : struct, HasCancel<Env> => mma is null ? throw new ArgumentNullException(nameof(mma)) : ThunkAsync<Env, A>.Lazy( async env => { var ra = mma.ReValue(); return ra.IsSucc ? await ra.Value.ReValue(env).ConfigureAwait(false) : Fin<A>.Fail(ra.Error); }); [Pure, MethodImpl(Thunk.mops)] public static ThunkAsync<Env, A> Flatten<Env, A>(this ThunkAsync<Env, ThunkAsync<A>> mma) where Env : struct, HasCancel<Env> => mma is null ? throw new ArgumentNullException(nameof(mma)) : ThunkAsync<Env, A>.Lazy( async env => { var ra = await mma.ReValue(env).ConfigureAwait(false); return ra.IsSucc ? await ra.Value.ReValue().ConfigureAwait(false) : Fin<A>.Fail(ra.Error); }); [Pure, MethodImpl(Thunk.mops)] public static ThunkAsync<Env, A> Flatten<Env, A>(this ThunkAsync<Env, Thunk<Env, A>> mma) where Env : struct, HasCancel<Env> => mma is null ? throw new ArgumentNullException(nameof(mma)) : ThunkAsync<Env, A>.Lazy( async env => { var ra = await mma.ReValue(env).ConfigureAwait(false); return ra.IsSucc ? ra.Value.ReValue(env) : Fin<A>.Fail(ra.Error); }); [Pure, MethodImpl(Thunk.mops)] public static ThunkAsync<Env, A> Flatten<Env, A>(this Thunk<Env, ThunkAsync<Env, A>> mma) where Env : struct, HasCancel<Env> => mma is null ? throw new ArgumentNullException(nameof(mma)) : ThunkAsync<Env, A>.Lazy( async env => { var ra = mma.ReValue(env); return ra.IsSucc ? await ra.Value.ReValue(env).ConfigureAwait(false) : Fin<A>.Fail(ra.Error); }); [Pure] public static ThunkAsync<Env, A> Flatten<Env, A>(this ThunkAsync<Env, Thunk<A>> mma) where Env : struct, HasCancel<Env> => mma is null ? throw new ArgumentNullException(nameof(mma)) : ThunkAsync<Env, A>.Lazy( async env => { var ra = await mma.ReValue(env).ConfigureAwait(false); return ra.IsSucc ? ra.Value.ReValue() : Fin<A>.Fail(ra.Error); }); [Pure] public static ThunkAsync<Env, A> Flatten<Env, A>(this Thunk<Env, ThunkAsync<A>> mma) where Env : struct, HasCancel<Env> => mma is null ? throw new ArgumentNullException(nameof(mma)) : ThunkAsync<Env, A>.Lazy( async env => { var ra = mma.ReValue(env); return ra.IsSucc ? await ra.Value.ReValue().ConfigureAwait(false) : Fin<A>.Fail(ra.Error); }); [Pure, MethodImpl(Thunk.mops)] public static ThunkAsync< A> Flatten<A>(this ThunkAsync<ThunkAsync<A>> mma) => mma is null ? throw new ArgumentNullException(nameof(mma)) : ThunkAsync<A>.Lazy( async () => { var ra = await mma.ReValue().ConfigureAwait(false); return ra.IsSucc ? await ra.Value.ReValue().ConfigureAwait(false) : Fin<A>.Fail(ra.Error); }); [Pure, MethodImpl(Thunk.mops)] public static ThunkAsync<A> Flatten<A>(this ThunkAsync<Thunk<A>> mma) => mma is null ? throw new ArgumentNullException(nameof(mma)) : ThunkAsync<A>.Lazy( async () => { var ra = await mma.ReValue().ConfigureAwait(false); return ra.IsSucc ? ra.Value.ReValue() : Fin<A>.Fail(ra.Error); }); [Pure, MethodImpl(Thunk.mops)] public static ThunkAsync<A> Flatten<A>(this Thunk<ThunkAsync<A>> mma) => mma is null ? throw new ArgumentNullException(nameof(mma)) : ThunkAsync<A>.Lazy( async () => { var ra = mma.ReValue(); return ra.IsSucc ? await ra.Value.ReValue().ConfigureAwait(false) : Fin<A>.Fail(ra.Error); }); [Pure, MethodImpl(Thunk.mops)] public static Thunk<Env, A> Flatten<Env, A>(this Thunk<Env, Thunk<Env, A>> mma) => mma is null ? throw new ArgumentNullException(nameof(mma)) : Thunk<Env, A>.Lazy( env => { var ra = mma.ReValue(env); return ra.IsSucc ? ra.Value.ReValue(env) : Fin<A>.Fail(ra.Error); }); [Pure, MethodImpl(Thunk.mops)] public static Thunk<Env, A> Flatten<Env, A>(this Thunk<Thunk<Env, A>> mma) => mma is null ? throw new ArgumentNullException(nameof(mma)) : Thunk<Env, A>.Lazy( env => { var ra = mma.ReValue(); return ra.IsSucc ? ra.Value.ReValue(env) : Fin<A>.Fail(ra.Error); }); [Pure] public static Thunk<Env, A> Flatten<Env, A>(this Thunk<Env, Thunk<A>> mma) => mma is null ? throw new ArgumentNullException(nameof(mma)) : Thunk<Env, A>.Lazy( env => { var ra = mma.ReValue(env); return ra.IsSucc ? ra.Value.ReValue() : Fin<A>.Fail(ra.Error); }); [Pure, MethodImpl(Thunk.mops)] public static Thunk<A> Flatten<A>(this Thunk<Thunk<A>> mma) => mma is null ? throw new ArgumentNullException(nameof(mma)) : Thunk< A>.Lazy( () => { var ra = mma.ReValue(); return ra.IsSucc ? ra.Value.ReValue() : Fin<A>.Fail(ra.Error); }); } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. 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. Note: This code has been heavily modified for the Duality framework. */ #endregion using System; using System.Runtime.InteropServices; namespace Duality { /// <summary> /// Represents a 2D vector using two single-precision floating-point numbers. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Vector2 : IEquatable<Vector2> { /// <summary> /// Defines a unit-length Vector2 that points towards the X-axis. /// </summary> public static readonly Vector2 UnitX = new Vector2(1, 0); /// <summary> /// Defines a unit-length Vector2 that points towards the Y-axis. /// </summary> public static readonly Vector2 UnitY = new Vector2(0, 1); /// <summary> /// Defines a zero-length Vector2. /// </summary> public static readonly Vector2 Zero = new Vector2(0, 0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector2 One = new Vector2(1, 1); /// <summary> /// The X component of the Vector2. /// </summary> public float X; /// <summary> /// The Y component of the Vector2. /// </summary> public float Y; /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector2(float value) { X = value; Y = value; } /// <summary> /// Constructs a new Vector2. /// </summary> /// <param name="x">The x coordinate of the net Vector2.</param> /// <param name="y">The y coordinate of the net Vector2.</param> public Vector2(float x, float y) { X = x; Y = y; } /// <summary> /// Constructs a new vector from angle and length. /// </summary> /// <param name="angle"></param> /// <param name="length"></param> /// <returns></returns> public static Vector2 FromAngleLength(float angle, float length) { return new Vector2((float)Math.Sin(angle) * length, (float)Math.Cos(angle) * -length); } /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <seealso cref="LengthSquared"/> public float Length { get { return (float)System.Math.Sqrt(X * X + Y * Y); } } /// <summary> /// Gets the square of the vector length (magnitude). /// </summary> /// <remarks> /// This property avoids the costly square root operation required by the Length property. This makes it more suitable /// for comparisons. /// </remarks> /// <see cref="Length"/> public float LengthSquared { get { return X * X + Y * Y; } } /// <summary> /// Returns the vectors angle /// </summary> public float Angle { get { return (float)((Math.Atan2(Y, X) + Math.PI * 2.5) % (Math.PI * 2)); } } /// <summary> /// Gets the perpendicular vector on the right side of this vector. /// </summary> public Vector2 PerpendicularRight { get { return new Vector2(-Y, X); } } /// <summary> /// Gets the perpendicular vector on the left side of this vector. /// </summary> public Vector2 PerpendicularLeft { get { return new Vector2(Y, -X); } } /// <summary> /// Returns a normalized version of this vector. /// </summary> public Vector2 Normalized { get { Vector2 n = this; n.Normalize(); return n; } } /// <summary> /// Gets or sets the value at the index of the Vector. /// </summary> public float this[int index] { get { if (index == 0) return X; else if (index == 1) return Y; throw new IndexOutOfRangeException("You tried to access this vector at index: " + index); } set { if (index == 0) X = value; else if (index == 1) Y = value; else throw new IndexOutOfRangeException("You tried to set this vector at index: " + index); } } /// <summary> /// Scales the Vector2 to unit length. /// </summary> public void Normalize() { float scale = 1.0f / this.Length; X *= scale; Y *= scale; } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <param name="result">Result of operation.</param> public static void Add(ref Vector2 a, ref Vector2 b, out Vector2 result) { result = new Vector2(a.X + b.X, a.Y + b.Y); } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Subtract(ref Vector2 a, ref Vector2 b, out Vector2 result) { result = new Vector2(a.X - b.X, a.Y - b.Y); } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector2 vector, float scale, out Vector2 result) { result = new Vector2(vector.X * scale, vector.Y * scale); } /// <summary> /// Multiplies a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector2 vector, ref Vector2 scale, out Vector2 result) { result = new Vector2(vector.X * scale.X, vector.Y * scale.Y); } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector2 vector, float scale, out Vector2 result) { Multiply(ref vector, 1 / scale, out result); } /// <summary> /// Divide a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector2 vector, ref Vector2 scale, out Vector2 result) { result = new Vector2(vector.X / scale.X, vector.Y / scale.Y); } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise minimum</returns> public static Vector2 Min(Vector2 a, Vector2 b) { a.X = a.X < b.X ? a.X : b.X; a.Y = a.Y < b.Y ? a.Y : b.Y; return a; } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise minimum</param> public static void Min(ref Vector2 a, ref Vector2 b, out Vector2 result) { result.X = a.X < b.X ? a.X : b.X; result.Y = a.Y < b.Y ? a.Y : b.Y; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise maximum</returns> public static Vector2 Max(Vector2 a, Vector2 b) { a.X = a.X > b.X ? a.X : b.X; a.Y = a.Y > b.Y ? a.Y : b.Y; return a; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise maximum</param> public static void Max(ref Vector2 a, ref Vector2 b, out Vector2 result) { result.X = a.X > b.X ? a.X : b.X; result.Y = a.Y > b.Y ? a.Y : b.Y; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The dot product of the two inputs</returns> public static float Dot(Vector2 left, Vector2 right) { return left.X * right.X + left.Y * right.Y; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <param name="result">The dot product of the two inputs</param> public static void Dot(ref Vector2 left, ref Vector2 right, out float result) { result = left.X * right.X + left.Y * right.Y; } /// <summary> /// Calculates the distance between two points described by two vectors. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static float Distance(ref Vector2 left, ref Vector2 right) { Vector2 diff; diff.X = left.X - right.X; diff.Y = left.Y - right.Y; return (float)Math.Sqrt(diff.X * diff.X + diff.Y * diff.Y); } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns> public static Vector2 Lerp(Vector2 a, Vector2 b, float blend) { a.X = blend * (b.X - a.X) + a.X; a.Y = blend * (b.Y - a.Y) + a.Y; return a; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param> public static void Lerp(ref Vector2 a, ref Vector2 b, float blend, out Vector2 result) { result.X = blend * (b.X - a.X) + a.X; result.Y = blend * (b.Y - a.Y) + a.Y; } /// <summary> /// Calculates the angle (in radians) between two vectors. /// </summary> /// <param name="first">The first vector.</param> /// <param name="second">The second vector.</param> /// <returns>Angle (in radians) between the vectors.</returns> /// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks> public static float AngleBetween(Vector2 first, Vector2 second) { return (float)System.Math.Acos((Vector2.Dot(first, second)) / (first.Length * second.Length)); } /// <summary> /// Calculates the angle (in radians) between two vectors. /// </summary> /// <param name="first">The first vector.</param> /// <param name="second">The second vector.</param> /// <param name="result">Angle (in radians) between the vectors.</param> /// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks> public static void AngleBetween(ref Vector2 first, ref Vector2 second, out float result) { float temp; Vector2.Dot(ref first, ref second, out temp); result = (float)System.Math.Acos(temp / (first.Length * second.Length)); } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector2 Transform(Vector2 vec, Quaternion quat) { Vector2 result; Transform(ref vec, ref quat, out result); return result; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector2 vec, ref Quaternion quat, out Vector2 result) { Quaternion v = new Quaternion(vec.X, vec.Y, 0, 0), i, t; Quaternion.Invert(ref quat, out i); Quaternion.Multiply(ref quat, ref v, out t); Quaternion.Multiply(ref t, ref i, out v); result = new Vector2(v.X, v.Y); } /// <summary> /// Transforms the vector /// </summary> /// <param name="vec"></param> /// <param name="mat"></param> /// <returns></returns> public static Vector2 Transform(Vector2 vec, Matrix4 mat) { Vector2 result; Transform(ref vec, ref mat, out result); return result; } /// <summary> /// Transforms the vector /// </summary> /// <param name="vec"></param> /// <param name="mat"></param> /// <param name="result"></param> /// <returns></returns> public static void Transform(ref Vector2 vec, ref Matrix4 mat, out Vector2 result) { Vector4 row0 = mat.Row0; Vector4 row1 = mat.Row1; Vector4 row3 = mat.Row3; result.X = vec.X * row0.X + vec.Y * row1.X + row3.X; result.Y = vec.X * row0.Y + vec.Y * row1.Y + row3.Y; } /// <summary> /// Adds the specified instances. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>Result of addition.</returns> public static Vector2 operator +(Vector2 left, Vector2 right) { left.X += right.X; left.Y += right.Y; return left; } /// <summary> /// Subtracts the specified instances. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>Result of subtraction.</returns> public static Vector2 operator -(Vector2 left, Vector2 right) { left.X -= right.X; left.Y -= right.Y; return left; } /// <summary> /// Negates the specified instance. /// </summary> /// <param name="vec">Operand.</param> /// <returns>Result of negation.</returns> public static Vector2 operator -(Vector2 vec) { vec.X = -vec.X; vec.Y = -vec.Y; return vec; } /// <summary> /// Multiplies the specified instance by a scalar. /// </summary> /// <param name="vec">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of multiplication.</returns> public static Vector2 operator *(Vector2 vec, float scale) { vec.X *= scale; vec.Y *= scale; return vec; } /// <summary> /// Multiplies the specified instance by a scalar. /// </summary> /// <param name="scale">Left operand.</param> /// <param name="vec">Right operand.</param> /// <returns>Result of multiplication.</returns> public static Vector2 operator *(float scale, Vector2 vec) { vec.X *= scale; vec.Y *= scale; return vec; } /// <summary> /// Scales the specified instance by a vector. /// </summary> /// <param name="vec">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of multiplication.</returns> public static Vector2 operator *(Vector2 vec, Vector2 scale) { vec.X *= scale.X; vec.Y *= scale.Y; return vec; } /// <summary> /// Divides the specified instance by a scalar. /// </summary> /// <param name="vec">Left operand</param> /// <param name="scale">Right operand</param> /// <returns>Result of the division.</returns> public static Vector2 operator /(Vector2 vec, float scale) { float mult = 1.0f / scale; vec.X *= mult; vec.Y *= mult; return vec; } /// <summary> /// Divides the specified instance by a vector. /// </summary> /// <param name="vec">Left operand</param> /// <param name="scale">Right operand</param> /// <returns>Result of the division.</returns> public static Vector2 operator /(Vector2 vec, Vector2 scale) { vec.X /= scale.X; vec.Y /= scale.Y; return vec; } /// <summary> /// Compares the specified instances for equality. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>True if both instances are equal; false otherwise.</returns> public static bool operator ==(Vector2 left, Vector2 right) { return left.Equals(right); } /// <summary> /// Compares the specified instances for inequality. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>True if both instances are not equal; false otherwise.</returns> public static bool operator !=(Vector2 left, Vector2 right) { return !left.Equals(right); } /// <summary> /// Returns a System.String that represents the current Vector2. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("({0:F}, {1:F})", X, Y); } /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Vector2)) return false; return this.Equals((Vector2)obj); } /// <summary> /// Indicates whether the current vector is equal to another vector. /// </summary> /// <param name="other">A vector to compare with this vector.</param> /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> public bool Equals(Vector2 other) { return X == other.X && Y == other.Y; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.Contracts; using Microsoft.Research.ClousotRegression; [assembly: RegressionOutcome("Detected call to method 'PureFunction.ImpureDelegate.Invoke(System.Int32)' without [Pure] in contracts of method 'PureFunction.DelegateTests.Test1(PureFunction.ImpureDelegate,System.Int32)'.")] //[assembly: RegressionOutcome("Detected call to method 'PureFunction.ImpureDelegate.Invoke(System.Int32)' without [Pure] in contracts of method 'PureFunction.DelegateTests.Test5(System.Int32)'.")] [assembly: RegressionOutcome("Detected call to method 'System.Comparison`1<System.Int32>.Invoke(System.Int32,System.Int32)' without [Pure] in contracts of method 'PureFunction.DelegateTests.Test3(System.Comparison`1<System.Int32>,System.Int32)'.")] namespace PureFunction { class C { [Pure] [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 9, MethodILOffset = 20)] public int P() { Contract.Ensures(Contract.Result<int>() == 3); return 3; } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 2, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"ensures is false: Contract.Result<int>() == 4", PrimaryILOffset = 24, MethodILOffset = 35)] public int M(int x) { Contract.Requires(P() == x); Contract.Ensures(Contract.Result<int>() == 4); return x; } [Pure] public int Binary(int x, int y) { return x + y; } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 4, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 21, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 29, MethodILOffset = 0)] public void TestBinaryPredicate(int x, int y) { Contract.Requires(Binary(x, y) > 0); Contract.Assert(Binary(x, y) > 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 4, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 44, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 52, MethodILOffset = 0)] public int TestBinaryPredicate2(int x, int y) { Contract.Requires(Binary(x, y) > 0); int z; if (x < y) { z = 55; } else { z = 77; } Contract.Assert(Binary(x, y) > 0); return z; } } class Tests { [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 7, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 10, MethodILOffset = 7)] static void TestMain() { new C().M(3); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 25, MethodILOffset = 0)] static void TestBinary1(int x, int y) { Contract.Requires(x * y >= 0); Contract.Assert(x * y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 25, MethodILOffset = 0)] static void TestBinary2(int x, int y) { Contract.Requires(x / y >= 0); Contract.Assert(x / y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 25, MethodILOffset = 0)] static void TestBinary3(int x, int y) { Contract.Requires(x + y >= 0); Contract.Assert(x + y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 25, MethodILOffset = 0)] static void TestBinary4(int x, int y) { Contract.Requires(x - y >= 0); Contract.Assert(x - y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 25, MethodILOffset = 0)] static void TestBinary5(int x, int y) { Contract.Requires(x % y >= 0); Contract.Assert(x % y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 29, MethodILOffset = 0)] static void TestBinary6(int x, int y) { Contract.Requires(-x * -y >= 0); Contract.Assert(-x * -y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 29, MethodILOffset = 0)] static void TestBinary7(int x, int y) { Contract.Requires(-x / -y >= 0); Contract.Assert(-x / -y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 29, MethodILOffset = 0)] static void TestBinary8(int x, int y) { Contract.Requires(-x + -y >= 0); Contract.Assert(-x + -y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 29, MethodILOffset = 0)] static void TestBinary9(int x, int y) { Contract.Requires(-x - -y >= 0); Contract.Assert(-x - -y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 29, MethodILOffset = 0)] static void TestBinary10(int x, int y) { Contract.Requires(-x % -y >= 0); Contract.Assert(-x % -y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 33, MethodILOffset = 0)] static void TestBinary1(float x, float y) { Contract.Requires(x * y >= 0); Contract.Assert(x * y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 33, MethodILOffset = 0)] static void TestBinary2(float x, float y) { Contract.Requires(x / y >= 0); Contract.Assert(x / y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 33, MethodILOffset = 0)] static void TestBinary3(float x, float y) { Contract.Requires(x + y >= 0); Contract.Assert(x + y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 33, MethodILOffset = 0)] static void TestBinary4(float x, float y) { Contract.Requires(x - y >= 0); Contract.Assert(x - y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 33, MethodILOffset = 0)] static void TestBinary5(float x, float y) { Contract.Requires(x % y >= 0); Contract.Assert(x % y >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 39, MethodILOffset = 0)] static void TestBinary1(int x, int y, int z) { Contract.Requires(x * -y - z * (x - y) >= 0); Contract.Assert(x * -y - z * (x - y) >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 39, MethodILOffset = 0)] static void TestBinary2(int x, int y, int z) { Contract.Requires(x / -y - z * (x - y) >= 0); Contract.Assert(x / -y - z * (x - y) >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 39, MethodILOffset = 0)] static void TestBinary3(int x, int y, int z) { Contract.Requires(x + -y - z * (x - y) >= 0); Contract.Assert(x + -y - z * (x - y) >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 39, MethodILOffset = 0)] static void TestBinary4(int x, int y, int z) { Contract.Requires(x - -y - z * (x - y) >= 0); Contract.Assert(x - -y - z * (x - y) >= 0); } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 39, MethodILOffset = 0)] static void TestBinary5(int x, int y, int z) { Contract.Requires(x % -y - z * (x - y) >= 0); Contract.Assert(x % -y - z * (x - y) >= 0); } } class PropertySetAndGet { public int InstanceProp { get; set; } public static int StaticProp { get; set; } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 9, MethodILOffset = 22)] public static void TestStatic(int x) { Contract.Ensures(StaticProp == x); StaticProp = x; } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 18, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 2, MethodILOffset = 24)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 10, MethodILOffset = 24)] public void TestInstance(int x) { Contract.Ensures(InstanceProp == x); InstanceProp = x; } } public delegate bool ImpureDelegate(int x); [Pure] public delegate bool PureDelegate(int x); [Pure] public delegate bool PureBinaryDelegate(int x, int y); public class DelegateTests { public PureDelegate pd1; public ImpureDelegate ipd1; public Comparison<int> comp; public Predicate<int> pred; public void Test1(ImpureDelegate d, int x) { Contract.Requires(d(x)); } public void Test2(PureDelegate d, int x) { Contract.Requires(d(x)); } public void Test3(Comparison<int> d, int x) { Contract.Requires(d(x,0) == 0); } public void Test4(Predicate<int> d, int x) { Contract.Requires(d(x)); } public void Test5(int x) { Contract.Requires(this.ipd1(x)); } public void Test6(int x) { Contract.Requires(this.pd1(x)); } public void Test7(int x) { Contract.Requires(this.comp(x, 0) == 0); } public void Test8(int x) { Contract.Requires(this.pred(x)); } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Possibly calling a method on a null reference 'd'", PrimaryILOffset = 4, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 18, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 23, MethodILOffset = 0)] public void Test9(PureBinaryDelegate d, int x, int y) { Contract.Requires(d(x, y)); Contract.Assert(d(x, y)); } } class MultiVariableJoins { [Pure] private static bool EndsWith(string source, string suffix) { return source.EndsWith(suffix); } [Pure] private static string TrimSuffix(string source, string suffix) { return source; } [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 15, MethodILOffset = 50)] public string TrimSuffixFully(string source, string suffix) { Contract.Ensures(!EndsWith(Contract.Result<string>(), suffix)); while (EndsWith(source, suffix)) { source = TrimSuffix(source, suffix); } return source; } } class PureFunctionsAndMutation { [Pure] public bool Contains<T>(T x) { return true; } public void Add<T>(T x) { Contract.Ensures(Contains(x)); } public void Remove<T>(T x) { } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 16, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 29, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 54, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 62, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 75, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 83, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 101, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 34, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven", PrimaryILOffset = 67, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 88, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 106, MethodILOffset = 0)] public static void Test(PureFunctionsAndMutation pf, int x) { Contract.Requires(pf != null); Contract.Requires(pf.Contains(x)); Contract.Assert(pf.Contains(x)); if (x > 5) { pf.Remove(x); Contract.Assert(pf.Contains(x)); // should be false pf.Add(x); Contract.Assert(pf.Contains(x)); // should be true } else { } Contract.Assert(pf.Contains(x)); // should be true } } class PureFunctionsAndOutParameters { [ClousotRegressionTest("regular")] [RegressionOutcome(Outcome=ProofOutcome.True,Message="assert is valid",PrimaryILOffset=34,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="assert is valid",PrimaryILOffset=44,MethodILOffset=0)] static void Main2() { object x; int y = Get(out x); Contract.Assume(x != null); int z; object w; z = Get(out w); Contract.Assert(z == y); Contract.Assert(x == w); } [Pure] static int Get(out object x) { x = new object(); return 0; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace oct01securitybasic.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Xml; using System.IO; using System.Text; using System.Timers; using Mono.TextEditor; using Mono.TextEditor.Highlighting; using Mono.TextEditor.Theatrics; using Mono.TextEditor.Vi; using Mono.TextEditor.PopupWindow; using Moscrif.IDE.Components; using Moscrif.IDE.Actions; using Moscrif.IDE.Task; using Moscrif.IDE.Editors.SourceEditorActions; using IdeBookmarkActions = Moscrif.IDE.Editors.SourceEditorActions.BookmarkActions; using IdeBreakpointActions = Moscrif.IDE.Editors.SourceEditorActions.BreakpointActions; using IdeAutocompleteAction = Moscrif.IDE.Editors.SourceEditorActions.AutoCompleteActions; using IdeEditAction = Moscrif.IDE.Editors.SourceEditorActions.EditAction; using Moscrif.IDE.Completion; using Moscrif.IDE.Controls; using Moscrif.IDE.Option; using Moscrif.IDE.Workspace; using Moscrif.IDE.Iface.Entities; using MessageDialogs = Moscrif.IDE.Controls.MessageDialog; namespace Moscrif.IDE.Editors { public class SourceEditor : Gtk.Frame, IEditor { private string fileName = String.Empty; private bool modified = false; //private TypeEditor typeEditor = TypeEditor.TextEditor; private TextEdit editor = null; private Gtk.Widget control = null; private Gtk.ActionGroup editorAction = null; private bool isCompileExtension = false; //private string statusFormat ="Ln: {0}; Col: {1}"; private string statusFormat ="Ln: {0}; Col: {1}; In: {2}"; private List<ErrorMarker> errors; //private CodeCompletionContext currentCompletionContext; private DateTime lastPrecompile; private Timer timer = new Timer(); private IdeBookmarkActions bookmarkActions; private IdeBreakpointActions breakpointActions; private IdeAutocompleteAction autoCompleteActions; private IdeEditAction editAction; private bool onlyRead = false; private SearchPattern searchPattern; private FileSetting fileSeting; public SourceEditor(string filePath) { if(MainClass.Settings.SourceEditorSettings == null){ MainClass.Settings.SourceEditorSettings = new Moscrif.IDE.Option.Settings.SourceEditorSetting(); } errors = new List<ErrorMarker>(); lastPrecompile = DateTime.Now; control = new Gtk.ScrolledWindow(); (control as Gtk.ScrolledWindow).ShadowType = Gtk.ShadowType.Out; editorAction = new Gtk.ActionGroup("sourceeditor"); searchPattern = null; editor = new TextEdit(); LoadSetting(); SyntaxMode mode = new SyntaxMode(); string extension = System.IO.Path.GetExtension(filePath); //editor.AccelCanActivate switch (extension) { case ".ms": { try{ mode = SyntaxModeService.GetSyntaxMode("text/moscrif"); }catch(Exception ex){ MessageDialogs msd = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("error_load_syntax"), MainClass.Languages.Translate("error_load_syntax_f1"), Gtk.MessageType.Error,null); msd.ShowDialog(); Tool.Logger.Error(ex.Message); } isCompileExtension = true; (editor as ICompletionWidget).BanCompletion = false; break; } case ".js": { try{ mode = SyntaxModeService.GetSyntaxMode("text/x-java"); }catch(Exception ex){ MessageDialogs msd = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("error_load_syntax"), MainClass.Languages.Translate("error_load_syntax_f1"), Gtk.MessageType.Error,null); msd.ShowDialog(); Tool.Logger.Error(ex.Message); } isCompileExtension = true; (editor as ICompletionWidget).BanCompletion = false; break; } case ".mso": { try{ mode = SyntaxModeService.GetSyntaxMode("text/moscrif"); }catch(Exception ex){ MessageDialogs msd = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("error_load_syntax"), MainClass.Languages.Translate("error_load_syntax_f1"), Gtk.MessageType.Error,null); msd.ShowDialog(); Tool.Logger.Error(ex.Message); } isCompileExtension = true; break; } case ".xml": { mode = SyntaxModeService.GetSyntaxMode("application/xml"); break; } case ".txt": case ".app": break; default: break; } //editor.Document. editor.Document.SyntaxMode = mode; //modified = true; editor.Document.LineChanged += delegate(object sender, LineEventArgs e) { OnBookmarkUpdate(); OnModifiedChanged(true); }; editor.Caret.PositionChanged+= delegate(object sender, DocumentLocationEventArgs e) { OnWriteToStatusbar(String.Format(statusFormat,editor.Caret.Location.Line+1,editor.Caret.Location.Column,editor.Caret.Offset)); }; FileAttributes fa = File.GetAttributes(filePath); if ((fa & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { onlyRead = true; //editor.Document.ReadOnly= true; } try { using (StreamReader file = new StreamReader(filePath)) { editor.Document.Text = file.ReadToEnd(); file.Close(); file.Dispose(); } } catch (Exception ex) { MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("file_cannot_open", filePath), ex.Message, Gtk.MessageType.Error,null); ms.ShowDialog(); return; } //Console.WriteLine(editor.Document.Text.Replace("\r","^").Replace("\n","$")); (control as Gtk.ScrolledWindow).Add(editor); control.ShowAll(); fileName = filePath; fileSeting = MainClass.Workspace.WorkspaceUserSetting.FilesSetting.Find(x=> x.FileName == fileName); if(fileSeting == null) fileSeting = new FileSetting( fileName ); editor.TextViewMargin.ButtonPressed += OnTextMarginButtonPress; editor.IconMargin.ButtonPressed += OnIconMarginButtonPress; //editor.KeyPressEvent += OnKeyPressEvent; editor.KeyReleaseEvent += OnKeyReleaseEvent; editor.ButtonPressEvent += OnButtonPressEvent; bookmarkActions = new IdeBookmarkActions(editor,fileSeting); breakpointActions = new IdeBreakpointActions(editor); autoCompleteActions = new IdeAutocompleteAction(editor, editor); editAction = new IdeEditAction(editor); Gtk.Action act = new Gtk.Action("sourceeditor_togglebookmark", ""); act.Activated += bookmarkActions.ToggleBookmark; editorAction.Add(act); Gtk.Action act2 = new Gtk.Action("sourceeditor_clearbookmark", ""); act2.Activated += bookmarkActions.ClearBookmarks; editorAction.Add(act2); Gtk.Action act3 = new Gtk.Action("sourceeditor_nextbookmark", ""); act3.Activated += bookmarkActions.NextBookmark; editorAction.Add(act3); Gtk.Action act4 = new Gtk.Action("sourceeditor_prevbookmark", ""); act4.Activated += bookmarkActions.PreviousBookmark; editorAction.Add(act4); Gtk.Action act5 = new Gtk.Action("sourceeditor_addbreakpoint", ""); act5.Activated += breakpointActions.AddBreakpoints; editorAction.Add(act5); Gtk.Action act6 = new Gtk.Action("sourceeditor_inserttemplate", ""); act6.Activated += autoCompleteActions.InsertTemplate; editorAction.Add(act6); Gtk.Action act7 = new Gtk.Action("sourceeditor_insertautocomplete", ""); act7.Activated += autoCompleteActions.InsertCompletion; editorAction.Add(act7); Gtk.Action act8 = new Gtk.Action("sourceeditor_pasteClipboard", ""); act8.Activated += editAction.PasteText; editorAction.Add(act8); Gtk.Action act9 = new Gtk.Action("sourceeditor_copyClipboard", ""); act9.Activated += editAction.CopyText; editorAction.Add(act9); Gtk.Action act10 = new Gtk.Action("sourceeditor_cutClipboard", ""); act10.Activated += editAction.CutText; editorAction.Add(act10); Gtk.Action act11 = new Gtk.Action("sourceeditor_gotoDefinition", ""); act11.Activated += editAction.GoToDefinition; editorAction.Add(act11); Gtk.Action act12 = new Gtk.Action("sourceeditor_commentUncomment", ""); act12.Activated += editAction.CommentUncomment; editorAction.Add(act12); List<FoldSegment> list = editor.GetFolding(); foreach(SettingValue sv in fileSeting.Folding){ FoldSegment foldS = list.Find(x=>x.Offset.ToString() == sv.Display); if(foldS != null){ bool isfolding = false; if( Boolean.TryParse(sv.Value, out isfolding)) foldS.IsFolded = isfolding; } } this.editor.Document.UpdateFoldSegments(list,true); //foreach (int bm in fileSeting.Bookmarks){ foreach (MyBookmark bm in fileSeting.Bookmarks2){ LineSegment ls = this.editor.Document.GetLine(bm.Line); if(ls != null) ls.IsBookmarked = true; //this.editor.Document.Lines[bm].IsBookmarked = true; } } /* int j = 1; for (int i = 1; i <= insertObject.Document.LineCount; i++) { LineSegment ls = insertObject.Document.GetLine(i); if (ls != null) { if (j == 1) { ErrorMarker er = new ErrorMarker(ls); er.AddToLine(insertObject.Document); j++; } else if (j == 2) { TextMarker bm = new BreakpointTextMarker(insertObject, false); //DebugTextMarker tm = new DebugTextMarker((insertObject as TextEditor)); insertObject.Document.AddMarker(ls, bm); insertObject.QueueDraw(); j++; } else { if (ls.IsBookmarked != true) { //int lineNumber = insertObject.Document.OffsetToLineNumber (ls.Offset); ls.IsBookmarked = true; insertObject.Document.RequestUpdate(new LineUpdate(i)); insertObject.Document.CommitDocumentUpdate(); } j = 1; } } }*/ void OnTextMarginButtonPress(object s, MarginMouseEventArgs args) { if (args.Button == 3){ Selection sel = editor.MainSelection; editor.Caret.Line = args.LineNumber; DocumentLocation dl = editor.VisualToDocumentLocation(args.X, args.Y); editor.Caret.Location = dl; if((sel!= null) && (args.LineNumber >= sel.MinLine && args.LineNumber <= sel.MaxLine)) editor.MainSelection = sel; if (args.LineSegment != null) { Gtk.Menu popupMenu = (Gtk.Menu)MainClass.MainWindow.ActionUiManager.GetWidget("/textMarginPopup"); if (popupMenu != null) { Gtk.Action act = MainClass.MainWindow.ActionUiManager.FindActionByName("gotodefinition"); if (act!= null){ act.Visible = false; string caretWord = editor.GetCarretWord(); //Console.WriteLine("caretWord ->"+caretWord ); if(!String.IsNullOrEmpty(caretWord)){ int indx = MainClass.CompletedCache.ListDataTypes.FindIndex(x=>x.DisplayText == caretWord); if(indx>-1){ act.Visible = true; } } //act.Visible = false; //act.Sensitive = false; } //popupMenu.ShowAll(); popupMenu.Popup(); } } } } //private TaskList tl = new TaskList(); [GLib.ConnectBefore] void OnKeyReleaseEvent(object s, Gtk.KeyReleaseEventArgs args) { if (args.Event.Key == Gdk.Key.Left || args.Event.Key == Gdk.Key.Right || args.Event.Key == Gdk.Key.Up || args.Event.Key == Gdk.Key.Down || args.Event.Key == Gdk.Key.Control_L || args.Event.Key == Gdk.Key.Control_R) return; //return; if (MainClass.Settings.PreCompile && isCompileExtension ) { DateTime now = DateTime.Now; TimeSpan ts = now.Subtract(lastPrecompile); if (ts.TotalMilliseconds > 5500) { //MainClass.MainWindow.ErrorOutput.Clear(); TaskList tl = new TaskList(); tl.TasksList = new System.Collections.Generic.List<Moscrif.IDE.Task.ITask>(); PrecompileTask pt = new PrecompileTask(); pt.Initialize(new PrecompileData(editor.Document.Text, fileName)); tl.TasksList.Clear(); tl.TasksList.Add(pt); MainClass.MainWindow.RunSecondaryTaskList(tl, EndTaskWritte,true); lastPrecompile = DateTime.Now; timer.Enabled = false; } } } private void OnTimeElapsed(object o, ElapsedEventArgs args) { DateTime now = DateTime.Now; TimeSpan ts = now.Subtract(lastPrecompile); if (ts.TotalMilliseconds > 5000) { timer.Enabled = false; TaskList tl = new TaskList(); tl.TasksList = new System.Collections.Generic.List<Moscrif.IDE.Task.ITask>(); PrecompileTask pt = new PrecompileTask(); pt.Initialize(new PrecompileData(editor.Document.Text, fileName)); tl.TasksList.Clear(); tl.TasksList.Add(pt); MainClass.MainWindow.RunSecondaryTaskList(tl, EndTaskWritte,true); lastPrecompile = DateTime.Now; } } public void OnBookmarkUpdate () { //FileSetting fs = MainClass.Workspace.WorkspaceUserSetting.FilesSetting.Find(x=> x.FileName == fileName); fileSeting.Bookmarks2 = new List<MyBookmark>();//new List<int>(); foreach (LineSegment ls in this.editor.Document.Lines){ if(ls.IsBookmarked){ int lineNumber = this.editor.Document.OffsetToLineNumber(ls.Offset); string text = this.editor.Document.GetTextBetween(ls.Offset,ls.EndOffset); fileSeting.Bookmarks2.Add(new MyBookmark(lineNumber,text.Trim())); } } MainClass.MainWindow.BookmarkOutput.RefreshBookmark(); } public void EndTaskWritte(object sender, string name, string status, List<TaskMessage> taskMessage) { Gtk.Application.Invoke(delegate { try { foreach (ErrorMarker er in errors) er.RemoveFromLine(editor.Document);//editor.Document.RemoveMarker(er.Line,typeof(ErrorMarker)); errors.Clear(); if (taskMessage != null) { foreach (TaskMessage tm in taskMessage) { LineSegment ls = editor.Document.GetLine(Convert.ToInt32(tm.Line) - 1); ErrorMarker er = new ErrorMarker(ls); er.AddToLine(editor.Document); errors.Add(er); } } else { Console.WriteLine("Output NULL"); } } catch (Exception ex) { //Tool.Logger.Error(ex.Message, null); Tool.Logger.Error(ex.Message); Tool.Logger.Error(ex.StackTrace); Tool.Logger.Error(ex.Source); } }); } private void LoadSetting(){ TextEditorOptions options = new TextEditorOptions(); options.ColorScheme = "Moscrif"; options.ShowInvalidLines = true; options.ShowLineNumberMargin = true; options.AutoIndent = true; options.TabSize = MainClass.Settings.SourceEditorSettings.TabSpace;//8; options.TabsToSpaces= MainClass.Settings.SourceEditorSettings.TabsToSpaces; options.ShowEolMarkers =MainClass.Settings.SourceEditorSettings.ShowEolMarker; options.ShowRuler =MainClass.Settings.SourceEditorSettings.ShowRuler; options.RulerColumn = MainClass.Settings.SourceEditorSettings.RulerColumn; options.ShowTabs=MainClass.Settings.SourceEditorSettings.ShowTab; options.ShowSpaces=MainClass.Settings.SourceEditorSettings.ShowSpaces; options.EnableAnimations=MainClass.Settings.SourceEditorSettings.EnableAnimations; options.ShowLineNumberMargin =MainClass.Settings.SourceEditorSettings.ShowLineNumber; options.HighlightCaretLine = true; options.DefaultEolMarker = "\n"; options.OverrideDocumentEolMarker= true; if (!String.IsNullOrEmpty(MainClass.Settings.SourceEditorSettings.EditorFont)) options.FontName = MainClass.Settings.SourceEditorSettings.EditorFont; try{//check parse style Mono.TextEditor.Highlighting.Style style = SyntaxModeService.GetColorStyle(null, "Moscrif"); }catch(Exception ex){ options.ColorScheme = ""; //MessageDialogs msd = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("error_load_styles"),ex.Message, Gtk.MessageType.Error,null); //msd.ShowDialog(); Tool.Logger.Error(MainClass.Languages.Translate("error_load_styles")); Tool.Logger.Error(ex.Message); } editor.Options = options; // editor.Options.ShowFoldMargin = true; } void OnButtonPressEvent(object o, Gtk.ButtonPressEventArgs args) { //if (currentCompletionContext != null) { CompletionWindowManager.HideWindow(); //} } void OnIconMarginButtonPress(object s, MarginMouseEventArgs args) { if (args.Button == 3) { editor.Caret.Line = args.LineNumber; editor.Caret.Column = 1; Gtk.Menu popupMenu = (Gtk.Menu)MainClass.MainWindow.ActionUiManager.GetWidget("/iconMarginPopup"); if (popupMenu != null) { popupMenu.ShowAll(); popupMenu.Popup(); } } else if (args.Button == 1) if (!string.IsNullOrEmpty(FileName)) { if (args.LineSegment != null) { //DebuggingService.Breakpoints.Toggle (this.Document.FileName, args.LineNumber + 1); //AddBreakpoints(args.LineSegment); } } } private void AddBreakpoints(LineSegment line) { if (line != null) { TextMarker bm = new BreakpointTextMarker(editor, false); editor.Document.AddMarker(line, bm); editor.QueueDraw(); } } private void SetSearchPattern(SearchPattern sp) { searchPattern = sp; Mono.TextEditor.SearchRequest sr = new Mono.TextEditor.SearchRequest(); sr.CaseSensitive = searchPattern.CaseSensitive; sr.SearchPattern = searchPattern.Expresion.ToString(); sr.WholeWordOnly = searchPattern.WholeWorlds; this.editor.SearchEngine.SearchRequest = sr; } void GotoResult(SearchResult result) { try { if (result == null) { this.editor.ClearSelection(); return; } this.editor.Caret.Offset = result.Offset; this.editor.SetSelection(result.Offset, result.EndOffset); this.editor.CenterToCaret(); this.editor.AnimateSearchResult(result); //this.editor.QueueDraw (); } catch (System.Exception) { } } #region IEditor public string Caption { get { return System.IO.Path.GetFileName(fileName); } } public string FileName { get { return fileName; } } public bool Modified { get { return modified; } } public bool RefreshSettings(){ LoadSetting(); return true; } public void Rename(string newName){ fileName = newName; } public void GoToPosition(object position) { int pos = 0; if( position.GetType() == typeof(string)){ // offset Console.WriteLine("string"); if (Int32.TryParse(position.ToString(), out pos)) { position = this.editor.Document.OffsetToLineNumber(pos)+1; //position=position+1; } } // line if (Int32.TryParse(position.ToString(), out pos)) { int line = Convert.ToInt32(pos); if (line < 0) line = 0; if (line > editor.Document.LineCount) line = editor.Document.LineCount; Caret caret = editor.Caret; DocumentLocation dl = new DocumentLocation(line - 1, 0); caret.Location = dl; editor.ScrollToCaret(); } } public object GetSelected(){ string selTxt = this.editor.SelectedText; if(String.IsNullOrEmpty(selTxt)) return null; else return selTxt; } public bool SearchExpression(SearchPattern expresion) { this.editor.HighlightSearchPattern = true; this.editor.TextViewMargin.RefreshSearchMarker(); SetSearchPattern(expresion); //Mono.TextEditor.SearchResult ser = this.editor.FindNext(true); SearchResult sr = this.editor.SearchForward(this.editor.Document.LocationToOffset(this.editor.Caret.Location)); GotoResult(sr); //this.editor.GrabFocus (); return true; } public bool SearchNext(SearchPattern expresion) { if (expresion != null) { SetSearchPattern(expresion); this.editor.FindNext(true); return true; } return false; } public bool SearchPreviu(SearchPattern expresion) { if (expresion != null) { SetSearchPattern(expresion); this.editor.FindPrevious(true); return true; } return false; } public bool Replace(SearchPattern expresion) { if (expresion != null) { SetSearchPattern(expresion); return this.editor.Replace(expresion.ReplaceExpresion.ToString()); } return false; } public bool ReplaceAll(SearchPattern expresion) { if (expresion != null) { SetSearchPattern(expresion); int number = this.editor.ReplaceAll(expresion.ReplaceExpresion.ToString()); this.editor.QueueDraw(); if (number == 0) { return false; } return true; } return false; } public List<FindResult> FindReplaceAll(SearchPattern searchPattern) { return this.editor.FindReplaceAll(searchPattern); } /* if((fa & FileAttributes.Directory) == FileAttributes.ReadOnly) editor.Document.ReadOnly= true;*/ public bool Save() { if (onlyRead) return false; if (!modified) return true; try { using (StreamWriter file = new StreamWriter(fileName)) { file.Write(editor.Document.Text); file.Close(); file.Dispose(); } OnModifiedChanged(false); } catch (Exception ex) { MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("cannot_save_file",fileName), ex.Message, Gtk.MessageType.Error); ms.ShowDialog(); return false; } // do save return true; // alebo true ak je OK } public bool SaveAs(string newPath) { if (File.Exists(newPath)) { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.YesNo, "", MainClass.Languages.Translate("overwrite_file", newPath), Gtk.MessageType.Question); int result = md.ShowDialog(); if (result != (int)Gtk.ResponseType.Yes) return false; } try { using (StreamWriter file = new StreamWriter(newPath)) { file.Write(editor.Document.Text); file.Close(); file.Dispose(); } OnModifiedChanged(false); fileName = newPath; onlyRead = false; } catch (Exception ex) { MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("cannot_save_file", newPath), ex.Message, Gtk.MessageType.Error); ms.ShowDialog(); return false; } // do save return true; // alebo true ak je OK } public void Close() { if(MainClass.Workspace != null){ if(MainClass.Workspace.WorkspaceUserSetting.FilesSetting == null) MainClass.Workspace.WorkspaceUserSetting.FilesSetting = new List<FileSetting>(); //FileSetting fs = MainClass.Workspace.WorkspaceUserSetting.FilesSetting.Find(x=> x.FileName == fileName); if(fileSeting!=null) MainClass.Workspace.WorkspaceUserSetting.FilesSetting.Remove(fileSeting); fileSeting = new FileSetting( fileName ); foreach (FoldSegment fold in this.editor.Document.FoldSegments){ SettingValue sv = new SettingValue(fold.IsFolded.ToString(),fold.Offset.ToString()); fileSeting.Folding.Add(sv); } fileSeting.Bookmarks2 = new List<MyBookmark>(); //new List<int>(); foreach (LineSegment ls in this.editor.Document.Lines){ if(ls.IsBookmarked){ int lineNumber = this.editor.Document.OffsetToLineNumber(ls.Offset); string text = this.editor.Document.GetTextBetween(ls.Offset,ls.EndOffset); fileSeting.Bookmarks2.Add(new MyBookmark(lineNumber,text.Trim())); } } MainClass.Workspace.WorkspaceUserSetting.FilesSetting.Add(fileSeting); //this.editor.IconMargin. } } public bool Undo() { if (!editor.Document.CanUndo) return true; try { editor.Document.Undo(); } catch (Exception ex) { throw ex; //return false; } // do save return true; // alebo true ak je OK } public bool Redo() { if (!editor.Document.CanRedo) return true; try { editor.Document.Redo(); } catch (Exception ex) { throw ex; //return false; } // do save return true; // alebo true ak je OK } public Gtk.Widget Control { get { return control; } } public Gtk.ActionGroup EditorAction { get { return editorAction; } } public event EventHandler<ModifiedChangedEventArgs> ModifiedChanged; public event EventHandler<WriteStatusEventArgs> WriteStatusChange; void OnModifiedChanged(bool newModified) { if (newModified != modified) modified = newModified; else return; ModifiedChangedEventArgs mchEventArg = new ModifiedChangedEventArgs(modified); if (ModifiedChanged != null) ModifiedChanged(this, mchEventArg); } void OnWriteToStatusbar(string message) { WriteStatusEventArgs mchEventArg = new WriteStatusEventArgs(message); if (WriteStatusChange != null) WriteStatusChange(this, mchEventArg); } public void ActivateEditor(bool updateStatus){ editor.ShowWidget(); if(updateStatus){ OnWriteToStatusbar(String.Format(statusFormat,editor.Caret.Location.Line+1,editor.Caret.Location.Column,editor.Caret.Offset)); } } #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.Collections.Generic; using System.Reflection.Metadata.Ecma335; using Xunit; namespace System.Reflection.Metadata.Tests { public class HandleTests { [Fact] public void HandleConversionGivesCorrectKind() { var expectedKinds = new SortedSet<HandleKind>((HandleKind[])Enum.GetValues(typeof(HandleKind))); Action<Handle, HandleKind> assert = (handle, expectedKind) => { Assert.False(expectedKinds.Count == 0, "Repeat handle in tests below."); Assert.Equal(expectedKind, handle.Kind); expectedKinds.Remove(expectedKind); }; assert(default(ModuleDefinitionHandle), HandleKind.ModuleDefinition); assert(default(AssemblyDefinitionHandle), HandleKind.AssemblyDefinition); assert(default(InterfaceImplementationHandle), HandleKind.InterfaceImplementation); assert(default(MethodDefinitionHandle), HandleKind.MethodDefinition); assert(default(MethodSpecificationHandle), HandleKind.MethodSpecification); assert(default(TypeDefinitionHandle), HandleKind.TypeDefinition); assert(default(ExportedTypeHandle), HandleKind.ExportedType); assert(default(TypeReferenceHandle), HandleKind.TypeReference); assert(default(TypeSpecificationHandle), HandleKind.TypeSpecification); assert(default(MemberReferenceHandle), HandleKind.MemberReference); assert(default(FieldDefinitionHandle), HandleKind.FieldDefinition); assert(default(EventDefinitionHandle), HandleKind.EventDefinition); assert(default(PropertyDefinitionHandle), HandleKind.PropertyDefinition); assert(default(StandaloneSignatureHandle), HandleKind.StandaloneSignature); assert(default(MemberReferenceHandle), HandleKind.MemberReference); assert(default(FieldDefinitionHandle), HandleKind.FieldDefinition); assert(default(EventDefinitionHandle), HandleKind.EventDefinition); assert(default(PropertyDefinitionHandle), HandleKind.PropertyDefinition); assert(default(ParameterHandle), HandleKind.Parameter); assert(default(GenericParameterHandle), HandleKind.GenericParameter); assert(default(GenericParameterConstraintHandle), HandleKind.GenericParameterConstraint); assert(default(ModuleReferenceHandle), HandleKind.ModuleReference); assert(default(CustomAttributeHandle), HandleKind.CustomAttribute); assert(default(DeclarativeSecurityAttributeHandle), HandleKind.DeclarativeSecurityAttribute); assert(default(ManifestResourceHandle), HandleKind.ManifestResource); assert(default(ConstantHandle), HandleKind.Constant); assert(default(ManifestResourceHandle), HandleKind.ManifestResource); assert(default(MethodImplementationHandle), HandleKind.MethodImplementation); assert(default(AssemblyFileHandle), HandleKind.AssemblyFile); assert(default(StringHandle), HandleKind.String); assert(default(AssemblyReferenceHandle), HandleKind.AssemblyReference); assert(default(UserStringHandle), HandleKind.UserString); assert(default(GuidHandle), HandleKind.Guid); assert(default(BlobHandle), HandleKind.Blob); assert(default(NamespaceDefinitionHandle), HandleKind.NamespaceDefinition); Assert.True(expectedKinds.Count == 0, "Some handles are missing from this test: " + string.Join("," + Environment.NewLine, expectedKinds)); } [Fact] public void Conversions_Handles() { Assert.Equal(1, ((ModuleDefinitionHandle)new Handle((byte)HandleType.Module, 1)).RowId); Assert.Equal(0x00ffffff, ((ModuleDefinitionHandle)new Handle((byte)HandleType.Module, 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyDefinitionHandle)new Handle((byte)HandleType.Assembly, 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyDefinitionHandle)new Handle((byte)HandleType.Assembly, 0x00ffffff)).RowId); Assert.Equal(1, ((InterfaceImplementationHandle)new Handle((byte)HandleType.InterfaceImpl, 1)).RowId); Assert.Equal(0x00ffffff, ((InterfaceImplementationHandle)new Handle((byte)HandleType.InterfaceImpl, 0x00ffffff)).RowId); Assert.Equal(1, ((MethodDefinitionHandle)new Handle((byte)HandleType.MethodDef, 1)).RowId); Assert.Equal(0x00ffffff, ((MethodDefinitionHandle)new Handle((byte)HandleType.MethodDef, 0x00ffffff)).RowId); Assert.Equal(1, ((MethodSpecificationHandle)new Handle((byte)HandleType.MethodSpec, 1)).RowId); Assert.Equal(0x00ffffff, ((MethodSpecificationHandle)new Handle((byte)HandleType.MethodSpec, 0x00ffffff)).RowId); Assert.Equal(1, ((TypeDefinitionHandle)new Handle((byte)HandleType.TypeDef, 1)).RowId); Assert.Equal(0x00ffffff, ((TypeDefinitionHandle)new Handle((byte)HandleType.TypeDef, 0x00ffffff)).RowId); Assert.Equal(1, ((ExportedTypeHandle)new Handle((byte)HandleType.ExportedType, 1)).RowId); Assert.Equal(0x00ffffff, ((ExportedTypeHandle)new Handle((byte)HandleType.ExportedType, 0x00ffffff)).RowId); Assert.Equal(1, ((TypeReferenceHandle)new Handle((byte)HandleType.TypeRef, 1)).RowId); Assert.Equal(0x00ffffff, ((TypeReferenceHandle)new Handle((byte)HandleType.TypeRef, 0x00ffffff)).RowId); Assert.Equal(1, ((TypeSpecificationHandle)new Handle((byte)HandleType.TypeSpec, 1)).RowId); Assert.Equal(0x00ffffff, ((TypeSpecificationHandle)new Handle((byte)HandleType.TypeSpec, 0x00ffffff)).RowId); Assert.Equal(1, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 1)).RowId); Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 0x00ffffff)).RowId); Assert.Equal(1, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 1)).RowId); Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 0x00ffffff)).RowId); Assert.Equal(1, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 1)).RowId); Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 0x00ffffff)).RowId); Assert.Equal(1, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 1)).RowId); Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 0x00ffffff)).RowId); Assert.Equal(1, ((StandaloneSignatureHandle)new Handle((byte)HandleType.Signature, 1)).RowId); Assert.Equal(0x00ffffff, ((StandaloneSignatureHandle)new Handle((byte)HandleType.Signature, 0x00ffffff)).RowId); Assert.Equal(1, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 1)).RowId); Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 0x00ffffff)).RowId); Assert.Equal(1, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 1)).RowId); Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 0x00ffffff)).RowId); Assert.Equal(1, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 1)).RowId); Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 0x00ffffff)).RowId); Assert.Equal(1, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 1)).RowId); Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 0x00ffffff)).RowId); Assert.Equal(1, ((ParameterHandle)new Handle((byte)HandleType.ParamDef, 1)).RowId); Assert.Equal(0x00ffffff, ((ParameterHandle)new Handle((byte)HandleType.ParamDef, 0x00ffffff)).RowId); Assert.Equal(1, ((GenericParameterHandle)new Handle((byte)HandleType.GenericParam, 1)).RowId); Assert.Equal(0x00ffffff, ((GenericParameterHandle)new Handle((byte)HandleType.GenericParam, 0x00ffffff)).RowId); Assert.Equal(1, ((GenericParameterConstraintHandle)new Handle((byte)HandleType.GenericParamConstraint, 1)).RowId); Assert.Equal(0x00ffffff, ((GenericParameterConstraintHandle)new Handle((byte)HandleType.GenericParamConstraint, 0x00ffffff)).RowId); Assert.Equal(1, ((ModuleReferenceHandle)new Handle((byte)HandleType.ModuleRef, 1)).RowId); Assert.Equal(0x00ffffff, ((ModuleReferenceHandle)new Handle((byte)HandleType.ModuleRef, 0x00ffffff)).RowId); Assert.Equal(1, ((CustomAttributeHandle)new Handle((byte)HandleType.CustomAttribute, 1)).RowId); Assert.Equal(0x00ffffff, ((CustomAttributeHandle)new Handle((byte)HandleType.CustomAttribute, 0x00ffffff)).RowId); Assert.Equal(1, ((DeclarativeSecurityAttributeHandle)new Handle((byte)HandleType.DeclSecurity, 1)).RowId); Assert.Equal(0x00ffffff, ((DeclarativeSecurityAttributeHandle)new Handle((byte)HandleType.DeclSecurity, 0x00ffffff)).RowId); Assert.Equal(1, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 1)).RowId); Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 0x00ffffff)).RowId); Assert.Equal(1, ((ConstantHandle)new Handle((byte)HandleType.Constant, 1)).RowId); Assert.Equal(0x00ffffff, ((ConstantHandle)new Handle((byte)HandleType.Constant, 0x00ffffff)).RowId); Assert.Equal(1, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 1)).RowId); Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyFileHandle)new Handle((byte)HandleType.File, 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyFileHandle)new Handle((byte)HandleType.File, 0x00ffffff)).RowId); Assert.Equal(1, ((MethodImplementationHandle)new Handle((byte)HandleType.MethodImpl, 1)).RowId); Assert.Equal(0x00ffffff, ((MethodImplementationHandle)new Handle((byte)HandleType.MethodImpl, 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyReferenceHandle)new Handle((byte)HandleType.AssemblyRef, 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyReferenceHandle)new Handle((byte)HandleType.AssemblyRef, 0x00ffffff)).RowId); Assert.Equal(1, ((UserStringHandle)new Handle((byte)HandleType.UserString, 1)).GetHeapOffset()); Assert.Equal(0x00ffffff, ((UserStringHandle)new Handle((byte)HandleType.UserString, 0x00ffffff)).GetHeapOffset()); Assert.Equal(1, ((GuidHandle)new Handle((byte)HandleType.Guid, 1)).Index); Assert.Equal(0x1fffffff, ((GuidHandle)new Handle((byte)HandleType.Guid, 0x1fffffff)).Index); Assert.Equal(1, ((NamespaceDefinitionHandle)new Handle((byte)HandleType.Namespace, 1)).GetHeapOffset()); Assert.Equal(0x1fffffff, ((NamespaceDefinitionHandle)new Handle((byte)HandleType.Namespace, 0x1fffffff)).GetHeapOffset()); Assert.Equal(1, ((StringHandle)new Handle((byte)HandleType.String, 1)).GetHeapOffset()); Assert.Equal(0x1fffffff, ((StringHandle)new Handle((byte)HandleType.String, 0x1fffffff)).GetHeapOffset()); Assert.Equal(1, ((BlobHandle)new Handle((byte)HandleType.Blob, 1)).GetHeapOffset()); Assert.Equal(0x1fffffff, ((BlobHandle)new Handle((byte)HandleType.Blob, 0x1fffffff)).GetHeapOffset()); } [Fact] public void Conversions_EntityHandles() { Assert.Equal(1, ((ModuleDefinitionHandle)new EntityHandle(TokenTypeIds.Module | 1)).RowId); Assert.Equal(0x00ffffff, ((ModuleDefinitionHandle)new EntityHandle(TokenTypeIds.Module | 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyDefinitionHandle)new EntityHandle(TokenTypeIds.Assembly | 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyDefinitionHandle)new EntityHandle(TokenTypeIds.Assembly | 0x00ffffff)).RowId); Assert.Equal(1, ((InterfaceImplementationHandle)new EntityHandle(TokenTypeIds.InterfaceImpl | 1)).RowId); Assert.Equal(0x00ffffff, ((InterfaceImplementationHandle)new EntityHandle(TokenTypeIds.InterfaceImpl | 0x00ffffff)).RowId); Assert.Equal(1, ((MethodDefinitionHandle)new EntityHandle(TokenTypeIds.MethodDef | 1)).RowId); Assert.Equal(0x00ffffff, ((MethodDefinitionHandle)new EntityHandle(TokenTypeIds.MethodDef | 0x00ffffff)).RowId); Assert.Equal(1, ((MethodSpecificationHandle)new EntityHandle(TokenTypeIds.MethodSpec | 1)).RowId); Assert.Equal(0x00ffffff, ((MethodSpecificationHandle)new EntityHandle(TokenTypeIds.MethodSpec | 0x00ffffff)).RowId); Assert.Equal(1, ((TypeDefinitionHandle)new EntityHandle(TokenTypeIds.TypeDef | 1)).RowId); Assert.Equal(0x00ffffff, ((TypeDefinitionHandle)new EntityHandle(TokenTypeIds.TypeDef | 0x00ffffff)).RowId); Assert.Equal(1, ((ExportedTypeHandle)new EntityHandle(TokenTypeIds.ExportedType | 1)).RowId); Assert.Equal(0x00ffffff, ((ExportedTypeHandle)new EntityHandle(TokenTypeIds.ExportedType | 0x00ffffff)).RowId); Assert.Equal(1, ((TypeReferenceHandle)new EntityHandle(TokenTypeIds.TypeRef | 1)).RowId); Assert.Equal(0x00ffffff, ((TypeReferenceHandle)new EntityHandle(TokenTypeIds.TypeRef | 0x00ffffff)).RowId); Assert.Equal(1, ((TypeSpecificationHandle)new EntityHandle(TokenTypeIds.TypeSpec | 1)).RowId); Assert.Equal(0x00ffffff, ((TypeSpecificationHandle)new EntityHandle(TokenTypeIds.TypeSpec | 0x00ffffff)).RowId); Assert.Equal(1, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 1)).RowId); Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 0x00ffffff)).RowId); Assert.Equal(1, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 1)).RowId); Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 0x00ffffff)).RowId); Assert.Equal(1, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 1)).RowId); Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 0x00ffffff)).RowId); Assert.Equal(1, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 1)).RowId); Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 0x00ffffff)).RowId); Assert.Equal(1, ((StandaloneSignatureHandle)new EntityHandle(TokenTypeIds.Signature | 1)).RowId); Assert.Equal(0x00ffffff, ((StandaloneSignatureHandle)new EntityHandle(TokenTypeIds.Signature | 0x00ffffff)).RowId); Assert.Equal(1, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 1)).RowId); Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 0x00ffffff)).RowId); Assert.Equal(1, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 1)).RowId); Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 0x00ffffff)).RowId); Assert.Equal(1, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 1)).RowId); Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 0x00ffffff)).RowId); Assert.Equal(1, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 1)).RowId); Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 0x00ffffff)).RowId); Assert.Equal(1, ((ParameterHandle)new EntityHandle(TokenTypeIds.ParamDef | 1)).RowId); Assert.Equal(0x00ffffff, ((ParameterHandle)new EntityHandle(TokenTypeIds.ParamDef | 0x00ffffff)).RowId); Assert.Equal(1, ((GenericParameterHandle)new EntityHandle(TokenTypeIds.GenericParam | 1)).RowId); Assert.Equal(0x00ffffff, ((GenericParameterHandle)new EntityHandle(TokenTypeIds.GenericParam | 0x00ffffff)).RowId); Assert.Equal(1, ((GenericParameterConstraintHandle)new EntityHandle(TokenTypeIds.GenericParamConstraint | 1)).RowId); Assert.Equal(0x00ffffff, ((GenericParameterConstraintHandle)new EntityHandle(TokenTypeIds.GenericParamConstraint | 0x00ffffff)).RowId); Assert.Equal(1, ((ModuleReferenceHandle)new EntityHandle(TokenTypeIds.ModuleRef | 1)).RowId); Assert.Equal(0x00ffffff, ((ModuleReferenceHandle)new EntityHandle(TokenTypeIds.ModuleRef | 0x00ffffff)).RowId); Assert.Equal(1, ((CustomAttributeHandle)new EntityHandle(TokenTypeIds.CustomAttribute | 1)).RowId); Assert.Equal(0x00ffffff, ((CustomAttributeHandle)new EntityHandle(TokenTypeIds.CustomAttribute | 0x00ffffff)).RowId); Assert.Equal(1, ((DeclarativeSecurityAttributeHandle)new EntityHandle(TokenTypeIds.DeclSecurity | 1)).RowId); Assert.Equal(0x00ffffff, ((DeclarativeSecurityAttributeHandle)new EntityHandle(TokenTypeIds.DeclSecurity | 0x00ffffff)).RowId); Assert.Equal(1, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 1)).RowId); Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 0x00ffffff)).RowId); Assert.Equal(1, ((ConstantHandle)new EntityHandle(TokenTypeIds.Constant | 1)).RowId); Assert.Equal(0x00ffffff, ((ConstantHandle)new EntityHandle(TokenTypeIds.Constant | 0x00ffffff)).RowId); Assert.Equal(1, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 1)).RowId); Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyFileHandle)new EntityHandle(TokenTypeIds.File | 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyFileHandle)new EntityHandle(TokenTypeIds.File | 0x00ffffff)).RowId); Assert.Equal(1, ((MethodImplementationHandle)new EntityHandle(TokenTypeIds.MethodImpl | 1)).RowId); Assert.Equal(0x00ffffff, ((MethodImplementationHandle)new EntityHandle(TokenTypeIds.MethodImpl | 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyReferenceHandle)new EntityHandle(TokenTypeIds.AssemblyRef | 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyReferenceHandle)new EntityHandle(TokenTypeIds.AssemblyRef | 0x00ffffff)).RowId); } [Fact] public void Conversions_VirtualHandles() { Assert.Throws<InvalidCastException>(() => (ModuleDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Module ), 1)); Assert.Throws<InvalidCastException>(() => (AssemblyDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Assembly ), 1)); Assert.Throws<InvalidCastException>(() => (InterfaceImplementationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.InterfaceImpl), 1)); Assert.Throws<InvalidCastException>(() => (MethodDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MethodDef ), 1)); Assert.Throws<InvalidCastException>(() => (MethodSpecificationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MethodSpec), 1)); Assert.Throws<InvalidCastException>(() => (TypeDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.TypeDef ), 1)); Assert.Throws<InvalidCastException>(() => (ExportedTypeHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ExportedType), 1)); Assert.Throws<InvalidCastException>(() => (TypeReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.TypeRef), 1)); Assert.Throws<InvalidCastException>(() => (TypeSpecificationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.TypeSpec), 1)); Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MemberRef), 1)); Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.FieldDef ), 1)); Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Event ), 1)); Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Property ), 1)); Assert.Throws<InvalidCastException>(() => (StandaloneSignatureHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Signature), 1)); Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MemberRef), 1)); Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.FieldDef ), 1)); Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Event ), 1)); Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Property ), 1)); Assert.Throws<InvalidCastException>(() => (ParameterHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ParamDef), 1)); Assert.Throws<InvalidCastException>(() => (GenericParameterHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.GenericParam), 1)); Assert.Throws<InvalidCastException>(() => (GenericParameterConstraintHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.GenericParamConstraint), 1)); Assert.Throws<InvalidCastException>(() => (ModuleReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ModuleRef), 1)); Assert.Throws<InvalidCastException>(() => (CustomAttributeHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.CustomAttribute), 1)); Assert.Throws<InvalidCastException>(() => (DeclarativeSecurityAttributeHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.DeclSecurity), 1)); Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ManifestResource), 1)); Assert.Throws<InvalidCastException>(() => (ConstantHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Constant), 1)); Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ManifestResource), 1)); Assert.Throws<InvalidCastException>(() => (AssemblyFileHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.File), 1)); Assert.Throws<InvalidCastException>(() => (MethodImplementationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MethodImpl), 1)); Assert.Throws<InvalidCastException>(() => (UserStringHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.UserString), 1)); Assert.Throws<InvalidCastException>(() => (GuidHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.Guid), 1)); Assert.Throws<InvalidCastException>(() => (NamespaceDefinitionHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.Namespace), 1)); var x1 = (AssemblyReferenceHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.AssemblyRef), 1); var x2 = (StringHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.String), 1); var x3 = (BlobHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.Blob), 1); } [Fact] public void Conversions_VirtualEntityHandles() { Assert.Throws<InvalidCastException>(() => (ModuleDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Module | 1)); Assert.Throws<InvalidCastException>(() => (AssemblyDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Assembly | 1)); Assert.Throws<InvalidCastException>(() => (InterfaceImplementationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.InterfaceImpl | 1)); Assert.Throws<InvalidCastException>(() => (MethodDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MethodDef | 1)); Assert.Throws<InvalidCastException>(() => (MethodSpecificationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MethodSpec | 1)); Assert.Throws<InvalidCastException>(() => (TypeDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.TypeDef | 1)); Assert.Throws<InvalidCastException>(() => (ExportedTypeHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ExportedType | 1)); Assert.Throws<InvalidCastException>(() => (TypeReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.TypeRef | 1)); Assert.Throws<InvalidCastException>(() => (TypeSpecificationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.TypeSpec | 1)); Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MemberRef | 1)); Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.FieldDef | 1)); Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Event | 1)); Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Property | 1)); Assert.Throws<InvalidCastException>(() => (StandaloneSignatureHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Signature | 1)); Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MemberRef | 1)); Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.FieldDef | 1)); Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Event | 1)); Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Property | 1)); Assert.Throws<InvalidCastException>(() => (ParameterHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ParamDef | 1)); Assert.Throws<InvalidCastException>(() => (GenericParameterHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.GenericParam | 1)); Assert.Throws<InvalidCastException>(() => (GenericParameterConstraintHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.GenericParamConstraint | 1)); Assert.Throws<InvalidCastException>(() => (ModuleReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ModuleRef | 1)); Assert.Throws<InvalidCastException>(() => (CustomAttributeHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.CustomAttribute | 1)); Assert.Throws<InvalidCastException>(() => (DeclarativeSecurityAttributeHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.DeclSecurity | 1)); Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ManifestResource | 1)); Assert.Throws<InvalidCastException>(() => (ConstantHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Constant | 1)); Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ManifestResource | 1)); Assert.Throws<InvalidCastException>(() => (AssemblyFileHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.File | 1)); Assert.Throws<InvalidCastException>(() => (MethodImplementationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MethodImpl | 1)); var x1 = (AssemblyReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.AssemblyRef | 1); } [Fact] public void IsNil() { Assert.False(ModuleDefinitionHandle.FromRowId(1).IsNil); Assert.False(AssemblyDefinitionHandle.FromRowId(1).IsNil); Assert.False(InterfaceImplementationHandle.FromRowId(1).IsNil); Assert.False(MethodDefinitionHandle.FromRowId(1).IsNil); Assert.False(MethodSpecificationHandle.FromRowId(1).IsNil); Assert.False(TypeDefinitionHandle.FromRowId(1).IsNil); Assert.False(ExportedTypeHandle.FromRowId(1).IsNil); Assert.False(TypeReferenceHandle.FromRowId(1).IsNil); Assert.False(TypeSpecificationHandle.FromRowId(1).IsNil); Assert.False(MemberReferenceHandle.FromRowId(1).IsNil); Assert.False(FieldDefinitionHandle.FromRowId(1).IsNil); Assert.False(EventDefinitionHandle.FromRowId(1).IsNil); Assert.False(PropertyDefinitionHandle.FromRowId(1).IsNil); Assert.False(StandaloneSignatureHandle.FromRowId(1).IsNil); Assert.False(MemberReferenceHandle.FromRowId(1).IsNil); Assert.False(FieldDefinitionHandle.FromRowId(1).IsNil); Assert.False(EventDefinitionHandle.FromRowId(1).IsNil); Assert.False(PropertyDefinitionHandle.FromRowId(1).IsNil); Assert.False(ParameterHandle.FromRowId(1).IsNil); Assert.False(GenericParameterHandle.FromRowId(1).IsNil); Assert.False(GenericParameterConstraintHandle.FromRowId(1).IsNil); Assert.False(ModuleReferenceHandle.FromRowId(1).IsNil); Assert.False(CustomAttributeHandle.FromRowId(1).IsNil); Assert.False(DeclarativeSecurityAttributeHandle.FromRowId(1).IsNil); Assert.False(ManifestResourceHandle.FromRowId(1).IsNil); Assert.False(ConstantHandle.FromRowId(1).IsNil); Assert.False(ManifestResourceHandle.FromRowId(1).IsNil); Assert.False(AssemblyFileHandle.FromRowId(1).IsNil); Assert.False(MethodImplementationHandle.FromRowId(1).IsNil); Assert.False(AssemblyReferenceHandle.FromRowId(1).IsNil); Assert.False(((EntityHandle)ModuleDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)AssemblyDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)InterfaceImplementationHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MethodDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MethodSpecificationHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)TypeDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ExportedTypeHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)TypeReferenceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)TypeSpecificationHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MemberReferenceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)FieldDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)EventDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)PropertyDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)StandaloneSignatureHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MemberReferenceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)FieldDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)EventDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)PropertyDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ParameterHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)GenericParameterHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)GenericParameterConstraintHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ModuleReferenceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)CustomAttributeHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)DeclarativeSecurityAttributeHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ManifestResourceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ConstantHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ManifestResourceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)AssemblyFileHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MethodImplementationHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)AssemblyReferenceHandle.FromRowId(1)).IsNil); Assert.False(StringHandle.FromOffset(1).IsNil); Assert.False(BlobHandle.FromOffset(1).IsNil); Assert.False(UserStringHandle.FromOffset(1).IsNil); Assert.False(GuidHandle.FromIndex(1).IsNil); Assert.False(((Handle)StringHandle.FromOffset(1)).IsNil); Assert.False(((Handle)BlobHandle.FromOffset(1)).IsNil); Assert.False(((Handle)UserStringHandle.FromOffset(1)).IsNil); Assert.False(((Handle)GuidHandle.FromIndex(1)).IsNil); Assert.True(ModuleDefinitionHandle.FromRowId(0).IsNil); Assert.True(AssemblyDefinitionHandle.FromRowId(0).IsNil); Assert.True(InterfaceImplementationHandle.FromRowId(0).IsNil); Assert.True(MethodDefinitionHandle.FromRowId(0).IsNil); Assert.True(MethodSpecificationHandle.FromRowId(0).IsNil); Assert.True(TypeDefinitionHandle.FromRowId(0).IsNil); Assert.True(ExportedTypeHandle.FromRowId(0).IsNil); Assert.True(TypeReferenceHandle.FromRowId(0).IsNil); Assert.True(TypeSpecificationHandle.FromRowId(0).IsNil); Assert.True(MemberReferenceHandle.FromRowId(0).IsNil); Assert.True(FieldDefinitionHandle.FromRowId(0).IsNil); Assert.True(EventDefinitionHandle.FromRowId(0).IsNil); Assert.True(PropertyDefinitionHandle.FromRowId(0).IsNil); Assert.True(StandaloneSignatureHandle.FromRowId(0).IsNil); Assert.True(MemberReferenceHandle.FromRowId(0).IsNil); Assert.True(FieldDefinitionHandle.FromRowId(0).IsNil); Assert.True(EventDefinitionHandle.FromRowId(0).IsNil); Assert.True(PropertyDefinitionHandle.FromRowId(0).IsNil); Assert.True(ParameterHandle.FromRowId(0).IsNil); Assert.True(GenericParameterHandle.FromRowId(0).IsNil); Assert.True(GenericParameterConstraintHandle.FromRowId(0).IsNil); Assert.True(ModuleReferenceHandle.FromRowId(0).IsNil); Assert.True(CustomAttributeHandle.FromRowId(0).IsNil); Assert.True(DeclarativeSecurityAttributeHandle.FromRowId(0).IsNil); Assert.True(ManifestResourceHandle.FromRowId(0).IsNil); Assert.True(ConstantHandle.FromRowId(0).IsNil); Assert.True(ManifestResourceHandle.FromRowId(0).IsNil); Assert.True(AssemblyFileHandle.FromRowId(0).IsNil); Assert.True(MethodImplementationHandle.FromRowId(0).IsNil); Assert.True(AssemblyReferenceHandle.FromRowId(0).IsNil); Assert.True(((EntityHandle)ModuleDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)AssemblyDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)InterfaceImplementationHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MethodDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MethodSpecificationHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)TypeDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ExportedTypeHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)TypeReferenceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)TypeSpecificationHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MemberReferenceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)FieldDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)EventDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)PropertyDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)StandaloneSignatureHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MemberReferenceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)FieldDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)EventDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)PropertyDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ParameterHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)GenericParameterHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)GenericParameterConstraintHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ModuleReferenceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)CustomAttributeHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)DeclarativeSecurityAttributeHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ManifestResourceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ConstantHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ManifestResourceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)AssemblyFileHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MethodImplementationHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)AssemblyReferenceHandle.FromRowId(0)).IsNil); // heaps: Assert.True(StringHandle.FromOffset(0).IsNil); Assert.True(BlobHandle.FromOffset(0).IsNil); Assert.True(UserStringHandle.FromOffset(0).IsNil); Assert.True(GuidHandle.FromIndex(0).IsNil); Assert.True(((Handle)StringHandle.FromOffset(0)).IsNil); Assert.True(((Handle)BlobHandle.FromOffset(0)).IsNil); Assert.True(((Handle)UserStringHandle.FromOffset(0)).IsNil); Assert.True(((Handle)GuidHandle.FromIndex(0)).IsNil); // virtual: Assert.False(AssemblyReferenceHandle.FromVirtualIndex(0).IsNil); Assert.False(StringHandle.FromVirtualIndex(0).IsNil); Assert.False(BlobHandle.FromVirtualIndex(0, 0).IsNil); Assert.False(((Handle)AssemblyReferenceHandle.FromVirtualIndex(0)).IsNil); Assert.False(((Handle)StringHandle.FromVirtualIndex(0)).IsNil); Assert.False(((Handle)BlobHandle.FromVirtualIndex(0, 0)).IsNil); } [Fact] public void IsVirtual() { Assert.False(AssemblyReferenceHandle.FromRowId(1).IsVirtual); Assert.False(StringHandle.FromOffset(1).IsVirtual); Assert.False(BlobHandle.FromOffset(1).IsVirtual); Assert.True(AssemblyReferenceHandle.FromVirtualIndex(0).IsVirtual); Assert.True(StringHandle.FromVirtualIndex(0).IsVirtual); Assert.True(BlobHandle.FromVirtualIndex(0, 0).IsVirtual); } [Fact] public void StringKinds() { var str = StringHandle.FromOffset(123); Assert.Equal(StringKind.Plain, str.StringKind); Assert.False(str.IsVirtual); Assert.Equal(123, str.GetHeapOffset()); var vstr = StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.AttributeTargets); Assert.Equal(StringKind.Virtual, vstr.StringKind); Assert.True(vstr.IsVirtual); Assert.Equal(StringHandle.VirtualIndex.AttributeTargets, vstr.GetVirtualIndex()); var dot = StringHandle.FromOffset(123).WithDotTermination(); Assert.Equal(StringKind.DotTerminated, dot.StringKind); Assert.False(dot.IsVirtual); Assert.Equal(123, dot.GetHeapOffset()); var winrtPrefix = StringHandle.FromOffset(123).WithWinRTPrefix(); Assert.Equal(StringKind.WinRTPrefixed, winrtPrefix.StringKind); Assert.True(winrtPrefix.IsVirtual); Assert.Equal(123, winrtPrefix.GetHeapOffset()); } [Fact] public void NamespaceKinds() { var full = NamespaceDefinitionHandle.FromFullNameOffset(123); Assert.Equal(NamespaceKind.Plain, full.NamespaceKind); Assert.False(full.IsVirtual); Assert.Equal(123, full.GetHeapOffset()); var synthetic = NamespaceDefinitionHandle.FromSimpleNameOffset(123); Assert.Equal(NamespaceKind.Synthetic, synthetic.NamespaceKind); Assert.False(synthetic.IsVirtual); Assert.Equal(123, synthetic.GetHeapOffset()); } [Fact] public void HandleKindHidesSpecialStringAndNamespaces() { foreach (int virtualBit in new[] { 0, (int)HandleType.VirtualBit }) { for (int i = 0; i <= sbyte.MaxValue; i++) { Handle handle = new Handle((byte)(virtualBit | i), 0); Assert.True(handle.IsNil ^ handle.IsVirtual); Assert.Equal(virtualBit != 0, handle.IsVirtual); Assert.Equal(handle.EntityHandleType, (uint)i << TokenTypeIds.RowIdBitCount); switch (i) { // String and namespace have two extra bits to represent their kind that are hidden from the handle type case (int)HandleKind.String: case (int)HandleKind.String + 1: case (int)HandleKind.String + 2: case (int)HandleKind.String + 3: Assert.Equal(HandleKind.String, handle.Kind); break; case (int)HandleKind.NamespaceDefinition: case (int)HandleKind.NamespaceDefinition + 1: case (int)HandleKind.NamespaceDefinition + 2: case (int)HandleKind.NamespaceDefinition + 3: Assert.Equal(HandleKind.NamespaceDefinition, handle.Kind); break; // all other types surface token type directly. default: Assert.Equal((int)handle.Kind, i); break; } } } } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- /// The texture filename filter used with OpenFileDialog. $TerrainEditor::TextureFileSpec = "Image Files (*.png, *.jpg, *.dds)|*.png;*.jpg;*.dds|All Files (*.*)|*.*|"; function TerrainEditor::init( %this ) { %this.attachTerrain(); %this.setBrushSize( 9, 9 ); new PersistenceManager( ETerrainPersistMan ); } /// function EPainter_TerrainMaterialUpdateCallback( %mat, %matIndex ) { // Skip over a bad selection. if ( %matIndex == -1 || !isObject( %mat ) ) return; // Update the material and the UI. ETerrainEditor.updateMaterial( %matIndex, %mat.getInternalName() ); EPainter.setup( %matIndex ); } function EPainter_TerrainMaterialAddCallback( %mat, %matIndex ) { // Ignore bad materials. if ( !isObject( %mat ) ) return; // Add it and update the UI. ETerrainEditor.addMaterial( %mat.getInternalName() ); EPainter.setup( %matIndex ); } function TerrainEditor::setPaintMaterial( %this, %matIndex, %terrainMat ) { assert( isObject( %terrainMat ), "TerrainEditor::setPaintMaterial - Got bad material!" ); ETerrainEditor.paintIndex = %matIndex; ETerrainMaterialSelected.selectedMatIndex = %matIndex; ETerrainMaterialSelected.selectedMat = %terrainMat; ETerrainMaterialSelected.bitmap = %terrainMat.diffuseMap; ETerrainMaterialSelectedEdit.Visible = isObject(%terrainMat); TerrainTextureText.text = %terrainMat.getInternalName(); ProceduralTerrainPainterDescription.text = "Generate "@ %terrainMat.getInternalName() @" layer"; } function TerrainEditor::setup( %this ) { %action = %this.savedAction; %desc = %this.savedActionDesc; if ( %this.savedAction $= "" ) { %action = brushAdjustHeight; } %this.switchAction( %action ); } function EPainter::updateLayers( %this, %matIndex ) { // Default to whatever was selected before. if ( %matIndex $= "" ) %matIndex = ETerrainEditor.paintIndex; // The material string is a newline seperated string of // TerrainMaterial internal names which we can use to find // the actual material data in TerrainMaterialSet. %mats = ETerrainEditor.getMaterials(); %matList = %this-->theMaterialList; %matList.deleteAllObjects(); %listWidth = getWord( %matList.getExtent(), 0 ); for( %i = 0; %i < getRecordCount( %mats ); %i++ ) { %matInternalName = getRecord( %mats, %i ); %mat = TerrainMaterialSet.findObjectByInternalName( %matInternalName ); // Is there no material info for this slot? if ( !isObject( %mat ) ) continue; %index = %matList.getCount(); %command = "ETerrainEditor.setPaintMaterial( " @ %index @ ", " @ %mat @ " );"; %altCommand = "TerrainMaterialDlg.show( " @ %index @ ", " @ %mat @ ", EPainter_TerrainMaterialUpdateCallback );"; %ctrl = new GuiIconButtonCtrl() { class = "EPainterIconBtn"; internalName = "EPainterMaterialButton" @ %i; profile = "GuiCreatorIconButtonProfile"; iconLocation = "Left"; textLocation = "Right"; extent = %listWidth SPC "46"; textMargin = 5; buttonMargin = "4 4"; buttonType = "RadioButton"; sizeIconToButton = true; makeIconSquare = true; tooltipprofile = "ToolsGuiToolTipProfile"; command = %command; altCommand = %altCommand; useMouseEvents = true; new GuiBitmapButtonCtrl() { bitmap = "tools/gui/images/delete"; buttonType = "PushButton"; HorizSizing = "left"; VertSizing = "bottom"; position = ( %listwidth - 20 ) SPC "26"; Extent = "17 17"; command = "EPainter.showMaterialDeleteDlg( " @ %matInternalName @ " );"; }; }; %ctrl.setText( %matInternalName ); %ctrl.setBitmap( %mat.diffuseMap ); %tooltip = %matInternalName; if(%i < 9) %tooltip = %tooltip @ " (" @ (%i+1) @ ")"; else if(%i == 9) %tooltip = %tooltip @ " (0)"; %ctrl.tooltip = %tooltip; %matList.add( %ctrl ); } %matCount = %matList.getCount(); // Add one more layer as the 'add new' layer. %ctrl = new GuiIconButtonCtrl() { profile = "GuiCreatorIconButtonProfile"; iconBitmap = "~/worldEditor/images/terrainpainter/new_layer_icon"; iconLocation = "Left"; textLocation = "Right"; extent = %listWidth SPC "46"; textMargin = 5; buttonMargin = "4 4"; buttonType = "PushButton"; sizeIconToButton = true; makeIconSquare = true; tooltipprofile = "ToolsGuiToolTipProfile"; text = "New Layer"; tooltip = "New Layer"; command = "TerrainMaterialDlg.show( " @ %matCount @ ", 0, EPainter_TerrainMaterialAddCallback );"; }; %matList.add( %ctrl ); // Make sure our selection is valid and that we're // not selecting the 'New Layer' button. if( %matIndex < 0 ) return; if( %matIndex >= %matCount ) %matIndex = 0; // To make things simple... click the paint material button to // active it and initialize other state. %ctrl = %matList.getObject( %matIndex ); %ctrl.performClick(); } function EPainter::showMaterialDeleteDlg( %this, %matInternalName ) { MessageBoxYesNo( "Confirmation", "Really remove material '" @ %matInternalName @ "' from the terrain?", %this @ ".removeMaterial( " @ %matInternalName @ " );", "" ); } function EPainter::removeMaterial( %this, %matInternalName ) { %selIndex = ETerrainEditor.paintIndex - 1; // Remove the material from the terrain. %index = ETerrainEditor.getMaterialIndex( %matInternalName ); if( %index != -1 ) ETerrainEditor.removeMaterial( %index ); // Update the material list. %this.updateLayers( %selIndex ); } function EPainter::setup( %this, %matIndex ) { // Update the layer listing. %this.updateLayers( %matIndex ); // Automagically put us into material paint mode. ETerrainEditor.currentMode = "paint"; ETerrainEditor.selectionHidden = true; ETerrainEditor.currentAction = paintMaterial; ETerrainEditor.currentActionDesc = "Paint material on terrain"; ETerrainEditor.setAction( ETerrainEditor.currentAction ); EditorGuiStatusBar.setInfo(ETerrainEditor.currentActionDesc); ETerrainEditor.renderVertexSelection = true; } function onNeedRelight() { if( RelightMessage.visible == false ) RelightMessage.visible = true; } function TerrainEditor::onGuiUpdate(%this, %text) { %minHeight = getWord(%text, 1); %avgHeight = getWord(%text, 2); %maxHeight = getWord(%text, 3); %mouseBrushInfo = " (Mouse) #: " @ getWord(%text, 0) @ " avg: " @ %avgHeight @ " " @ ETerrainEditor.currentAction; %selectionInfo = " (Selected) #: " @ getWord(%text, 4) @ " avg: " @ getWord(%text, 5); TEMouseBrushInfo.setValue(%mouseBrushInfo); TEMouseBrushInfo1.setValue(%mouseBrushInfo); TESelectionInfo.setValue(%selectionInfo); TESelectionInfo1.setValue(%selectionInfo); EditorGuiStatusBar.setSelection("min: " @ %minHeight @ " avg: " @ %avgHeight @ " max: " @ %maxHeight); } function TerrainEditor::onBrushChanged( %this ) { EditorGui.currentEditor.syncBrushInfo(); } function TerrainEditor::toggleBrushType( %this, %brush ) { %this.setBrushType( %brush.internalName ); } function TerrainEditor::offsetBrush(%this, %x, %y) { %curPos = %this.getBrushPos(); %this.setBrushPos(getWord(%curPos, 0) + %x, getWord(%curPos, 1) + %y); } function TerrainEditor::onActiveTerrainChange(%this, %newTerrain) { // Need to refresh the terrain painter. if ( EditorGui.currentEditor.getId() == TerrainPainterPlugin.getId() ) EPainter.setup(ETerrainEditor.paintIndex); } function TerrainEditor::getActionDescription( %this, %action ) { switch$( %action ) { case "brushAdjustHeight": return "Adjust terrain height up or down."; case "raiseHeight": return "Raise terrain height."; case "lowerHeight": return "Lower terrain height."; case "smoothHeight": return "Smooth terrain."; case "paintNoise": return "Modify terrain height using noise."; case "flattenHeight": return "Flatten terrain."; case "setHeight": return "Set terrain height to defined value."; case "setEmpty": return "Remove terrain collision."; case "clearEmpty": return "Add back terrain collision."; default: return ""; } } /// This is only ment for terrain editing actions and not /// processed actions or the terrain material painting action. function TerrainEditor::switchAction( %this, %action ) { %actionDesc = %this.getActionDescription(%action); %this.currentMode = "paint"; %this.selectionHidden = true; %this.currentAction = %action; %this.currentActionDesc = %actionDesc; %this.savedAction = %action; %this.savedActionDesc = %actionDesc; if ( %action $= "setEmpty" || %action $= "clearEmpty" || %action $= "setHeight" ) %this.renderSolidBrush = true; else %this.renderSolidBrush = false; EditorGuiStatusBar.setInfo(%actionDesc); %this.setAction( %this.currentAction ); } function TerrainEditor::onSmoothHeightmap( %this ) { if ( !%this.getActiveTerrain() ) return; // Show the dialog first and let the user // set the smoothing parameters. // Now create the terrain smoothing action to // get the work done and perform later undos. %action = new TerrainSmoothAction(); %action.smooth( %this.getActiveTerrain(), 1.0, 1 ); %action.addToManager( Editor.getUndoManager() ); } function TerrainEditor::onMaterialUndo( %this ) { // Update the gui to reflect the current materials. EPainter.updateLayers(); } //------------------------------------------------------------------------------ // Functions //------------------------------------------------------------------------------ function TerrainEditorSettingsGui::onWake(%this) { TESoftSelectFilter.setValue(ETerrainEditor.softSelectFilter); } function TerrainEditorSettingsGui::onSleep(%this) { ETerrainEditor.softSelectFilter = TESoftSelectFilter.getValue(); } function TESettingsApplyButton::onAction(%this) { ETerrainEditor.softSelectFilter = TESoftSelectFilter.getValue(); ETerrainEditor.resetSelWeights(true); ETerrainEditor.processAction("softSelect"); } function getPrefSetting(%pref, %default) { // if(%pref $= "") return(%default); else return(%pref); } function TerrainEditorPlugin::setEditorFunction(%this) { %terrainExists = parseMissionGroup( "TerrainBlock" ); if( %terrainExists == false ) MessageBoxYesNoCancel("No Terrain","Would you like to create a New Terrain?", "Canvas.pushDialog(CreateNewTerrainGui);"); return %terrainExists; } function TerrainPainterPlugin::setEditorFunction(%this, %overrideGroup) { %terrainExists = parseMissionGroup( "TerrainBlock" ); if( %terrainExists == false ) MessageBoxYesNoCancel("No Terrain","Would you like to create a New Terrain?", "Canvas.pushDialog(CreateNewTerrainGui);"); return %terrainExists; } function EPainterIconBtn::onMouseDragged( %this ) { %payload = new GuiControl() { profile = GuiCreatorIconButtonProfile; position = "0 0"; extent = %this.extent.x SPC "5"; dragSourceControl = %this; }; %xOffset = getWord( %payload.extent, 0 ) / 2; %yOffset = getWord( %payload.extent, 1 ) / 2; %cursorpos = Canvas.getCursorPos(); %xPos = getWord( %cursorpos, 0 ) - %xOffset; %yPos = getWord( %cursorpos, 1 ) - %yOffset; // Create the drag control. %ctrl = new GuiDragAndDropControl() { canSaveDynamicFields = "0"; Profile = EPainterDragDropProfile; HorizSizing = "right"; VertSizing = "bottom"; Position = %xPos SPC %yPos; extent = %payload.extent; MinExtent = "4 4"; canSave = "1"; Visible = "1"; hovertime = "1000"; deleteOnMouseUp = true; }; %ctrl.add( %payload ); Canvas.getContent().add( %ctrl ); %ctrl.startDragging( %xOffset, %yOffset ); } function EPainterIconBtn::onControlDragged( %this, %payload ) { %payload.getParent().position = %this.getGlobalPosition(); } function EPainterIconBtn::onControlDropped( %this, %payload ) { %srcBtn = %payload.dragSourceControl; %dstBtn = %this; %stack = %this.getParent(); // Not dropped on a valid Button. // Really this shouldnt happen since we are in a callback on our specialized // EPainterIconBtn namespace. if ( %stack != %dstBtn.getParent() || %stack != EPainterStack.getId() ) { echo( "Not dropped on valid control" ); return; } // Dropped on the original control, no order change. // Simulate a click on the control, instead of a drag/drop. if ( %srcBtn == %dstBtn ) { %dstBtn.performClick(); return; } %dstIndex = %stack.getObjectIndex( %dstBtn ); ETerrainEditor.reorderMaterial( %stack.getObjectIndex( %srcBtn ), %dstIndex ); // select the button/material we just reordered. %stack.getObject( %dstIndex ).performClick(); }
using System; using System.Linq; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace QarnotSDK { /// <summary> /// Pool states. /// </summary> public sealed class QPoolStates { /// <summary> /// The Pool has been submitted and is waiting for dispatch. /// </summary> public static readonly string Submitted = "Submitted"; /// <summary> /// Some of the nodes have been dispatched. /// </summary> public static readonly string PartiallyDispatched = "PartiallyDispatched"; /// <summary> /// All the nodes have been dispatched. /// </summary> public static readonly string FullyDispatched = "FullyDispatched"; /// <summary> /// Some of the nodes are up an running. /// </summary> public static readonly string PartiallyExecuting = "PartiallyExecuting"; /// <summary> /// All the nodes are up an running. /// </summary> public static readonly string FullyExecuting = "FullyExecuting"; /// <summary> /// The pool has ended. /// </summary> public static readonly string Closed = "Closed"; } /// <summary> /// This class manages pools life cycle: start, monitor, stop. /// </summary> public partial class QPool : AQPool { /// <summary> /// The pool shortname identifier. The shortname is provided by the user. It has to be unique. /// </summary> [InternalDataApiName(Name="Shortname")] public virtual string Shortname { get { return _poolApi.Shortname == null ? _poolApi.Uuid.ToString() : _poolApi.Shortname; } } /// <summary> /// The pool name. /// </summary> [InternalDataApiName(Name="Name")] public virtual string Name { get { return _poolApi.Name; } } /// <summary> /// The pool profile. /// </summary> [InternalDataApiName(Name="Profile")] public virtual string Profile { get { return _poolApi.Profile; } } /// <summary> /// Qarnot resources buckets bound to this pool. /// Can be set only before the pool start. /// </summary> [InternalDataApiName(IsFilterable=false, IsSelectable=false)] public virtual List<QAbstractStorage> Resources { get { return _resources.Select(bucket => (QAbstractStorage) bucket).ToList(); } set { _resources = QBucket.GetBucketsFromResources(value); } } private List<QBucket> _resources { get; set; } /// <summary> /// Qarnot resources buckets bound to this pool. /// Can be set only before the pool start. /// </summary> [InternalDataApiName(Name="ResourceBuckets", IsFilterable=false)] public virtual IEnumerable<QBucket> ResourcesBuckets { get { return _resources; } } /// <summary> /// Retrieve the pool state (see QPoolStates). /// Available only after the pool is started. Use UpdateStatus or UpdateStatusAsync to refresh. /// </summary> [InternalDataApiName(Name="State")] public virtual string State { get { return _poolApi?.State; } } /// <summary> /// Retrieve the pool previous state (see QPoolStates). /// Available only after the submission. Use UpdateStatus or UpdateStatusAsync to refresh. /// </summary> [InternalDataApiName(Name = "PreviousState")] public virtual string PreviousState { get { return _poolApi?.PreviousState; } } /// <summary> /// Retrieve the pool state transition utc-time (see QPoolStates). /// Available only after the submission. Use UpdateStatus or UpdateStatusAsync to refresh. /// </summary> [InternalDataApiName(Name = "StateTransitionTime")] public DateTime? StateTransitionTime { get { if (_poolApi != null) { if (_poolApi.StateTransitionTime != default) { return _poolApi.StateTransitionTime; } } return null; } } /// <summary> /// Retrieve the pool previous state transition utc-time (see QPoolStates). /// Available only after the submission. Use UpdateStatus or UpdateStatusAsync to refresh. /// </summary> [InternalDataApiName(Name = "PreviousStateTransitionTime")] public virtual DateTime? PreviousStateTransitionTime { get { if (_poolApi != null) { if (_poolApi.PreviousStateTransitionTime != default) { return _poolApi.PreviousStateTransitionTime; } } return null; } } /// <summary> /// The Pool last modified date. /// </summary> [InternalDataApiName(Name = "LastModified")] public virtual DateTime? LastModified { get { if (_poolApi != null) { if (_poolApi.LastModified != default) { return _poolApi.LastModified; } } return null; } } /// <summary> /// Retrieve the pool errors. /// </summary> [InternalDataApiName(Name="Errors", IsFilterable=false)] public virtual List<QPoolError> Errors { get { return _poolApi != null ? _poolApi.Errors : new List<QPoolError>(); } } /// <summary> /// Retrieve the pool detailed status. /// Available only after the pool is started. Use UpdateStatus or UpdateStatusAsync to refresh. /// </summary> [InternalDataApiName(Name="Status", IsFilterable=false)] public virtual QPoolStatus Status { get { return _poolApi != null ? _poolApi.Status : null; } } /// <summary> /// The pool creation date. /// Available only after the pool is started. /// </summary> [InternalDataApiName(Name="CreationDate")] public virtual DateTime CreationDate { get { return _poolApi.CreationDate; } } /// <summary> /// The count of task instances running or enqueued on this pool. /// Available only after the submission. /// </summary> [InternalDataApiName(Name="queuedOrRunningTaskInstancesCount")] public virtual int QueuedOrRunningTaskInstancesCount { get { return _poolApi.QueuedOrRunningTaskInstancesCount; } } /// <summary> /// The slot capacity of this Pool. /// Representing the slots count for a static pool /// or the maximum slot count for an elastic pool. /// Available only after the submission. /// </summary> [InternalDataApiName(Name="totalSlotCapacity")] public virtual int TotalSlotCapacity { get { return _poolApi.TotalSlotCapacity; } } /// <summary> /// The ratio of dispatched task instances on the slot capacity indicating /// how much a pool is currently being used. /// Available only after the submission. /// </summary> [InternalDataApiName(Name="poolUsage")] public virtual double PoolUsage { get { return _poolApi.PoolUsage; } } /// <summary> /// How many nodes this pool has. /// </summary> [InternalDataApiName(Name="InstanceCount")] public virtual uint NodeCount { get { return _poolApi.InstanceCount; } } /// <summary> /// The actual running instance count. /// </summary> [InternalDataApiName(Name = "RunningInstanceCount")] public virtual uint RunningInstanceCount { get { return _poolApi?.RunningInstanceCount ?? default(uint); } } /// <summary> /// The actual running cores count. /// </summary> [InternalDataApiName(Name = "RunningCoreCount")] public virtual uint RunningCoreCount { get { return _poolApi?.RunningCoreCount ?? default(uint); } } /// <summary> /// The pool execution time. /// </summary> [InternalDataApiName(Name = "ExecutionTime")] public virtual TimeSpan ExecutionTime { get { return _poolApi?.ExecutionTime ?? default(TimeSpan); } } /// <summary> /// The pool wall time. /// </summary> [InternalDataApiName(Name = "WallTime")] public virtual TimeSpan WallTime { get { return _poolApi?.WallTime ?? default(TimeSpan); } } /// <summary> /// The pool end date. /// </summary> [InternalDataApiName(Name = "EndDate")] public virtual DateTime EndDate { get { return _poolApi?.EndDate ?? default(DateTime); } } /// <summary> /// The custom pool tag list. /// </summary> [InternalDataApiName(Name="Tags")] public virtual List<String> Tags { get { return _poolApi.Tags; } } /// <summary> /// The pool hardware constraints list. /// </summary> [InternalDataApiName(Name="HardwareConstraints")] public virtual HardwareConstraints HardwareConstraints { get { return _poolApi.HardwareConstraints; } set { _poolApi.HardwareConstraints = value; } } private Dictionary<string, string> _constants { get; set; } /// <summary> /// The Pool constants. /// </summary> [InternalDataApiName(Name="Constants", IsFilterable=false)] public virtual Dictionary<string, string> Constants { get { if (_constants == null) _constants = new Dictionary<string, string>(); return _constants; } } private Dictionary<string, string> _constraints { get; set; } /// <summary> /// The pool constraints. /// </summary> [InternalDataApiName(Name="Constraints", IsFilterable=false)] public virtual Dictionary<string, string> Constraints { get { if (_constraints == null) _constraints = new Dictionary<string, string>(); return _constraints; } } /// <summary> /// The pool labels. /// </summary> [InternalDataApiName(Name="Labels", IsFilterable=false)] public virtual Dictionary<string, string> Labels { get { if (_poolApi.Labels == null) { _poolApi.Labels = new Dictionary<string, string>(); } return _poolApi.Labels; } } #region Elastic properties /// <summary> /// Allow the automatic resize of the pool /// </summary> [InternalDataApiName(Name="ElasticProperty.IsElastic")] public virtual bool IsElastic { get { return _poolApi?.ElasticProperty?.IsElastic ?? false; } set { if (_poolApi.ElasticProperty == null) { _poolApi.ElasticProperty = new QPoolElasticProperty(); } _poolApi.ElasticProperty.IsElastic = value; } } /// <summary> /// Minimum node number for the pool in elastic mode /// </summary> [InternalDataApiName(Name="ElasticProperty.MinTotalSlots")] public virtual uint ElasticMinimumTotalNodes { get { return _poolApi?.ElasticProperty?.MinTotalSlots ?? 0; } set { if (_poolApi.ElasticProperty == null) { _poolApi.ElasticProperty = new QPoolElasticProperty(); } _poolApi.ElasticProperty.MinTotalSlots = value; } } /// <summary> /// Maximum node number for the pool in elastic mode /// </summary> [InternalDataApiName(Name="ElasticProperty.MaxTotalSlots")] public virtual uint ElasticMaximumTotalNodes { get { return _poolApi?.ElasticProperty?.MaxTotalSlots ?? 0; } set { if (_poolApi.ElasticProperty == null) { _poolApi.ElasticProperty = new QPoolElasticProperty(); } _poolApi.ElasticProperty.MaxTotalSlots = value; } } /// <summary> /// Minimum idling node number. /// </summary> [InternalDataApiName(Name="ElasticProperty.MinIdleSlots")] public virtual uint ElasticMinimumIdlingNodes { get { return _poolApi?.ElasticProperty?.MinIdleSlots ?? 0; } set { if (_poolApi.ElasticProperty == null) { _poolApi.ElasticProperty = new QPoolElasticProperty(); } _poolApi.ElasticProperty.MinIdleSlots = value; } } /// <summary> /// </summary> [InternalDataApiName(Name="ElasticProperty.ResizePeriod")] public virtual uint ElasticResizePeriod { get { return _poolApi?.ElasticProperty?.ResizePeriod ?? 0; } set { if (_poolApi.ElasticProperty == null) { _poolApi.ElasticProperty = new QPoolElasticProperty(); } _poolApi.ElasticProperty.ResizePeriod = value; } } /// <summary> /// </summary> [InternalDataApiName(Name="ElasticProperty.RampResizeFactor")] public virtual float ElasticResizeFactor { get { return _poolApi?.ElasticProperty?.RampResizeFactor ?? 0; } set { if (_poolApi.ElasticProperty == null) { _poolApi.ElasticProperty = new QPoolElasticProperty(); } _poolApi.ElasticProperty.RampResizeFactor = value; } } /// <summary> /// </summary> [InternalDataApiName(Name="ElasticProperty.MinIdleTimeSeconds")] public virtual uint ElasticMinimumIdlingTime { get { return _poolApi?.ElasticProperty?.MinIdleTimeSeconds ?? 0; } set { if (_poolApi.ElasticProperty == null) { _poolApi.ElasticProperty = new QPoolElasticProperty(); } _poolApi.ElasticProperty.MinIdleTimeSeconds = value; } } /// <summary> /// The Pool Preparation Command Line. /// </summary> [InternalDataApiName(Name="PreparationTask.CommandLine")] public virtual string PreparationCommandLine { get { return _poolApi?.PreparationTask?.CommandLine; } set { if (_poolApi != null) { _poolApi.PreparationTask = new PoolPreparationTask(value); } } } /// <summary> /// AutoDeleteOnCompletion: Field allowing the automatic deletion of the pool when in a final state. /// Must be set before the submission. /// </summary> [InternalDataApiName(IsFilterable = false, IsSelectable = false)] public bool AutoDeleteOnCompletion { get { return _poolApi.AutoDeleteOnCompletion; } set { _poolApi.AutoDeleteOnCompletion = value; } } /// <summary> /// CompletionTimeToLive: Final State Duration before deletion of the pool. /// Must be set before the submission. /// </summary> [InternalDataApiName(IsFilterable = false, IsSelectable = false)] public TimeSpan CompletionTimeToLive { get { return _poolApi.CompletionTimeToLive; } set { _poolApi.CompletionTimeToLive = value; } } /// <summary> /// Default value of <see cref="QTask.WaitForPoolResourcesSynchronization" /> for pool's tasks /// </summary> public virtual bool? TaskDefaultWaitForPoolResourcesSynchronization { get { return _poolApi?.TaskDefaultWaitForPoolResourcesSynchronization; } } #endregion /// <summary> /// Create a new pool. /// </summary> /// <param name="connection">The inner connection object.</param> /// <param name="name">The pool name.</param> /// <param name="profile">The pool profile. If not specified, it must be given when the pool is started.</param> /// <param name="initialNodeCount">The number of compute nodes this pool will have. If not specified, it must be given when the pool is started.</param> /// <param name="shortname">optional unique friendly shortname of the pool.</param> /// <param name="taskDefaultWaitForPoolResourcesSynchronization">Default value for task's <see /// cref="QTask.WaitForPoolResourcesSynchronization" />, see also <see cref="TaskDefaultWaitForPoolResourcesSynchronization" /></param> public QPool(Connection connection, string name, string profile = null, uint initialNodeCount = 0, string shortname = default(string), bool? taskDefaultWaitForPoolResourcesSynchronization=null) : base(connection, new PoolApi()) { _poolApi.Name = name; _poolApi.Profile = profile; _poolApi.InstanceCount = initialNodeCount; _poolApi.TaskDefaultWaitForPoolResourcesSynchronization = taskDefaultWaitForPoolResourcesSynchronization; _resources = new List<QBucket>(); _constants = new Dictionary<string, string>(); _constraints = new Dictionary<string, string>(); if (shortname != default(string)) { _poolApi.Shortname = shortname; _uri = "pools/" + shortname; } } /// <summary> /// Create a pool object given an existing Uuid. /// </summary> /// <param name="connection">The inner connection object.</param> /// <param name="uuid">The Uuid of an already existing pool.</param> public QPool(Connection connection, Guid uuid) : this(connection, uuid.ToString()) { _uri = "pools/" + uuid.ToString(); _poolApi.Uuid = uuid; } internal QPool() {} internal QPool(Connection qapi, PoolApi poolApi) : base(qapi, poolApi) { _uri = "pools/" + poolApi.Uuid.ToString(); if (_resources == null) _resources = new List<QBucket>(); if (_constants == null) _constants = new Dictionary<string, string>(); if (_constraints == null) _constraints = new Dictionary<string, string>(); SyncFromApiObjectAsync(poolApi).Wait(); } internal async new Task<QPool> InitializeAsync(Connection qapi, PoolApi poolApi) { await base.InitializeAsync(qapi, poolApi); _uri = "pools/" + poolApi.Uuid.ToString(); if (_resources == null) _resources = new List<QBucket>(); if (_constants == null) _constants = new Dictionary<string, string>(); if (_constraints == null) _constraints = new Dictionary<string, string>(); await SyncFromApiObjectAsync(poolApi); return this; } internal async static Task<QPool> CreateAsync(Connection qapi, PoolApi poolApi) { return await new QPool().InitializeAsync(qapi, poolApi); } #region public methods /// <summary> /// Set the a list of tags for the pool. /// </summary> /// <param name="tags">Pool tags.</param> public virtual void SetTags(params String [] tags) { _poolApi.Tags = tags.Distinct().ToList(); } /// <summary> /// Set a new preparation Task. /// </summary> /// <param name="preparationTask">Pool Preparation Task.</param> public virtual void SetPreparationTask(PoolPreparationTask preparationTask) { _poolApi.PreparationTask = preparationTask; } /// <summary> /// Deprecated, use SetConstant. /// </summary> /// <param name="key">Constant name.</param> /// <param name="value">Constant value.</param> [Obsolete("use SetConstant")] public virtual void AddConstant(string key, string value) { this.SetConstant(key, value); } /// <summary> /// Set a constant. If the constant already exists, it is replaced (or removed if value is null). /// </summary> /// <param name="name">Constant name.</param> /// <param name="value">Constant value. If null, the constant is deleted.</param> public virtual void SetConstant(string name, string value) { // First, check if the constant already exists if (_constants.ContainsKey(name) && value == null) { // Just delete the constant _constants.Remove(name); return; } // Add or update the constant if (value != null) _constants[name] = value; } /// <summary> /// Set a constraint. If the constraint already exists, it is replaced (or removed if value is null). /// </summary> /// <param name="name">Constraint name.</param> /// <param name="value">Constraint value. If null, the constraint is deleted.</param> public virtual void SetConstraint(string name, string value) { // First, check if the constraints already exists if (_constraints.ContainsKey(name) && value == null) { // Delete a constraint _constraints.Remove(name); return; } // Add or update the constraint if (value != null) _constraints[name] = value; } /// <summary> /// Set a label. If the label already exists, it is replaced (or removed if value is null). /// </summary> /// <param name="name">Label name.</param> /// <param name="value">Label value. If null, the label is deleted.</param> public virtual void SetLabel(string name, string value) { // First, check if the constraints already exists if (Labels.ContainsKey(name) && value == null) { // Delete a constraint Labels.Remove(name); return; } // Add or update the constraint if (value != null) Labels[name] = value; } /// <summary> /// Commit the local pool changes. /// </summary> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns></returns> public virtual async Task CommitAsync(CancellationToken cancellationToken = default(CancellationToken)) { // build the constants _poolApi.Constants = new List<KeyValHelper>(); foreach(var c in _constants) { _poolApi.Constants.Add(new KeyValHelper(c.Key, c.Value)); } // build the constraints _poolApi.Constraints = new List<KeyValHelper>(); foreach(var c in _constraints) { _poolApi.Constraints.Add(new KeyValHelper(c.Key, c.Value)); } using (var response = await _api._client.PutAsJsonAsync<PoolApi>(_uri, _poolApi, cancellationToken)) await Utils.LookForErrorAndThrowAsync(_api._client, response); } /// <summary> /// Start the pool. /// </summary> /// <param name="profile">The pool profile. Optional if it has already been defined in the constructor.</param> /// <param name="initialNodeCount">The number of compute nodes this pool will have. Optional if it has already been defined in the constructor.</param> /// <returns></returns> public virtual async Task StartAsync(string profile = null, uint initialNodeCount = 0) { await StartAsync(default(CancellationToken), profile, initialNodeCount); } internal void PreSubmit(string profile=null, uint initialNodeCount=0) { // build the constants _poolApi.Constants = new List<KeyValHelper>(); foreach(var c in _constants) { _poolApi.Constants.Add(new KeyValHelper(c.Key, c.Value)); } // build the constraints _poolApi.Constraints = new List<KeyValHelper>(); foreach(var c in _constraints) { _poolApi.Constraints.Add(new KeyValHelper(c.Key, c.Value)); } _poolApi.ResourceBuckets = new List<string>(); bool useAdvancedResources = _resources.Any(res => res?.Filtering != null || res?.ResourcesTransformation != null); foreach (var item in _resources) { var resQBucket = item as QBucket; if (resQBucket != null) { if (useAdvancedResources) { _poolApi.AdvancedResourceBuckets.Add(new ApiAdvancedResourceBucket { BucketName = resQBucket.Shortname, Filtering = resQBucket.Filtering is BucketFilteringPrefix prefixFiltering ? new ApiBucketFiltering { PrefixFiltering = new ApiBucketFilteringPrefix { Prefix = _api._shouldSanitizeBucketPaths ? Utils.GetSanitizedBucketPath(prefixFiltering.Prefix, _api._showBucketWarnings) : prefixFiltering.Prefix } } : null, ResourcesTransformation = resQBucket.ResourcesTransformation is ResourcesTransformationStripPrefix stripPrefixTransformation ? new ApiResourcesTransformation { StripPrefix = new ApiResourcesTransformationStripPrefix { Prefix = _api._shouldSanitizeBucketPaths ? Utils.GetSanitizedBucketPath(stripPrefixTransformation.Prefix, _api._showBucketWarnings) : stripPrefixTransformation.Prefix } } : null, }); } else { _poolApi.ResourceBuckets.Add(resQBucket.Shortname); } } } if (profile != null) { _poolApi.Profile = profile; } if (initialNodeCount > 0) { _poolApi.InstanceCount = initialNodeCount; } } /// <summary> /// Start the pool. /// </summary> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <param name="profile">The pool profile. Optional if it has already been defined in the constructor.</param> /// <param name="initialNodeCount">The number of compute nodes this pool will have. Optional if it has already been defined in the constructor.</param> /// <returns></returns> public virtual async Task StartAsync(CancellationToken cancellationToken, string profile = null, uint initialNodeCount = 0) { PreSubmit(profile, initialNodeCount); if (_api.IsReadOnly) throw new Exception("Can't start pools, this connection is configured in read-only mode"); using (var response = await _api._client.PostAsJsonAsync<PoolApi> ("pools", _poolApi, cancellationToken)) { await Utils.LookForErrorAndThrowAsync(_api._client, response); // Update the pool Uuid var result = await response.Content.ReadAsAsync<PoolApi>(Utils.GetCustomResponseFormatter(), cancellationToken); _poolApi.Uuid = result.Uuid; _uri = "pools/" + _poolApi.Uuid.ToString(); } // Retrieve the pool status once to update the other fields (result bucket uuid etc..) await UpdateStatusAsync(cancellationToken); } /// <summary> /// Update this pool state and status. /// </summary> /// <param name="updateQBucketsInfo">If set to true, the resources qbucket objects are also updated.</param> /// <returns></returns> public virtual async Task UpdateStatusAsync(bool updateQBucketsInfo = false) { await UpdateStatusAsync(default(CancellationToken), updateQBucketsInfo); } private async Task SyncFromApiObjectAsync(PoolApi result) { _poolApi = result; // update constants _constants = result.Constants?.ToDictionary(kv => kv.Key, kv => kv.Value) ?? new Dictionary<string, string>(); // update constraints _constraints = result.Constraints?.ToDictionary(kv => kv.Key, kv => kv.Value) ?? new Dictionary<string, string>(); var newResourcesCount = 0; if (_poolApi.ResourceBuckets != null) newResourcesCount += _poolApi.ResourceBuckets.Count; if (_poolApi.AdvancedResourceBuckets != null) newResourcesCount += _poolApi.AdvancedResourceBuckets.Count; if (_resources.Count != newResourcesCount) { _resources.Clear(); if (_poolApi.ResourceBuckets != null) { foreach (var r in _poolApi.ResourceBuckets) { _resources.Add(await QBucket.CreateAsync(_api, r, create: false)); } } if (_poolApi.AdvancedResourceBuckets != null) { foreach (var r in _poolApi.AdvancedResourceBuckets) { _resources.Add(await QBucket.CreateAsync(_api, r, create: false)); } } } } /// <summary> /// Update this pool state and status. /// </summary> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <param name="updateQBucketsInfo">If set to true, the resources bucket objects are also updated.</param> /// <returns></returns> public virtual async Task UpdateStatusAsync(CancellationToken cancellationToken, bool updateQBucketsInfo = false) { using (var response = await _api._client.GetAsync(_uri, cancellationToken)) // get pool status { await Utils.LookForErrorAndThrowAsync(_api._client, response); var result = await response.Content.ReadAsAsync<PoolApi>(Utils.GetCustomResponseFormatter(), cancellationToken); await SyncFromApiObjectAsync(result); } if (updateQBucketsInfo) { foreach(var r in _resources) { await r.UpdateAsync(cancellationToken); } } } /// <summary> /// Delete the pool. If the pool is running, the pool is closed and deleted. /// </summary> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <param name="failIfDoesntExist">If set to false and the pool doesn't exist, no exception is thrown. Default is true.</param> /// <param name="purgeResources">Boolean to trigger all resource storages deletion. Default is false.</param> /// <returns></returns> public override async Task DeleteAsync(CancellationToken cancellationToken, bool failIfDoesntExist = false, bool purgeResources=false) { try { if (_api.IsReadOnly) throw new Exception("Can't delete pools, this connection is configured in read-only mode"); using (var response = await _api._client.DeleteAsync(_uri, cancellationToken)) await Utils.LookForErrorAndThrowAsync(_api._client, response); if (purgeResources) await Task.WhenAll(_resources.Select(r => r.DeleteAsync(cancellationToken))); } catch (QarnotApiResourceNotFoundException ex) { if (failIfDoesntExist) throw ex; } } #endregion #region helpers /// <summary> /// Return the public host and port to establish an inbound connection to the master compute node (node 0) running your pool. /// Note: your profile have to define one or more inbound connection to support that feature. For example, the profile "docker-network-ssh" /// defines a redirection to the ssh port 22. If you need inbound connections on a specific port, you can make a request to the support team. /// </summary> /// <param name="port">The port you want to access on the master compute node (node 0).</param> /// <returns>The host and port formated in a string "host:port".</returns> public virtual string GetPublicHostForApplicationPort(UInt16 port) { if (Status != null && Status.RunningInstancesInfo != null) { var instances = Status.RunningInstancesInfo.PerRunningInstanceInfo; if (instances != null && instances.Count > 0) { foreach (var i in instances) { if (i.ActiveForwards == null) continue; foreach (var af in i.ActiveForwards) { if (af.ApplicationPort == port) { return String.Format("{0}:{1}", af.ForwarderHost, af.ForwarderPort); } } } } } return null; } /// <summary> /// Get the status of a node given its node id. /// Note: the status of a node could be retrieved in the Status.RunningInstancesInfo.PerRunningInstanceInfo /// structure. This method provides an /// easy way to retrieve those information. /// </summary> /// <param name="nodeId">The id of the node.</param> /// <returns>The status of the node or null if not available.</returns> public virtual QPoolNodeStatus GetNodeStatus(UInt32 nodeId) { if (_poolApi.Status != null && _poolApi.Status.RunningInstancesInfo != null && _poolApi.Status.RunningInstancesInfo.PerRunningInstanceInfo != null) { foreach (var j in _poolApi.Status.RunningInstancesInfo.PerRunningInstanceInfo) { if (j.InstanceId == nodeId) { return new QPoolNodeStatus(j); } } } return null; } /// <summary> /// Get the list of the running nodes status. /// Note: the status of a node could be retrieved in the Status.RunningInstancesInfo.PerRunningInstanceInfo /// structure. This method provides an /// easy way to retrieve those information. /// </summary> /// <returns>The status list of nodes.</returns> public virtual List<QPoolNodeStatus> GetNodeStatusList() { return _poolApi ?.Status ?.RunningInstancesInfo ?.PerRunningInstanceInfo ?.Select(rii => new QPoolNodeStatus(rii)) .ToList() ?? new List<QPoolNodeStatus>(); } #endregion } /// <summary> /// Represents an unified an simplified version of a pool node status. /// </summary> public class QPoolNodeStatus { /// <summary> /// Retrieve the instance state. /// </summary> public virtual string State { get; set; } /// <summary> /// Retrieve the instance error /// </summary> public virtual QPoolError Error { get; set; } /// <summary> /// Retrieve the instance progress indicator /// </summary> public virtual float Progress { get; set; } /// <summary> /// Instance execution time(in seconds). /// </summary> public virtual float ExecutionTimeSec { get; set; } /// <summary> /// Instance execution time frequency(in seconds.ghz). /// </summary> public virtual float ExecutionTimeGHz { get; set; } /// <summary> /// Retrieve the instance wall time(in seconds). /// </summary> public virtual float WallTimeSec { get; set; } /// <summary> /// Informations about running instances (see QPoolStatusPerRunningInstanceInfo) /// </summary> public virtual QPoolStatusPerRunningInstanceInfo RunningNodeInfo { get; private set; } internal QPoolNodeStatus(QPoolStatusPerRunningInstanceInfo i) { // Phase is lowercase, convert the first letter to uppercase State = String.IsNullOrEmpty(i.Phase) ? "Unknown" : (i.Phase[0].ToString().ToUpper() + i.Phase.Substring(1)); Error = null; Progress = i.Progress; ExecutionTimeGHz = i.ExecutionTimeGHz; ExecutionTimeSec = i.ExecutionTimeSec; WallTimeSec = 0; RunningNodeInfo = i; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RectFileReader.cs" company="Microsoft"> // (c) Microsoft Corporation. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Routing; using Microsoft.Msagl.Routing.Visibility; namespace Microsoft.Msagl.UnitTests.Rectilinear { using System.Linq; using System.Text; using Core.DataStructures; using Core.Geometry; using Routing.Rectilinear; internal class RectFileReader : IDisposable { internal List<Shape> UnpaddedObstacles { get; private set; } internal List<Polyline> PaddedObstacles { get; private set; } internal List<EdgeGeometry> RoutingSpecs { get; private set; } internal List<LineSegment> HorizontalScanLineSegments { get; private set; } internal List<LineSegment> VerticalScanLineSegments { get; private set; } internal VisibilityGraph VisibilityGraph { get; private set; } internal int InitialSeed { get; private set; } internal string RandomObstacleArg { get; private set; } internal int RandomObstacleCount { get; private set; } internal string RandomObstacleDensity { get; private set; } internal bool RandomObstacleRotate { get; private set; } internal double Padding { get; private set; } internal double EdgeSeparation { get; private set; } internal bool RouteToCenter { get; private set; } internal double ArrowheadLength { get; private set; } private int fileVertexCount; private int fileEdgeCount; internal bool IsRandom { get; set; } // For reading the relationship between free relative ports and their shapes. internal Dictionary<Port, Shape> FreeRelativePortToShapeMap { get; private set; } internal bool UseFreePortsForObstaclePorts { get; private set; } internal bool UseSparseVisibilityGraph { get; private set; } internal bool UseObstacleRectangles { get; private set; } internal double BendPenalty { get; private set; } internal bool LimitPortVisibilitySpliceToEndpointBoundingBox { get; private set; } // Verification stuff. internal bool WantPaths { get; private set; } internal bool WantNudger { get; private set; } internal bool WantVerify { get; private set; } internal double StraightTolerance { get; private set; } internal double CornerTolerance { get; private set; } // Used by subroutines. private string currentLine; private int currentLineNumber; private StreamReader inputFileReader; private readonly Dictionary<int, Port> idToPortMap = new Dictionary<int, Port>(); private readonly Dictionary<int, Shape> idToShapeMap = new Dictionary<int, Shape>(); private readonly Dictionary<Shape, int> shapeToIdMap = new Dictionary<Shape, int>(); private readonly Dictionary<int, Polyline> idToPaddedPolylineMap = new Dictionary<int, Polyline>(); private readonly Dictionary<Tuple<Port, Port>, Curve> portsToPathMap = new Dictionary<Tuple<Port, Port>, Curve>(); // For clumps and convex hulls. private class ObstacleAccretion { internal readonly int Id; internal readonly List<int> SiblingIds = new List<int>(); internal Polyline Polyline; // Filled in by clump or convex hull verification. internal object RouterAccretion; internal ObstacleAccretion(int id) { this.Id = id; } } private readonly Dictionary<int, ObstacleAccretion> convexHullIdToAccretionMap = new Dictionary<int, ObstacleAccretion>(); private readonly Dictionary<int, ObstacleAccretion> shapeIdToConvexHullMap = new Dictionary<int, ObstacleAccretion>(); private readonly Dictionary<int, ObstacleAccretion> clumpIdToAccretionMap = new Dictionary<int, ObstacleAccretion>(); private readonly Dictionary<int, ObstacleAccretion> shapeIdToClumpMap = new Dictionary<int, ObstacleAccretion>(); // This is not "provably invalid" as any shape Id might have it but we currently don't // assign an id < 0 except for -1 for shapeId for FreePorts (which don't have a shape). private const int InvalidId = -42; private readonly TestPointComparer comparer; internal RectFileReader(string fileName, int fileRoundingDigits) { comparer = new TestPointComparer(fileRoundingDigits); UnpaddedObstacles = new List<Shape>(); PaddedObstacles = new List<Polyline>(); RoutingSpecs = new List<EdgeGeometry>(); HorizontalScanLineSegments = new List<LineSegment>(); VerticalScanLineSegments = new List<LineSegment>(); VisibilityGraph = new VisibilityGraph(); this.FreeRelativePortToShapeMap = new Dictionary<Port, Shape>(); this.inputFileReader = new StreamReader(fileName); this.RandomObstacleArg = RectFileStrings.NullStr; this.RandomObstacleDensity = RectFileStrings.NullStr; // Input parameters ReadHeader(); // Input detail ReadInputObstacles(); ReadPorts(); ReadRoutingSpecs(); // Output detail. ReadPaddedObstacles(); ReadConvexHulls(); ReadScanSegments(); ReadVisibilityGraph(); ReadPaths(); this.inputFileReader.Close(); if (0 == this.UnpaddedObstacles.Count) { Validate.Fail("No obstacles found in file"); } } private void ReadHeader() { // Input parameters and output summary Match m = ParseNext(RectFileStrings.ParseSeed); if (m.Success) { string strSeed = m.Groups["seed"].ToString(); System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer; if (strSeed.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { // For some reason the 0x prefix is not allowed for hex strings. strSeed = strSeed.Substring(2); style = System.Globalization.NumberStyles.HexNumber; } this.InitialSeed = int.Parse(strSeed, style); } m = ParseNext(RectFileStrings.ParseRandomArgs); if (!IsString(RectFileStrings.NullStr, m.Groups["arg"].ToString())) { this.IsRandom = true; this.RandomObstacleArg = m.Groups["arg"].ToString(); this.RandomObstacleCount = int.Parse(m.Groups["count"].ToString()); this.RandomObstacleDensity = m.Groups["density"].ToString(); this.RandomObstacleRotate = bool.Parse(m.Groups["rotate"].ToString()); } // This sequencing assumes the members are in the expected order but m = ParseNext(RectFileStrings.ParsePadding); this.Padding = double.Parse(m.Groups["padding"].ToString()); m = ParseNext(RectFileStrings.ParseEdgeSeparation); this.EdgeSeparation = double.Parse(m.Groups["sep"].ToString()); m = ParseNext(RectFileStrings.ParseRouteToCenter); this.RouteToCenter = bool.Parse(m.Groups["toCenter"].ToString()); m = ParseNext(RectFileStrings.ParseArrowheadLength); this.ArrowheadLength = double.Parse(m.Groups["length"].ToString()); m = this.ParseNext(RectFileStrings.ParseUseFreePortsForObstaclePorts); this.UseFreePortsForObstaclePorts = bool.Parse(m.Groups["value"].ToString()); m = this.ParseNext(RectFileStrings.ParseUseSparseVisibilityGraph); this.UseSparseVisibilityGraph = bool.Parse(m.Groups["value"].ToString()); m = this.ParseNext(RectFileStrings.ParseUseObstacleRectangles); this.UseObstacleRectangles = bool.Parse(m.Groups["value"].ToString()); m = ParseNext(RectFileStrings.ParseBendPenalty); this.BendPenalty = double.Parse(m.Groups["value"].ToString()); m = this.ParseNext(RectFileStrings.ParseLimitPortVisibilitySpliceToEndpointBoundingBox); this.LimitPortVisibilitySpliceToEndpointBoundingBox = bool.Parse(m.Groups["value"].ToString()); m = ParseNext(RectFileStrings.ParseWantPaths); this.WantPaths = bool.Parse(m.Groups["value"].ToString()); m = ParseNext(RectFileStrings.ParseWantNudger); this.WantNudger = bool.Parse(m.Groups["value"].ToString()); m = ParseNext(RectFileStrings.ParseWantVerify); this.WantVerify = bool.Parse(m.Groups["value"].ToString()); m = ParseNext(RectFileStrings.ParseStraightTolerance); this.StraightTolerance = double.Parse(m.Groups["value"].ToString()); m = ParseNext(RectFileStrings.ParseCornerTolerance); this.CornerTolerance = double.Parse(m.Groups["value"].ToString()); // Output summary m = ParseNext(RectFileStrings.ParseVisibilityGraphSummary); this.fileVertexCount = int.Parse(m.Groups["vcount"].ToString()); this.fileEdgeCount = int.Parse(m.Groups["ecount"].ToString()); } private void ReadInputObstacles() { this.ReadUnpaddedObstacles(); foreach (var sibList in this.shapeIdToClumpMap.Values.Select(acc => acc.SiblingIds)) { sibList.OrderBy(sibId => sibId); } foreach (var sibList in this.shapeIdToConvexHullMap.Values.Select(acc => acc.SiblingIds)) { sibList.OrderBy(sibId => sibId); } } private void ReadUnpaddedObstacles() { this.VerifyIsNextLine(RectFileStrings.BeginUnpaddedObstacles); // Get to the first line for consistency with the lookahead for children which will end up // reading the following line. this.NextLine(); for (;;) { int id; Shape shape; if (this.IsLine(RectFileStrings.BeginCurve)) { id = ParseNextId(); shape = new Shape(this.ReadCurve()) { UserData = id }; } else if (this.IsLine(RectFileStrings.BeginEllipse)) { id = ParseNextId(); shape = new Shape(this.ReadEllipse()) { UserData = id }; } else if (this.IsLine(RectFileStrings.BeginRoundedRect)) { id = ParseNextId(); shape = new Shape(this.ReadRoundedRect()) { UserData = id }; } else if (this.IsLine(RectFileStrings.BeginPolyline)) { id = ParseNextId(); shape = new Shape(this.ReadPolyline()) { UserData = id }; } else { this.VerifyIsLine(RectFileStrings.EndUnpaddedObstacles); return; } this.UnpaddedObstacles.Add(shape); idToShapeMap.Add(id, shape); shapeToIdMap.Add(shape, id); this.NextLine(); TryParseChildren(shape); this.TryParseClumpId(id); this.TryParseConvexHullId(id); } } private void TryParseChildren(Shape shape) { if (!IsLine(RectFileStrings.Children)) { return; } int id; while (TryParseNextId(out id)) { shape.AddChild(idToShapeMap[id]); } } private void TryParseClumpId(int shapeId) { Match m = this.TryParse(RectFileStrings.ParseClumpId); if (!m.Success) { return; } int clumpId = int.Parse(m.Groups["id"].ToString()); this.shapeIdToClumpMap[shapeId] = AddShapeToAccretion(shapeId, clumpId, this.clumpIdToAccretionMap); this.NextLine(); } private void TryParseConvexHullId(int shapeId) { Match m = this.TryParse(RectFileStrings.ParseConvexHullId); if (!m.Success) { return; } int convexHullId = int.Parse(m.Groups["id"].ToString()); this.shapeIdToConvexHullMap[shapeId] = AddShapeToAccretion(shapeId, convexHullId, this.convexHullIdToAccretionMap); this.NextLine(); } private static ObstacleAccretion AddShapeToAccretion(int shapeId, int accretionId, Dictionary<int, ObstacleAccretion> accretionMap) { ObstacleAccretion accretion; if (!accretionMap.TryGetValue(accretionId, out accretion)) { accretion = new ObstacleAccretion(accretionId); accretionMap[accretionId] = accretion; } accretion.SiblingIds.Add(shapeId); return accretion; } private void ReadPorts() { Match m; this.VerifyIsNextLine(RectFileStrings.BeginPorts); // Get to the first line for consistency with the lookahead for multiPort offsets and/or any // PortEntries, which will end up reading the following line. this.NextLine(); for (;;) { if (!(m = ParseOrDone(RectFileStrings.ParsePort, RectFileStrings.EndPorts)).Success) { break; } bool isMultiPort = IsString(m.Groups["type"].ToString(), RectFileStrings.Multi); bool isRelative = IsString(m.Groups["type"].ToString(), RectFileStrings.Relative); var x = double.Parse(m.Groups["X"].ToString()); var y = double.Parse(m.Groups["Y"].ToString()); var portId = int.Parse(m.Groups["portId"].ToString()); var shapeId = int.Parse(m.Groups["shapeId"].ToString()); Validate.IsFalse(idToPortMap.ContainsKey(portId), "PortId already exists"); var location = new Point(x, y); Shape shape = GetShapeFromId(shapeId, isMultiPort || isRelative); Port port; if (isMultiPort) { // 'location' was actually the active offset of the multiPort. Recreate it and reset the // closest-location and verify the active offset index is the same. This may fail if there // are two identical offsets in the offset list, in which case fix the test setup. int activeOffsetIndex; var offsets = ReadMultiPortOffsets(out activeOffsetIndex); var multiPort = new MultiLocationFloatingPort(() => shape.BoundaryCurve, () => shape.BoundingBox.Center, offsets); multiPort.SetClosestLocation(multiPort.CenterDelegate() + location); Validate.AreEqual(multiPort.ActiveOffsetIndex, activeOffsetIndex, CurrentLineError("ActiveOffsetIndex is not as expected")); port = multiPort; } else { if (isRelative) { // The location in the ParsePort line is the offset for the relative port. port = new RelativeFloatingPort(() => shape.BoundaryCurve, () => shape.BoundingBox.Center, location); } else { Validate.IsTrue(IsString(m.Groups["type"].ToString(), RectFileStrings.Floating), CurrentLineError("Unknown port type")); port = new FloatingPort((null == shape) ? null : shape.BoundaryCurve, location); } this.NextLine(); // Since we didn't read multiPort offsets } idToPortMap.Add(portId, port); if (null != shape) { if (!this.UseFreePortsForObstaclePorts) { shape.Ports.Insert(port); } else { FreeRelativePortToShapeMap[port] = shape; } } ReadPortEntries(port); } } private Shape GetShapeFromId(int shapeId, bool isMultiOrRelative) { Shape shape; if (!idToShapeMap.TryGetValue(shapeId, out shape)) { Validate.IsFalse(isMultiOrRelative, CurrentLineError("Shape not found for MultiOrRelativePort")); } return shape; } private List<Point> ReadMultiPortOffsets(out int activeOffsetIndex) { var offsets = new List<Point>(); Match m = ParseNext(RectFileStrings.ParseMultiPortOffsets); Validate.IsTrue(m.Success, CurrentLineError("Did not find expected MultiPortOffsets")); activeOffsetIndex = int.Parse(m.Groups["index"].ToString()); for (;;) { m = TryParseNext(RectFileStrings.ParsePoint); if (!m.Success) { break; } var x = double.Parse(m.Groups["X"].ToString()); var y = double.Parse(m.Groups["Y"].ToString()); offsets.Add(new Point(x, y)); } Validate.IsTrue(offsets.Count > 0, CurrentLineError("No offsets found for multiPort")); return offsets; } private void ReadPortEntries(Port port) { // We've already positioned ourselves to the next line in ReadPorts. if (!IsLine(RectFileStrings.PortEntryOnCurve)) { return; } var spans = new List<Tuple<double, double>>(); Match m; while ((m = TryParseNext(RectFileStrings.ParsePoint)).Success) { // We reuse ParsePoint because a span is just two doubles as well. var first = double.Parse(m.Groups["X"].ToString()); var second = double.Parse(m.Groups["Y"].ToString()); spans.Add(new Tuple<double, double>(first, second)); } Validate.IsTrue(spans.Count > 0, CurrentLineError("Empty span list")); port.PortEntry = new PortEntryOnCurve(port.Curve, spans); } private void ReadRoutingSpecs() { Match m; this.VerifyIsNextLine(RectFileStrings.BeginRoutingSpecs); // Get to the first line for consistency with the lookahead for waypoints, which will // end up reading the following line. this.NextLine(); for (;;) { if (!(m = ParseOrDone(RectFileStrings.ParseEdgeGeometry, RectFileStrings.EndRoutingSpecs)).Success) { break; } var sourceId = int.Parse(m.Groups["sourceId"].ToString()); var targetId = int.Parse(m.Groups["targetId"].ToString()); var arrowheadAtSource = bool.Parse(m.Groups["arrowheadAtSource"].ToString()); var arrowheadAtTarget = bool.Parse(m.Groups["arrowheadAtTarget"].ToString()); var arrowheadLength = double.Parse(m.Groups["arrowheadLength"].ToString()); var arrowheadWidth = double.Parse(m.Groups["arrowheadWidth"].ToString()); var lineWidth = double.Parse(m.Groups["lineWidth"].ToString()); Port sourcePort, targetPort; Validate.IsTrue(idToPortMap.TryGetValue(sourceId, out sourcePort), CurrentLineError("Can't find source port")); Validate.IsTrue(idToPortMap.TryGetValue(targetId, out targetPort), CurrentLineError("Can't find target port")); var edgeGeom = new EdgeGeometry(sourcePort, targetPort) { LineWidth = lineWidth }; if (arrowheadAtSource) { edgeGeom.SourceArrowhead = new Arrowhead { Length = arrowheadLength, Width = arrowheadWidth }; } if (arrowheadAtTarget) { edgeGeom.TargetArrowhead = new Arrowhead { Length = arrowheadLength, Width = arrowheadWidth }; } this.RoutingSpecs.Add(edgeGeom); this.ReadWaypoints(edgeGeom); } } private void ReadWaypoints(EdgeGeometry edgeGeom) { if (!IsNextLine(RectFileStrings.Waypoints)) { return; } var waypoints = new List<Point>(); Match m; while ((m = TryParseNext(RectFileStrings.ParsePoint)).Success) { // We reuse ParsePoint because a span is just two doubles as well. var x = double.Parse(m.Groups["X"].ToString()); var y = double.Parse(m.Groups["Y"].ToString()); waypoints.Add(new Point(x, y)); } Validate.IsTrue(waypoints.Count > 0, CurrentLineError("Empty waypoint list")); edgeGeom.Waypoints = waypoints; } private void ReadPaddedObstacles() { this.VerifyIsNextLine(RectFileStrings.BeginPaddedObstacles); for (;;) { if (!this.IsNextLine(RectFileStrings.BeginPolyline)) { this.VerifyIsLine(RectFileStrings.EndPaddedObstacles); break; } int id = ParseNextId(); Validate.IsFalse(idToPaddedPolylineMap.ContainsKey(id), CurrentLineError("Duplicate padded-obstacle id")); var polyline = this.ReadPolyline(); this.PaddedObstacles.Add(polyline); idToPaddedPolylineMap.Add(id, polyline); } } private void ReadConvexHulls() { this.VerifyIsNextLine(RectFileStrings.BeginConvexHulls); for (; ; ) { if (!this.IsNextLine(RectFileStrings.BeginPolyline)) { this.VerifyIsLine(RectFileStrings.EndConvexHulls); break; } int id = ParseNextId(); var hullAccretion = this.convexHullIdToAccretionMap[id]; Validate.AreEqual(id, hullAccretion.Id, "This should always be true.. accretion.Id is just to make debugging easier"); hullAccretion.Polyline = this.ReadPolyline(); } } public void VerifyObstaclePaddedPolylines(IEnumerable<Obstacle> routerObstacles) { if (0 == idToPaddedPolylineMap.Count) { return; } foreach (var routerObstacle in routerObstacles) { var filePolyline = idToPaddedPolylineMap[shapeToIdMap[routerObstacle.InputShape]]; var routerPolyline = routerObstacle.PaddedPolyline; VerifyPolylinesAreSame(filePolyline, routerPolyline); } } private void VerifyPolylinesAreSame(Polyline filePolyline, Polyline routerPolyline) { Validate.AreEqual(filePolyline.PolylinePoints.Count(), routerPolyline.PolylinePoints.Count(), "Different number of points in polyline"); Validate.IsTrue(comparer.Equals(filePolyline.StartPoint.Point, routerPolyline.StartPoint.Point), "Polyline StartPoints are not equal"); Validate.IsTrue(comparer.Equals(filePolyline.EndPoint.Point, routerPolyline.EndPoint.Point), "Polyline EndPoints are not equal"); var filePoint = filePolyline.StartPoint.NextOnPolyline; var obstaclePoint = routerPolyline.StartPoint.NextOnPolyline; while (!comparer.Equals(filePoint.Point, filePolyline.EndPoint.Point)) { Validate.IsTrue(comparer.Equals(filePoint.Point, obstaclePoint.Point), "Polyline Intermediate Points are not equal"); filePoint = filePoint.NextOnPolyline; obstaclePoint = obstaclePoint.NextOnPolyline; } } private void ReadScanSegments() { Match m; this.VerifyIsNextLine(RectFileStrings.BeginHScanSegments); for (;;) { if (!(m = ParseNextOrDone(RectFileStrings.ParseSegment, RectFileStrings.EndHScanSegments)).Success) { break; } this.HorizontalScanLineSegments.Add(LoadLineSegment(m)); } this.VerifyIsNextLine(RectFileStrings.BeginVScanSegments); for (;;) { if (!(m = ParseNextOrDone(RectFileStrings.ParseSegment, RectFileStrings.EndVScanSegments)).Success) { break; } this.VerticalScanLineSegments.Add(LoadLineSegment(m)); } } internal void VerifyScanSegments(RectilinearEdgeRouterWrapper router) { this.VerifyAxisScanSegments(this.HorizontalScanLineSegments, router.HorizontalScanLineSegments, "Horizontal ScanSegment"); this.VerifyAxisScanSegments(this.VerticalScanLineSegments, router.VerticalScanLineSegments, "Vertical ScanSegment"); } private void VerifyAxisScanSegments(List<LineSegment> readerSegmentList, IEnumerable<LineSegment> routerSegs, string name) { // These are already ordered as desired in the tree. if (0 != readerSegmentList.Count) { IEnumerator<LineSegment> readerSegs = readerSegmentList.GetEnumerator(); foreach (var routerSeg in routerSegs) { readerSegs.MoveNext(); var readerSeg = readerSegs.Current; Validate.IsTrue(comparer.IsClose(routerSeg, readerSeg), string.Format(System.Globalization.CultureInfo.InvariantCulture, "Router {0} does not match Reader", name)); } } } internal void VerifyClumps(RectilinearEdgeRouterWrapper router) { if (this.clumpIdToAccretionMap.Count == 0) { return; } VerifyThatAllRouterClumpsAreInFile(router); VerifyThatAllFileClumpsAreInRouter(router); } private void VerifyThatAllRouterClumpsAreInFile(RectilinearEdgeRouterWrapper router) { foreach (var routerClump in router.ObstacleTree.GetAllPrimaryObstacles().Where(obs => obs.IsOverlapped).Select(obs => obs.Clump).Distinct()) { var routerSiblings = routerClump.Select(obs => this.shapeToIdMap[obs.InputShape]).OrderBy(id => id).ToArray(); var fileClump = this.shapeIdToClumpMap[routerSiblings.First()]; fileClump.RouterAccretion = routerClump; VerifyOrderedSiblingLists(fileClump.SiblingIds, routerSiblings); // SiblingIds are already ordered } } private void VerifyThatAllFileClumpsAreInRouter(RectilinearEdgeRouterWrapper router) { foreach (var fileClump in this.clumpIdToAccretionMap.Values) { var firstSibling = this.idToShapeMap[fileClump.SiblingIds.First()]; var firstObstacle = router.ShapeToObstacleMap[firstSibling]; // We've already verified all the router clumps, so we now just need to know that we do have a router clump. Validate.AreSame(fileClump.RouterAccretion, firstObstacle.Clump, "Clump from file was not found in router"); } } internal void VerifyConvexHulls(RectilinearEdgeRouterWrapper router) { if (this.convexHullIdToAccretionMap.Count == 0) { return; } VerifyThatAllRouterHullsAreInFile(router); VerifyThatAllFileHullsAreInRouter(router); } private void VerifyThatAllRouterHullsAreInFile(RectilinearEdgeRouterWrapper router) { foreach (var routerHull in router.ObstacleTree.GetAllPrimaryObstacles().Where(obs => obs.ConvexHull != null).Select(obs => obs.ConvexHull)) { var routerSiblings = routerHull.Obstacles.Select(obs => this.shapeToIdMap[obs.InputShape]).OrderBy(id => id).ToArray(); var fileHull = this.shapeIdToConvexHullMap[routerSiblings.First()]; fileHull.RouterAccretion = routerHull; VerifyOrderedSiblingLists(fileHull.SiblingIds, routerSiblings); // SiblingIds are already ordered // This may be null if -nowriteConvexHulls if (fileHull.Polyline != null) { this.VerifyPolylinesAreSame(fileHull.Polyline, routerHull.Polyline); } // Convex Hulls can exist for both groups and non-groups. For groups, there should only be one obstacle, // the group, in the hull. var firstSibling = this.idToShapeMap[routerSiblings.First()]; if (firstSibling.IsGroup) { Validate.AreEqual(1, routerSiblings.Count(), "only one item should be in a convex hull for a group"); } else { Validate.IsFalse(routerSiblings.Any(sib => this.idToShapeMap[sib].IsGroup), "group found with non-groups in a convex hull"); } } } private void VerifyThatAllFileHullsAreInRouter(RectilinearEdgeRouterWrapper router) { foreach (var fileHull in this.convexHullIdToAccretionMap.Values) { var firstSibling = this.idToShapeMap[fileHull.SiblingIds.First()]; var firstObstacle = router.ShapeToObstacleMap[firstSibling]; // We've already verified all the router hulls, so we now just need to know that we do have a router hull. Validate.AreSame(fileHull.RouterAccretion, firstObstacle.ConvexHull, "Convex hull from file was not found in router"); } } private static void VerifyOrderedSiblingLists(List<int> fileSiblings, int[] routerSiblings) { Validate.AreEqual(fileSiblings.Count, routerSiblings.Length, "Unequal number of file and router siblings"); for (int ii = 0; ii < routerSiblings.Length; ++ii) { Validate.AreEqual(fileSiblings[ii], routerSiblings[ii], "File and router siblings differ"); } } private void ReadVisibilityGraph() { Match m; this.VerifyIsNextLine(RectFileStrings.BeginVisibilityVertices); for (;;) { if (!(m = ParseNextOrDone(RectFileStrings.ParsePoint, RectFileStrings.EndVisibilityVertices)).Success) { break; } var x = double.Parse(m.Groups["X"].ToString()); var y = double.Parse(m.Groups["Y"].ToString()); this.VisibilityGraph.AddVertex(ApproximateComparer.Round(new Point(x, y))); } this.VerifyIsNextLine(RectFileStrings.BeginVisibilityEdges); for (;;) { if (!(m = ParseNextOrDone(RectFileStrings.ParseSegment, RectFileStrings.EndVisibilityEdges)).Success) { break; } var startX = double.Parse(m.Groups["startX"].ToString()); var startY = double.Parse(m.Groups["startY"].ToString()); var endX = double.Parse(m.Groups["endX"].ToString()); var endY = double.Parse(m.Groups["endY"].ToString()); this.VisibilityGraph.AddEdge(ApproximateComparer.Round(new Point(startX, startY)), ApproximateComparer.Round(new Point(endX, endY))); } } internal void VerifyVisibilityGraph(RectilinearEdgeRouterWrapper router) { Validate.AreEqual(this.fileVertexCount, router.VisibilityGraph.VertexCount, "Graph vertex count difference"); // If the vertices and edges were stored to the file, verify them. if (0 != this.VisibilityGraph.VertexCount) { foreach (var fileVertex in this.VisibilityGraph.Vertices()) { Validate.IsNotNull(router.VisibilityGraph.FindVertex(fileVertex.Point), "Cannot find file vertex in router graph"); } foreach (var routerVertex in router.VisibilityGraph.Vertices()) { Validate.IsNotNull(this.VisibilityGraph.FindVertex(routerVertex.Point), "Cannot find router vertex in file graph"); } foreach (var fileEdge in this.VisibilityGraph.Edges) { Validate.IsNotNull(VisibilityGraph.FindEdge(fileEdge), "Cannot find file edge in router graph"); } foreach (var routerEdge in router.VisibilityGraph.Edges) { Validate.IsNotNull(VisibilityGraph.FindEdge(routerEdge), "Cannot find router edge in file graph"); } } } private void ReadPaths() { Match m; this.VerifyIsNextLine(RectFileStrings.BeginPaths); for (;;) { if (!(m = ParseNextOrDone(RectFileStrings.ParsePathEndpoints, RectFileStrings.EndPaths)).Success) { break; } var sourceId = int.Parse(m.Groups["sourceId"].ToString()); var targetId = int.Parse(m.Groups["targetId"].ToString()); Port sourcePort, targetPort; Validate.IsTrue(idToPortMap.TryGetValue(sourceId, out sourcePort), CurrentLineError("Can't find source port")); Validate.IsTrue(idToPortMap.TryGetValue(targetId, out targetPort), CurrentLineError("Can't find target port")); this.VerifyIsNextLine(RectFileStrings.BeginCurve); var curve = this.ReadCurve(); portsToPathMap.Add(new Tuple<Port, Port>(sourcePort, targetPort), curve); } } private void VerifyPaths(RectilinearEdgeRouterWrapper router) { IEnumerable<EdgeGeometry> routerEdgeGeometries = router.EdgeGeometriesToRoute; foreach (EdgeGeometry routerEdgeGeom in routerEdgeGeometries.Where(edgeGeom => null != edgeGeom.Curve)) { Curve fileCurve; if (this.portsToPathMap.TryGetValue(new Tuple<Port, Port>(routerEdgeGeom.SourcePort, routerEdgeGeom.TargetPort), out fileCurve)) { var routerCurve = (Curve)routerEdgeGeom.Curve; // This is currently always a Curve this.VerifyCurvesAreSame(fileCurve, routerCurve); } } } private void VerifyCurvesAreSame(Curve fileCurve, Curve routerCurve) { var fileSegments = fileCurve.Segments; var routerSegments = routerCurve.Segments; Validate.AreEqual(fileSegments.Count, routerSegments.Count, "Unequal Curve segment counts"); for (int ii = 0; ii < fileSegments.Count; ++ii) { Validate.IsTrue(comparer.IsClose(fileSegments[ii].Start, routerSegments[ii].Start), "Unequal Curve segment Start"); Validate.IsTrue(comparer.IsClose(fileSegments[ii].End, routerSegments[ii].End), "Unequal Curve segment End"); } } public void VerifyRouter(RectilinearEdgeRouterWrapper router) { if (router.WantVerify) { VerifyVisibilityGraph(router); VerifyPaths(router); } } private Curve ReadCurve() { var c = new Curve(); Match m; while ((m = ParseNextOrDone(RectFileStrings.ParseSegment, RectFileStrings.EndCurve)).Success) { c.AddSegment(LoadLineSegment(m)); } return c; } private static LineSegment LoadLineSegment(Match m) { var startX = double.Parse(m.Groups["startX"].ToString()); var startY = double.Parse(m.Groups["startY"].ToString()); var endX = double.Parse(m.Groups["endX"].ToString()); var endY = double.Parse(m.Groups["endY"].ToString()); return new LineSegment(new Point(startX, startY), new Point(endX, endY)); } private Ellipse ReadEllipse() { Match m = ParseNext(RectFileStrings.ParseEllipse); var axisAx = double.Parse(m.Groups["axisAx"].ToString()); var axisAy = double.Parse(m.Groups["axisAy"].ToString()); var axisBx = double.Parse(m.Groups["axisBx"].ToString()); var axisBy = double.Parse(m.Groups["axisBy"].ToString()); var centerX = double.Parse(m.Groups["centerX"].ToString()); var centerY = double.Parse(m.Groups["centerY"].ToString()); VerifyIsNextLine(RectFileStrings.EndEllipse); return new Ellipse(new Point(axisAx, axisAy), new Point(axisBx, axisBy), new Point(centerX, centerY)); } private RoundedRect ReadRoundedRect() { Match m = ParseNext(RectFileStrings.ParseRoundedRect); var x = double.Parse(m.Groups["X"].ToString()); var y = double.Parse(m.Groups["Y"].ToString()); var width = double.Parse(m.Groups["width"].ToString()); var height = double.Parse(m.Groups["height"].ToString()); var radiusX = double.Parse(m.Groups["radiusX"].ToString()); var radiusY = double.Parse(m.Groups["radiusY"].ToString()); VerifyIsNextLine(RectFileStrings.EndRoundedRect); return new RoundedRect(new Rectangle(x, y, x + width, y + height), radiusX, radiusY); } private Polyline ReadPolyline() { var p = new Polyline(); Match m; while ((m = ParseNextOrDone(RectFileStrings.ParsePoint, RectFileStrings.EndPolyline)).Success) { var x = double.Parse(m.Groups["X"].ToString()); var y = double.Parse(m.Groups["Y"].ToString()); p.AddPoint(new Point(x, y)); } p.Closed = true; return p; } private void NextLine() { while ((this.currentLine = this.inputFileReader.ReadLine()) != null) { ++this.currentLineNumber; if (this.currentLine.StartsWith("//", StringComparison.CurrentCultureIgnoreCase)) { continue; } this.currentLine = this.currentLine.Trim(); if (string.IsNullOrEmpty(this.currentLine)) { continue; } return; } // We only call this when we expect a line. Validate.Fail("Unexpected EOF in source file"); } private Match ParseNext(Regex rgx) { NextLine(); return Parse(rgx); } private Match Parse(Regex rgx) { Match m = rgx.Match(this.currentLine); if (!m.Success) { Validate.Fail(CurrentLineError("Unexpected Parse mismatch")); } return m; } private Match TryParseNext(Regex rgx) { NextLine(); return TryParse(rgx); } private Match TryParse(Regex rgx) { Match m = rgx.Match(this.currentLine); return m; } private Match ParseNextOrDone(Regex rgx, string strDone) { NextLine(); return ParseOrDone(rgx, strDone); } private Match ParseOrDone(Regex rgx, string strDone) { Match m = rgx.Match(this.currentLine); if (m.Success) { return m; } if (!this.IsLine(strDone)) { Validate.Fail(CurrentLineError("Unexpected ParseOrDone mismatch")); } return m; } private int ParseNextId() { NextLine(); return ParseId(); } private int ParseId() { int id; if (!TryParseId(out id)) { Validate.Fail(CurrentLineError("Unexpected ParseNextId mismatch")); } return id; } private bool TryParseNextId(out int id) { this.NextLine(); return TryParseId(out id); } private bool TryParseId(out int id) { Match m = TryParse(RectFileStrings.ParseId); id = InvalidId; if (!m.Success) { return false; } id = int.Parse(m.Groups["id"].ToString()); return true; } private void VerifyIsNextLine(string strTest) { NextLine(); VerifyIsLine(strTest); } private void VerifyIsLine(string strTest) { if (!IsLine(strTest)) { Validate.Fail(CurrentLineError("Unexpected mismatch: expected {0}", strTest)); } } private bool IsNextLine(string strTest) { NextLine(); return IsLine(strTest); } private bool IsLine(string strTest) { return IsString(strTest, this.currentLine); } private static bool IsString(string strWant, string strTest) { return 0 == string.Compare(strWant, strTest, StringComparison.CurrentCultureIgnoreCase); } private string CurrentLineError(string format, params object[] args) { var details = string.Format(format, args); return string.Format("{0} on line {1}: {2}", details, this.currentLineNumber, this.currentLine); } #region IDisposable Members public void Dispose() { if (null != this.inputFileReader) { this.inputFileReader.Dispose(); this.inputFileReader = null; } } #endregion } }
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * 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.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { #region .NET /// <summary>Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath); } /// <summary>Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, searchPattern, null, null, null, PathFormat.RelativePath); } /// <summary>Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>, and optionally searches subdirectories.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/> and <paramref name="searchOption"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="searchOption"> /// One of the <see cref="SearchOption"/> enumeration values that specifies whether the <paramref name="searchOption"/> /// should include only the current directory or should include all subdirectories. /// </param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, searchPattern, searchOption, null, null, PathFormat.RelativePath); } #endregion // .NET /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, Path.WildcardStarMatchAll, null, null, null, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, searchPattern, null, null, null, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>, and optionally searches subdirectories.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/> and <paramref name="searchOption"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="searchOption"> /// One of the <see cref="SearchOption"/> enumeration values that specifies whether the <paramref name="searchOption"/> /// should include only the current directory or should include all subdirectories. /// </param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, searchPattern, searchOption, null, null, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, Path.WildcardStarMatchAll, null, options, null, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, Path.WildcardStarMatchAll, null, options, null, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, searchPattern, null, options, null, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, searchPattern, null, options, null, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="filters">The specification of custom filters to be used in the process.</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, Path.WildcardStarMatchAll, null, null, filters, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="filters">The specification of custom filters to be used in the process.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, Path.WildcardStarMatchAll, null, null, filters, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> /// <param name="filters">The specification of custom filters to be used in the process.</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, Path.WildcardStarMatchAll, null, options, filters, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> /// <param name="filters">The specification of custom filters to be used in the process.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, Path.WildcardStarMatchAll, null, options, filters, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> /// <param name="filters">The specification of custom filters to be used in the process.</param> [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, searchPattern, null, options, filters, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> /// <param name="filters">The specification of custom filters to be used in the process.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] [Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")] public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(null, null, path, searchPattern, null, options, filters, pathFormat); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using Scaffolder.Core.Base; using Scaffolder.Core.Data; using Scaffolder.Core.Meta; namespace Scaffolder.Core.Engine.Sql { public class SqlSchemaBuilder : SchemeBuilderBase { private class ReferenceDetails { public String Table { get; set; } public String Column { get; set; } public Reference Reference { get; set; } } private readonly IEnumerable<ReferenceDetails> _references; public SqlSchemaBuilder(IDatabase db) : base(db) { _references = GetForeignKeys(); } protected override Table GetDataTable(string name) { var sql = @"SELECT COLUMN_NAME, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName"; var table = new Table(name); var parameters = new Dictionary<string, object> { { "@TableName", name } }; var keyColumns = GetTablePrimaryKeys(name); var identityColumns = GetTableIdentityColumns(name); _db.Execute(sql, r => MapTableColumns(table, r, _references, keyColumns, identityColumns), parameters); return table; } protected override IEnumerable<string> GetTablePrimaryKeys(string name) { var sql = @"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu ON tc.CONSTRAINT_NAME = ccu.Constraint_name WHERE tc.CONSTRAINT_TYPE = 'Primary Key' AND tc.TABLE_NAME = @TableName"; var parameters = new Dictionary<string, object> { { "@TableName", name } }; return _db.Execute(sql, r => r["COLUMN_NAME"].ToString(), parameters).ToList(); } protected override IEnumerable<String> GetDatabaseTables() { var sql = "SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME != 'sysdiagrams'"; var tables = _db.Execute(sql, r => r[0].ToString()); return tables; } private IEnumerable<string> GetTableIdentityColumns(string name) { var sql = @"select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA = 'dbo' and COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 AND TABLE_NAME = @TableName order by TABLE_NAME"; var parameters = new Dictionary<string, object> { { "@TableName", name } }; return _db.Execute(sql, r => r["COLUMN_NAME"].ToString(), parameters).ToList(); } private IEnumerable<ReferenceDetails> GetForeignKeys() { var sql = @"SELECT RC.CONSTRAINT_NAME FK_Name , KF.TABLE_SCHEMA FK_Schema , KF.TABLE_NAME FK_Table , KF.COLUMN_NAME FK_Column , RC.UNIQUE_CONSTRAINT_NAME PK_Name , KP.TABLE_SCHEMA PK_Schema , KP.TABLE_NAME PK_Table , KP.COLUMN_NAME PK_Column , RC.MATCH_OPTION MatchOption , RC.UPDATE_RULE UpdateRule , RC.DELETE_RULE DeleteRule FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KF ON RC.CONSTRAINT_NAME = KF.CONSTRAINT_NAME JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KP ON RC.UNIQUE_CONSTRAINT_NAME = KP.CONSTRAINT_NAME"; var references = _db.Execute(sql, MapReferenceDetails); return references; } private static ReferenceDetails MapReferenceDetails(IDataReader r) { var table = Convert.ToString(r["FK_Table"]); var column = Convert.ToString(r["FK_Column"]); var reference = new Reference { Table = Convert.ToString(r["PK_Table"]), TextColumn = Convert.ToString(r["PK_Column"]), KeyColumn = Convert.ToString(r["PK_Column"]), }; return new ReferenceDetails { Table = table, Column = column, Reference = reference }; } private static Table MapTableColumns(Table t, IDataRecord r, IEnumerable<ReferenceDetails> references, IEnumerable<string> keyColumns, IEnumerable<string> identityColumns) { var columnName = r["COLUMN_NAME"].ToString(); var columnType = ParseColumnType(r["DATA_TYPE"].ToString(), r["COLUMN_NAME"].ToString()); var reference = references.Where(o => o.Table == t.Name && o.Column == columnName) .Select(o => o.Reference) .SingleOrDefault(); var column = new Column { Type = columnType, Position = 1, Name = columnName, Title = columnName, IsNullable = r["IS_NULLABLE"].ToString() == "YES", ShowInGrid = ShowInGrid(columnType, columnName), IsKey = keyColumns.Contains(columnName), Readonly = false, AutoIncrement = identityColumns.Contains(columnName), Description = "", MaxLength = null, Reference = reference, MaxValue = null, MinValue = null }; if (column.Type == ColumnType.DateTime) { column.MinValue = new DateTime(1753, 1, 1); } if (t.Columns.Count > 0) { column.Position = t.Columns.Max(o => o.Position) + 1; } t.Columns.Add(column); return t; } private static ColumnType ParseColumnType(string type, string name) { name = name.ToLower(); type = type.ToLower(); if (type == "nvarchar" || type == "varchar" || type == "ntext" || type == "text" || type == "nchar") { if (name.Contains("password")) return ColumnType.Password; if (name.Contains("content") || name.Contains("html")) return ColumnType.HTML; if (name.Contains("image") || name.Contains("picture") || name.Contains("logo") || name.Contains("background")) return ColumnType.Image; if (name.Contains("phone")) return ColumnType.Phone; if (name.Contains("email")) return ColumnType.Email; if (name.Contains("link") || name.Contains("url")) return ColumnType.Url; return ColumnType.Text; } else if (type == "int" || type == "tinyint") { return ColumnType.Integer; } else if (type == "datetime") { return ColumnType.DateTime; } if (type == "date") { return ColumnType.Date; } else if (type == "float") { return ColumnType.Double; } if (type == "bit") { return ColumnType.Boolean; } if (type == "varbinary") { return ColumnType.Binary; } if (type == "uniqueidentifier") { return ColumnType.Guid; } else { throw new NotSupportedException(); } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; public partial class TypeSystemForCodeTransformation { [Runtime.ConfigurationOption( "ExcludeDebuggerHooks" )] public bool ExcludeDebuggerHooks; //--// [CompilationSteps.NewEntityNotification] private void Notify_NewBoxedType( TypeRepresentation td ) { // // Make sure that there's a boxed representation for each value type. // if(td is ValueTypeRepresentation) { CreateBoxedValueType( td ); } } [CompilationSteps.NewEntityNotification] private void Notify_CheckArrays( TypeRepresentation td ) { if(td is SzArrayReferenceTypeRepresentation) { var elementType = td.ContainedType; // // For a non-generic array, we need to instantiate also the helper class. // It will provide the implementation for the runtime methods. // if(elementType.IsOpenType == false) { CreateInstantiationOfGenericTemplate( this.WellKnownTypes.Microsoft_Zelig_Runtime_SZArrayHelper, elementType ); } } } [CompilationSteps.NewEntityNotification] private void Notify_CheckForComparerInstantiation( MethodRepresentation md ) { if(md.Name == "CreateComparer") { var td = md.OwnerType; if(td.IsGenericInstantiation) { if(td.GenericTemplate == this.WellKnownTypes.System_Collections_Generic_Comparer_of_T) { var tdParam = td.GenericParameters[0]; //// private static Comparer<T> CreateComparer() //// { //// Type t = typeof( T ); //// //// // If T implements IComparable<T> return a GenericComparer<T> //// if(typeof( IComparable<T> ).IsAssignableFrom( t )) //// { //// //return (Comparer<T>)Activator.CreateInstance(typeof(GenericComparer<>).MakeGenericType(t)); //// return (Comparer<T>)(typeof( GenericComparer<int> ).TypeHandle.CreateInstanceForAnotherGenericParameter( t )); //// } //// //// // If T is a Nullable<U> where U implements IComparable<U> return a NullableComparer<U> //// if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof( Nullable<> )) //// { //// Type u = t.GetGenericArguments()[0]; //// if(typeof( IComparable<> ).MakeGenericType( u ).IsAssignableFrom( u )) //// { //// //return (Comparer<T>)Activator.CreateInstance(typeof(NullableComparer<>).MakeGenericType(u)); //// return (Comparer<T>)(typeof( NullableComparer<int> ).TypeHandle.CreateInstanceForAnotherGenericParameter( u )); //// } //// } //// //// // Otherwise return an ObjectComparer<T> //// return new ObjectComparer<T>(); //// } if(tdParam.FindInstantiationOfGenericInterface( (InterfaceTypeRepresentation)this.WellKnownTypes.System_IComparable_of_T, tdParam ) != null) { var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_GenericComparer_of_T, tdParam ); CreateComparerHelper( md, newTd ); } if(tdParam.GenericTemplate == this.WellKnownTypes.System_Nullable_of_T) { var tdParam2 = tdParam.GenericParameters[0]; if(td.FindInstantiationOfGenericInterface( (InterfaceTypeRepresentation)this.WellKnownTypes.System_IComparable_of_T, tdParam2 ) != null) { var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_NullableComparer_of_T, tdParam2 ); CreateComparerHelper( md, newTd ); return; } } { var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_ObjectComparer_of_T, tdParam ); CreateComparerHelper( md, newTd ); return; } } } } } [CompilationSteps.NewEntityNotification] private void Notify_CheckForEqualityComparerInstantiation( MethodRepresentation md ) { if(md.Name == "CreateComparer") { var td = md.OwnerType; if(td.IsGenericInstantiation) { if(td.GenericTemplate == this.WellKnownTypes.System_Collections_Generic_EqualityComparer_of_T) { var tdParam = td.GenericParameters[0]; //// private static EqualityComparer<T> CreateComparer() //// { //// Type t = typeof( T ); //// //// // Specialize type byte for performance reasons //// if(t == typeof( byte )) //// { //// return (EqualityComparer<T>)(object)(new ByteEqualityComparer()); //// } //// //// // If T implements IEquatable<T> return a GenericEqualityComparer<T> //// if(typeof( IEquatable<T> ).IsAssignableFrom( t )) //// { //// //return (EqualityComparer<T>)Activator.CreateInstance(typeof(GenericEqualityComparer<>).MakeGenericType(t)); //// return (EqualityComparer<T>)(typeof( GenericEqualityComparer<int> ).TypeHandle.CreateInstanceForAnotherGenericParameter( t )); //// } //// //// // If T is a Nullable<U> where U implements IEquatable<U> return a NullableEqualityComparer<U> //// if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof( Nullable<> )) //// { //// Type u = t.GetGenericArguments()[0]; //// if(typeof( IEquatable<> ).MakeGenericType( u ).IsAssignableFrom( u )) //// { //// //return (EqualityComparer<T>)Activator.CreateInstance(typeof(NullableEqualityComparer<>).MakeGenericType(u)); //// return (EqualityComparer<T>)(typeof( NullableEqualityComparer<int> ).TypeHandle.CreateInstanceForAnotherGenericParameter( u )); //// } //// } //// //// // Otherwise return an ObjectEqualityComparer<T> //// return new ObjectEqualityComparer<T>(); //// } if(tdParam.FindInstantiationOfGenericInterface( (InterfaceTypeRepresentation)this.WellKnownTypes.System_IEquatable_of_T, tdParam ) != null) { var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_GenericEqualityComparer_of_T, tdParam ); CreateComparerHelper( md, newTd ); return; } if(tdParam.GenericTemplate == this.WellKnownTypes.System_Nullable_of_T) { var tdParam2 = tdParam.GenericParameters[0]; if(td.FindInstantiationOfGenericInterface( (InterfaceTypeRepresentation)this.WellKnownTypes.System_IEquatable_of_T, tdParam2 ) != null) { var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_NullableEqualityComparer_of_T, tdParam2 ); CreateComparerHelper( md, newTd ); return; } } { var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_ObjectEqualityComparer_of_T, tdParam ); CreateComparerHelper( md, newTd ); return; } } } } } private void CreateComparerHelper( MethodRepresentation md , TypeRepresentation newTd ) { var cfg = (ControlFlowGraphStateForCodeTransformation)this.CreateControlFlowGraphState( md ); var bb = cfg.CreateFirstNormalBasicBlock(); // // Allocate helper. // bb.AddOperator( ObjectAllocationOperator.New( null, newTd, cfg.ReturnValue ) ); cfg.AddReturnOperator(); } //--//--// //// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Internals_TypeDependencyAttribute" )] //// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_TypeDependencyAttribute" )] //// private void Notify_TypeDependencyAttribute( ref bool fKeep , //// CustomAttributeRepresentation ca , //// TypeRepresentation owner ) //// { //// } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Internals_WellKnownFieldAttribute" )] [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_WellKnownFieldAttribute" )] private void Notify_WellKnownFieldAttribute( ref bool fKeep , CustomAttributeRepresentation ca , FieldRepresentation owner ) { fKeep = false; string fieldName = (string)ca.FixedArgsValues[0]; FieldRepresentation fdOld = this.GetWellKnownFieldNoThrow( fieldName ); if(fdOld != null && fdOld != owner) { throw TypeConsistencyErrorException.Create( "Found the well-known field '{0}' defined more than once: {1} and {2}", fieldName, fdOld, owner ); } this.SetWellKnownField( fieldName, owner ); } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Internals_WellKnownMethodAttribute" )] [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_WellKnownMethodAttribute" )] private void Notify_WellKnownMethodAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; if(owner.IsOpenMethod) { throw TypeConsistencyErrorException.Create( "WellKnownMethodAttribute cannot be applied to a generic method: {0}", owner ); } string methodName = (string)ca.FixedArgsValues[0]; MethodRepresentation mdOld = this.GetWellKnownMethodNoThrow( methodName ); if(mdOld != null && mdOld != owner) { throw TypeConsistencyErrorException.Create( "Found the well-known method '{0}' defined more than once: {1} and {2}", methodName, mdOld, owner ); } this.SetWellKnownMethod( methodName, owner ); } //--// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_ForceDevirtualizationAttribute" )] private void Notify_ForceDevirtualizationAttribute( ref bool fKeep , CustomAttributeRepresentation ca , TypeRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.ForceDevirtualization; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_ImplicitInstanceAttribute" )] private void Notify_ImplicitInstanceAttribute( ref bool fKeep , CustomAttributeRepresentation ca , TypeRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.ImplicitInstance; } [CompilationSteps.CustomAttributeNotification( "System_FlagsAttribute" )] private void Notify_FlagsAttribute( ref bool fKeep , CustomAttributeRepresentation ca , TypeRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.FlagsAttribute; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_InlineAttribute" )] private void Notify_InlineAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.Inline; owner.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.NoInline; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_NoInlineAttribute" )] private void Notify_NoInlineAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoInline; owner.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.Inline; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_BottomOfCallStackAttribute" )] private void Notify_BottomOfCallStackAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.BottomOfCallStack; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_SaveFullProcessorContextAttribute" )] private void Notify_SaveFullProcessorContextAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.SaveFullProcessorContext; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_NoReturnAttribute" )] private void Notify_NoReturnAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoReturn; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_CannotAllocateAttribute" )] private void Notify_CannotAllocateAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.CannotAllocate; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_CanAllocateOnReturnAttribute" )] private void Notify_CanAllocateOnReturnAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.CanAllocateOnReturn; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_StackNotAvailableAttribute" )] private void Notify_StackNotAvailableAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.StackNotAvailable; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_StackAvailableOnReturnAttribute" )] private void Notify_StackAvailableOnReturnAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.StackAvailableOnReturn; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_DisableBoundsChecksAttribute" )] private void Notify_DisableBoundsChecksAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; if(ca.GetNamedArg( "ApplyRecursively" ) != null) { owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.DisableDeepBoundsChecks; } else { owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.DisableBoundsChecks; } } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_DisableNullChecksAttribute" )] private void Notify_DisableNullChecksAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; if(ca.GetNamedArg( "ApplyRecursively" ) != null) { owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.DisableDeepNullChecks; } else { owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.DisableNullChecks; } } //LON: 2/16/09 [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_ImportedMethodReferenceAttribute" )] private void Notify_ImportedMethodReferenceAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = true; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.Imported; // for now disable inlining of these methods owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoInline; owner.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.Inline; } //LON: 2/16/09 [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_ExportedMethodAttribute" )] private void Notify_ExportedMethodAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.Exported; // for now disable inlining of these methods owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoInline; owner.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.Inline; } //--// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_GarbageCollectionExtensionAttribute" )] private void Notify_GarbageCollectionExtensionAttribute( ref bool fKeep , CustomAttributeRepresentation ca , TypeRepresentation owner ) { var td = (TypeRepresentation)ca.FixedArgsValues[0]; m_garbageCollectionExtensions.Add( td, owner ); } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_SkipDuringGarbageCollectionAttribute" )] private void Notify_SkipDuringGarbageCollectionAttribute( ref bool fKeep , CustomAttributeRepresentation ca , FieldRepresentation owner ) { m_garbageCollectionExclusions.Insert( owner ); } //--// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_AlignmentRequirementsAttribute" )] private void Notify_AlignmentRequirementsAttribute( ref bool fKeep , CustomAttributeRepresentation ca , BaseRepresentation owner ) { Abstractions.PlacementRequirements pr = CreatePlacementRequirements( owner ); pr.Alignment = (uint)ca.FixedArgsValues[0]; pr.AlignmentOffset = (int )ca.FixedArgsValues[1]; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_MemoryRequirementsAttribute" )] private void Notify_MemoryRequirementsAttribute( ref bool fKeep , CustomAttributeRepresentation ca , BaseRepresentation owner ) { Abstractions.PlacementRequirements pr = CreatePlacementRequirements( owner ); pr.AddConstraint( (Runtime.MemoryAttributes)ca.FixedArgsValues[0] ); } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_MemoryUsageAttribute" )] private void Notify_MemoryUsageAttribute( ref bool fKeep , CustomAttributeRepresentation ca , BaseRepresentation owner ) { Abstractions.PlacementRequirements pr = CreatePlacementRequirements( owner ); pr.AddConstraint( (Runtime.MemoryUsage)ca.FixedArgsValues[0] ); pr.AddConstraint( ca.GetNamedArg<string>( "SectionName", null ) ); pr.ContentsUninitialized = ca.GetNamedArg( "ContentsUninitialized" , false ); pr.AllocateFromHighAddress = ca.GetNamedArg( "AllocateFromHighAddress", false ); } //--// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_HardwareExceptionHandlerAttribute" )] private void Notify_HardwareExceptionHandlerAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { m_hardwareExceptionHandlers[ owner ] = ca; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_DebuggerHookHandlerAttribute" )] private void Notify_DebuggerHookHandlerAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { if(this.ExcludeDebuggerHooks == false) { m_debuggerHookHandlers[owner] = ca; } } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_SingletonFactoryAttribute" )] private void Notify_SingletonFactoryAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { m_singletonFactories[ owner ] = ca; var tdFallback = ca.GetNamedArg( "Fallback" ) as TypeRepresentation; if(tdFallback != null) { m_singletonFactoriesFallback[owner.OwnerType] = tdFallback; } } //--// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_NoVTableAttribute" )] private void Notify_NoVTableAttribute( ref bool fKeep , CustomAttributeRepresentation ca , TypeRepresentation owner ) { owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.NoVTable; } //--//--// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_MemoryMappedPeripheralAttribute" )] private void Notify_MemoryMappedPeripheralAttribute( ref bool fKeep , CustomAttributeRepresentation ca , TypeRepresentation owner ) { m_memoryMappedPeripherals[ owner ] = ca; RegisterAsMemoryMappedPeripheral( owner ); if(owner is ConcreteReferenceTypeRepresentation) { CheckRequiredFieldForMemoryMappedPeripheralAttribute( owner, "Base" ); CheckRequiredFieldForMemoryMappedPeripheralAttribute( owner, "Length" ); } } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_RegisterAttribute" )] private void Notify_RegisterAttribute( ref bool fKeep , CustomAttributeRepresentation ca , FieldRepresentation owner ) { CheckRequiredField( ca, owner, "Offset" ); m_registerAttributes[ owner ] = ca; RegisterAsMemoryMappedPeripheral( owner.OwnerType ); } private void RegisterAsMemoryMappedPeripheral( TypeRepresentation td ) { for(var td2 = td; td2 != null && td2 != this.WellKnownTypes.System_Object; td2 = td2.Extends) { if(m_memoryMappedPeripherals.ContainsKey( td2 ) == false) { if(td == td2) { throw TypeConsistencyErrorException.Create( "'{0}' is not marked as a memory-mapped class", td.FullName ); } else { throw TypeConsistencyErrorException.Create( "Cannot have memory-mapped class derive from a non-memory-mapped one: '{0}' => '{1}'", td.FullName, td2.FullName ); } } } td.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.NoVTable; RegisterForTypeLayoutDelegation( td, Notify_LayoutMemoryMappedPeripheral ); } //--// private bool Notify_LayoutMemoryMappedPeripheral( TypeRepresentation td , GrowOnlySet< TypeRepresentation > history ) { uint maxSize = 0; { TypeRepresentation tdSize = td; while(tdSize != null) { CustomAttributeRepresentation ca; if(m_memoryMappedPeripherals.TryGetValue( tdSize, out ca )) { object sizeObj = ca.GetNamedArg( "Length" ); if(sizeObj != null) { maxSize = (uint)sizeObj; break; } } tdSize = tdSize.Extends; } } foreach(FieldRepresentation fd in td.Fields) { if(fd is InstanceFieldRepresentation) { CustomAttributeRepresentation caFd; if(m_registerAttributes.TryGetValue( fd, out caFd ) == false) { throw TypeConsistencyErrorException.Create( "Cannot have non-register field '{0}' in memory-mapped class '{1}'", fd.Name, td.FullNameWithAbbreviation ); } var tdField = fd.FieldType; EnsureTypeLayout( tdField, history, this.PlatformAbstraction.MemoryAlignment ); fd.Offset = (int)(uint)caFd.GetNamedArg( "Offset" ); maxSize = Math.Max( (uint)(fd.Offset + tdField.SizeOfHoldingVariable), maxSize ); } } td.Size = maxSize; return true; } //--//--// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_BitFieldPeripheralAttribute" )] private void Notify_BitFieldPeripheralAttribute( ref bool fKeep , CustomAttributeRepresentation ca , TypeRepresentation owner ) { CheckRequiredField( ca, owner, "PhysicalType" ); owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.NoVTable; m_memoryMappedBitFieldPeripherals[ owner ] = ca; RegisterForTypeLayoutDelegation( owner, Layout_LayoutMemoryMappedBitFieldPeripheral ); } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_BitFieldRegisterAttribute" )] private void Notify_BitFieldRegisterAttribute( ref bool fKeep , CustomAttributeRepresentation ca , FieldRepresentation owner ) { var sec = CreateSectionOfBitFieldDefinition( ca, owner ); HandleBitFieldRegisterAttributeCommon( ref fKeep, ca, owner, sec ); } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_BitFieldSplitRegisterAttribute" )] private void Notify_BitFieldSplitRegisterAttribute( ref bool fKeep , CustomAttributeRepresentation ca , FieldRepresentation owner ) { var sec = CreateSectionOfBitFieldDefinition( ca, owner ); if(ca.TryToGetNamedArg( "Offset", out sec.Offset ) == false) { FailedRequiredField( ca, owner, "Offset" ); } HandleBitFieldRegisterAttributeCommon( ref fKeep, ca, owner, sec ); } private BitFieldDefinition.Section CreateSectionOfBitFieldDefinition( CustomAttributeRepresentation ca , FieldRepresentation owner ) { BitFieldDefinition.Section sec = new BitFieldDefinition.Section(); if(ca.TryToGetNamedArg( "Position", out sec.Position ) == false) { FailedRequiredField( ca, owner, "Position" ); } if(ca.TryToGetNamedArg( "Size", out sec.Size ) == false) { if(owner.FieldType != this.WellKnownTypes.System_Boolean) { FailedRequiredField( ca, owner, "Size" ); } sec.Size = 1; } ca.TryToGetNamedArg( "Modifiers", out sec.Modifiers ); ca.TryToGetNamedArg( "ReadAs" , out sec.ReadsAs ); ca.TryToGetNamedArg( "WriteAs" , out sec.WritesAs ); return sec; } private void HandleBitFieldRegisterAttributeCommon( ref bool fKeep , CustomAttributeRepresentation ca , FieldRepresentation owner , BitFieldDefinition.Section sec ) { fKeep = false; if(m_memoryMappedBitFieldPeripherals.ContainsKey( owner.OwnerType ) == false) { throw TypeConsistencyErrorException.Create( "Containing type '{0}' of bitfield register '{1}' must be a bitfield peripheral", owner.OwnerType.FullName, owner ); } BitFieldDefinition bfDef; if(m_bitFieldRegisterAttributes.TryGetValue( owner, out bfDef ) == false) { bfDef = new BitFieldDefinition(); m_bitFieldRegisterAttributes[ owner ] = bfDef; } bfDef.AddSection( sec ); } //--// private bool Layout_LayoutMemoryMappedBitFieldPeripheral( TypeRepresentation td , GrowOnlySet< TypeRepresentation > history ) { CustomAttributeRepresentation ca = m_memoryMappedBitFieldPeripherals[td]; TypeRepresentation tdPhysical = ca.GetNamedArg< TypeRepresentation >( "PhysicalType" ); EnsureTypeLayout( tdPhysical, history, this.PlatformAbstraction.MemoryAlignment ); td.Size = tdPhysical.Size; foreach(FieldRepresentation fd in td.Fields) { if(fd is StaticFieldRepresentation) { throw TypeConsistencyErrorException.Create( "Cannot have static field '{0}' in memory-mapped bitfield class '{1}'", fd.Name, td.FullNameWithAbbreviation ); } if(m_bitFieldRegisterAttributes.ContainsKey( fd ) == false) { throw TypeConsistencyErrorException.Create( "Cannot have non-bitfield register field '{0}' in memory-mapped bitfield class '{1}'", fd.Name, td.FullNameWithAbbreviation ); } fd.Offset = 0; } return true; } //--//--// private void CheckRequiredFieldForMemoryMappedPeripheralAttribute( TypeRepresentation target , string name ) { for(TypeRepresentation td = target; td != null; td = td.Extends) { CustomAttributeRepresentation ca; if(m_memoryMappedPeripherals.TryGetValue( td, out ca )) { if(ca.HasNamedArg( name )) { return; } } } throw TypeConsistencyErrorException.Create( "Cannot find required '{0}' field for attribute MemoryMappedPeripheralAttribute on the hierarchy for {2}", name, target ); } private static void CheckRequiredField( CustomAttributeRepresentation ca , object owner , string name ) { if(ca.HasNamedArg( name ) == false) { FailedRequiredField( ca, owner, name ); } } private static void FailedRequiredField( CustomAttributeRepresentation ca , object owner , string name ) { throw TypeConsistencyErrorException.Create( "Missing required '{0}' field for attribute '{1}' on '{2}'", name, ca.Constructor.OwnerType.FullName, owner ); } } }
using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Linq; using System.Text; using EnvDTE; using JetBrains.Annotations; using JetBrains.Application; using JetBrains.Application.UI.ActionsRevised.Shortcuts; using JetBrains.Application.UI.Controls.JetPopupMenu.Detail; using JetBrains.Diagnostics; using JetBrains.Lifetimes; using JetBrains.Util; using JetBrains.Util.Logging; using JetBrains.VsIntegration.Shell; using JetBrains.VsIntegration.Shell.ActionManagement; using JetBrains.VsIntegration.Shell.EnvDte; using Microsoft.VisualStudio.CommandBars; using Microsoft.VisualStudio.Shell.Interop; namespace JetBrains.ReSharper.Plugins.PresentationAssistant.VisualStudio { [ShellComponent] public class VsCommandShortcutProvider : IShortcutProvider { private readonly ShortcutDisplayStatistics statistics; private readonly IVsCmdNameMapping vsCmdNameMapping; private readonly VsShortcutFinder vsShortcutFinder; private readonly IActionShortcuts actionShortcuts; private readonly IEnvDteWrapper dte; private readonly IDictionary<string, CommandBarActionDef> cachedActionDefs; public VsCommandShortcutProvider(Lifetime lifetime, ShortcutDisplayStatistics statistics, IEnvDteWrapper dte, IVsCmdNameMapping vsCmdNameMapping, VsShortcutFinder vsShortcutFinder, VsToolsOptionsMonitor vsToolsOptionsMonitor, IActionShortcuts actionShortcuts) { this.statistics = statistics; this.vsCmdNameMapping = vsCmdNameMapping; this.vsShortcutFinder = vsShortcutFinder; this.actionShortcuts = actionShortcuts; this.dte = dte; cachedActionDefs = new Dictionary<string, CommandBarActionDef>(); vsToolsOptionsMonitor.VsOptionsMightHaveChanged.Advise(lifetime, _ => cachedActionDefs.Clear()); } public Shortcut GetShortcut(string actionId) { var def = Find(actionId); if (def == null) return null; statistics.OnAction(actionId); return new Shortcut { ActionId = def.ActionId, Text = def.Text, Path = def.Path, CurrentScheme = actionShortcuts.CurrentScheme, VsShortcut = def.VsShortcuts, Multiplier = statistics.Multiplier }; } private CommandBarActionDef Find(string actionId) { var cache = GetCachedActionDefs(); CommandBarActionDef def; return cache.TryGetValue(actionId, out def) ? def : null; } private IDictionary<string, CommandBarActionDef> GetCachedActionDefs() { if (cachedActionDefs.Any()) return cachedActionDefs; PopulateCachedActionDefs(); return cachedActionDefs; } private void PopulateCachedActionDefs() { var menuBar = Logger.CatchSilent(() => ((CommandBars) dte.CommandBars)["MenuBar"]); if (menuBar != null) { var compoundException = new CompoundException(); var enumDescendantControls = menuBar.EnumDescendantControls(compoundException).ToList(); foreach (var tuple in enumDescendantControls) { // Make sure it's an actionable type (e.g. not a CommandBarPopup, or _CommandBarActiveX) var commandBarControl = tuple.Item1; if (commandBarControl is CommandBarButton || commandBarControl is CommandBarComboBox) { var commandId = VsCommandHelpersTodo.TryGetVsControlCommandID(commandBarControl, dte); if (commandId == null) continue; // Breadth first enumeration of descendant controls means the first time a command is encountered // is always the shortest path to a control for that command var actionId = vsCmdNameMapping.TryMapCommandIdToVsCommandName(commandId); if (string.IsNullOrEmpty(actionId) || cachedActionDefs.ContainsKey(actionId)) continue; var commandBarPopups = tuple.Item2; var def = new CommandBarActionDef(vsShortcutFinder, dte, actionId, commandId, commandBarControl, commandBarPopups ?? EmptyArray<CommandBarPopup>.Instance); cachedActionDefs.Add(actionId, def); } } if (compoundException.Exceptions.Any()) Logger.LogException(compoundException); } } private class CommandBarActionDef { private readonly Lazy<BackingFields> backingFields; private class BackingFields { public string Text; public string Path; public ShortcutSequence VsShortcut; } public CommandBarActionDef(VsShortcutFinder vsShortcutFinder, IEnvDteWrapper dte, string actionId, CommandID commandId, CommandBarControl control, CommandBarPopup[] parentPopups) { ActionId = actionId; // Lazily initialise. Talking to the command bar objects is SLOOOOOOOWWWWWW. backingFields = Lazy.Of(() => { Assertion.AssertNotNull(control, "control != null"); var sb = new StringBuilder(); foreach (var popup in parentPopups) sb.AppendFormat("{0} \u2192 ", popup.Caption); var fields = new BackingFields { Text = MnemonicStore.RemoveMnemonicMark(control.Caption), Path = MnemonicStore.RemoveMnemonicMark(sb.ToString()) }; var command = VsCommandHelpers.TryGetVsCommandAutomationObject(commandId, dte); var vsShortcut = vsShortcutFinder.GetVsShortcut(command); if (vsShortcut != null) { var details = new ShortcutDetails[vsShortcut.KeyboardShortcuts.Length]; for (int i = 0; i < vsShortcut.KeyboardShortcuts.Length; i++) { var keyboardShortcut = vsShortcut.KeyboardShortcuts[i]; details[i] = new ShortcutDetails(KeyConverter.Convert(keyboardShortcut.Key), keyboardShortcut.Modifiers); } fields.VsShortcut = new ShortcutSequence(details); } return fields; }, true); } public string ActionId { get; } public string Text => backingFields.Value.Text; public ShortcutSequence VsShortcuts => backingFields.Value.VsShortcut; public string Path => backingFields.Value.Path; } } // We can't use ReSharper's VsCommandHelpers directly as it uses an embedded interop type // which isn't available across assemblies public static class VsCommandHelpers2 { /// <summary> /// Does BFS on descendant controls and command bars of a command bar. /// Each returned item is the descendant control plus an array of its parents, top to bottom. /// </summary> [NotNull] public static IEnumerable<Tuple<CommandBarControl, CommandBarPopup[]>> EnumDescendantControls( [NotNull] this CommandBar root, [NotNull] CompoundException cex) { if (root == null) throw new ArgumentNullException(nameof(root)); if (cex == null) throw new ArgumentNullException(nameof(cex)); var queueEnumChildren = new Queue<Tuple<CommandBar, CommandBarPopup[]>>(new[] {Tuple.Create(root, EmptyArray<CommandBarPopup>.Instance)}); int nBar = -1; while (queueEnumChildren.Any()) { Tuple<CommandBar, CommandBarPopup[]> tuple = queueEnumChildren.Dequeue(); nBar++; List<CommandBarControl> children = null; try { // All children children = tuple.Item1.Controls.OfType<CommandBarControl>().ToList(); // EnqueueJob child containers var popups = children.OfType<CommandBarPopup>() .Select(popup => Tuple.Create(popup.CommandBar, tuple.Item2.Concat(popup).ToArray())); foreach (var popup in popups) queueEnumChildren.Enqueue(popup); } catch (Exception e) { var ex = new LoggerException("Failed to enum command bar child controls.", e); ex.AddData("IndexInQueue", () => nBar); ex.AddData("CommandBarName", () => tuple.Item1.Name); ex.AddData("CommandBarIndexProperty", () => tuple.Item1.Index); cex.Exceptions.Add(ex); } // Emit if (children != null) // Null if were exceptions (cannot yield from a catch) { foreach (CommandBarControl child in children) yield return Tuple.Create(child, tuple.Item2); } } } } }
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2009 Jason Booth Copyright (c) 2011-2012 openxlive.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Collections.Generic; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; namespace CocosSharp { /// <summary> /// Helper class to handle file operations /// </summary> public class CCFileUtils { static bool PopupNotify = true; #region Properties // Set/Get whether pop-up a message box when the image load failed public static bool IsPopupNotify { get { return PopupNotify; } set { PopupNotify = value; } } #endregion Properties public static Stream GetFileStream(string fileName) { fileName = Path.Combine(CCContentManager.SharedContentManager.RootDirectory, fileName); return TitleContainer.OpenStream(fileName); } /// <summary> /// @brief Get resource file data /// @param[in] filename The resource file name which contain the path /// @param[in] pszMode The read mode of the file /// @param[out] pSize If get the file data succeed the it will be the data size,or it will be 0 /// @return if success,the pointer of data will be returned,or NULL is returned /// @warning If you get the file data succeed,you must delete it after used. /// </summary> /// <param name="filename"></param> /// <returns></returns> public static string GetFileData(string filename) { return CCContentManager.SharedContentManager.Load<string>(filename); } public static byte[] GetFileBytes(string filename) { filename = System.IO.Path.Combine(CCContentManager.SharedContentManager.RootDirectory, filename); using (var stream = TitleContainer.OpenStream(filename)) { var buffer = new byte[1024]; var ms = new MemoryStream(); int readed = 0; readed = stream.Read(buffer, 0, 1024); while (readed > 0) { ms.Write(buffer, 0, readed); readed = stream.Read(buffer, 0, 1024); } return ms.ToArray(); } } /// <summary> /// @brief Get resource file data from zip file /// @param[in] filename The resource file name which contain the relative path of zip file /// @param[out] pSize If get the file data succeed the it will be the data size,or it will be 0 /// @return if success,the pointer of data will be returned,or NULL is returned /// @warning If you get the file data succeed,you must delete it after used. /// </summary> /// <param name="pszZipFilePath"></param> /// <param name="filename"></param> /// <param name="pSize"></param> /// <returns></returns> public static char[] GetFileDataFromZip(string zipFilePath, string filename, UInt64 pSize) { throw new NotImplementedException("Cannot load zip files for this method has not been realized !"); } /// <summary> /// removes the HD suffix from a path /// @returns const char * without the HD suffix /// @since v0.99.5 /// </summary> /// <param name="path"></param> /// <returns></returns> public static string CCRemoveHDSuffixFromFile(string path) { throw new NotImplementedException("Remove hd picture !"); } /// <summary> /// @brief Generate the absolute path of the file. /// @param pszRelativePath The relative path of the file. /// @return The absolute path of the file. /// @warning We only add the ResourcePath before the relative path of the file. /// If you have not set the ResourcePath,the function add "/NEWPLUS/TDA_DATA/UserData/" as default. /// You can set ResourcePath by function void setResourcePath(const char *pszResourcePath); /// </summary> /// <param name="pszRelativePath"></param> /// <returns></returns> public static string FullPathFromRelativePath(string relativePath) { // todo: return self now return relativePath; // throw new NotImplementedException("win32 only definition does not realize !"); } /// <summary> /// extracts the directory from the pszRelativeFile and uses that directory path as the /// path for the pszFilename. /// </summary> public static string FullPathFromRelativeFile(string filename, string relativeFile) { string path = Path.GetDirectoryName(relativeFile); return Path.Combine(path, RemoveExtension(filename)); } public static string RemoveExtension(string fileName) { int len = fileName.LastIndexOf('.'); if (len != -1) { return fileName.Substring(0, len); } return fileName; } /// <summary> /// @brief Set the ResourcePath,we will find resource in this path /// @param pszResourcePath The absolute resource path /// @warning Don't call this function in android and iOS, it has not effect. /// In android, if you want to read file other than apk, you shoud use invoke getFileData(), and pass the /// absolute path. /// </summary> /// <param name="?"></param> public static void SetResourcePath(string resourcePath) { throw new NotSupportedException ("Not supported in XNA"); } /// <summary> /// @brief Generate a CCDictionary pointer by file /// @param pFileName The file name of *.plist file /// @return The CCDictionary pointer generated from the file /// </summary> /// <typeparam name="?"></typeparam> /// <typeparam name="?"></typeparam> /// <param name="?"></param> /// <returns></returns> public static Dictionary<string, object> DictionaryWithContentsOfFile(string filename) { CCDictMaker tMaker = new CCDictMaker(); return tMaker.DictionaryWithContentsOfFile(filename); } /// <summary> /// @brief Get the writeable path /// @return The path that can write/read file /// </summary> /// <returns></returns> public static string GetWriteablePath() { throw new NotSupportedException("Use IsolatedStorage in XNA"); } /////////////////////////////////////////////////// // interfaces on wophone /////////////////////////////////////////////////// /// <summary> /// @brief Set the resource zip file name /// @param pszZipFileName The relative path of the .zip file /// </summary> /// <param name="pszZipFileName"></param> public static void SetResource(string zipFilename) { throw new NotImplementedException("win32 only definition does not realize !"); } /////////////////////////////////////////////////// // interfaces on ios /////////////////////////////////////////////////// public static int CCLoadFileIntoMemory(string filename, out char[] file) { throw new NotImplementedException("win32 only definition does not realize !"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestZUInt16() { var test = new BooleanBinaryOpTest__TestZUInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanBinaryOpTest__TestZUInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt16> _fld1; public Vector128<UInt16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(BooleanBinaryOpTest__TestZUInt16 testClass) { var result = Sse41.TestZ(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestZUInt16 testClass) { fixed (Vector128<UInt16>* pFld1 = &_fld1) fixed (Vector128<UInt16>* pFld2 = &_fld2) { var result = Sse41.TestZ( Sse2.LoadVector128((UInt16*)(pFld1)), Sse2.LoadVector128((UInt16*)(pFld2)) ); testClass.ValidateResult(_fld1, _fld2, result); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector128<UInt16> _clsVar1; private static Vector128<UInt16> _clsVar2; private Vector128<UInt16> _fld1; private Vector128<UInt16> _fld2; private DataTable _dataTable; static BooleanBinaryOpTest__TestZUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public BooleanBinaryOpTest__TestZUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.TestZ( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.TestZ( Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.TestZ( Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.TestZ( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt16>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt16>* pClsVar2 = &_clsVar2) { var result = Sse41.TestZ( Sse2.LoadVector128((UInt16*)(pClsVar1)), Sse2.LoadVector128((UInt16*)(pClsVar2)) ); ValidateResult(_clsVar1, _clsVar2, result); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = Sse41.TestZ(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse41.TestZ(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse41.TestZ(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new BooleanBinaryOpTest__TestZUInt16(); var result = Sse41.TestZ(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new BooleanBinaryOpTest__TestZUInt16(); fixed (Vector128<UInt16>* pFld1 = &test._fld1) fixed (Vector128<UInt16>* pFld2 = &test._fld2) { var result = Sse41.TestZ( Sse2.LoadVector128((UInt16*)(pFld1)), Sse2.LoadVector128((UInt16*)(pFld2)) ); ValidateResult(test._fld1, test._fld2, result); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.TestZ(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt16>* pFld1 = &_fld1) fixed (Vector128<UInt16>* pFld2 = &_fld2) { var result = Sse41.TestZ( Sse2.LoadVector128((UInt16*)(pFld1)), Sse2.LoadVector128((UInt16*)(pFld2)) ); ValidateResult(_fld1, _fld2, result); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.TestZ(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.TestZ( Sse2.LoadVector128((UInt16*)(&test._fld1)), Sse2.LoadVector128((UInt16*)(&test._fld2)) ); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt16> op1, Vector128<UInt16> op2, bool result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt16[] left, UInt16[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((left[i] & right[i]) == 0); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.TestZ)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DEBUG_BRICKTABLE namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using EncDef_VFP = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_VFP; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Cfg = Microsoft.Zelig.Configuration.Environment; public class DebugGarbageColllection { class ProhibitedRange { // // State // internal uint m_addressStart; internal uint m_addressEnd; // // Constructor Methods // internal ProhibitedRange( uint addressStart , uint addressEnd ) { m_addressStart = addressStart; m_addressEnd = addressEnd; } // // Helper Methods // internal int Compare( uint addressStart , uint addressEnd ) { if(m_addressStart >= addressEnd) { return 1; } else if(m_addressEnd <= addressStart) { return -1; } else { return 0; } } // // Debug Methods // public override string ToString() { return string.Format( "[{0:X8}-{1:X8}]", m_addressStart, m_addressEnd ); } } // // State // private MemoryDelta m_memDelta; private bool m_fVerbose; private InteropHelper m_ih; private Emulation.ArmProcessor.Simulator m_simulator; private List< ProhibitedRange > m_freeRanges = new List< ProhibitedRange >(); private int m_suspendCount; // // Constructor Methods // public DebugGarbageColllection( MemoryDelta memDelta , bool fVerbose ) { m_memDelta = memDelta; m_fVerbose = fVerbose; m_ih = new InteropHelper( memDelta.ImageInformation, memDelta.Host ); memDelta.Host.GetHostingService( out this.m_simulator ); if(memDelta.ImageInformation.TypeSystem != null && this.m_simulator != null) { RegisterInterops(); } } // // Helper Methods // void RegisterInterops() { this.m_simulator.NotifyOnStore += delegate( uint address, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { CheckAccess( address, value == 0xDEADBEEF ); }; m_ih.SetInteropOnWellKnownMethod( "DebugGC_MemorySegment_Initialize", false, delegate() { m_suspendCount++; m_ih.SetTemporaryInteropOnReturn( delegate() { m_suspendCount--; return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugGC_MemorySegment_LinkNewFreeBlock", false, delegate() { m_suspendCount++; m_ih.SetTemporaryInteropOnReturn( delegate() { m_suspendCount--; return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugGC_MemorySegment_RemoveFreeBlock", false, delegate() { uint ptr = m_ih.GetRegisterUInt32( EncDef.c_register_r1 ); int pos = FindRange( m_freeRanges, ptr ); if(pos < 0) { ReportProblem( "Expecting a free block at 0x{0:X8}", ptr ); } else { m_freeRanges.RemoveAt( pos ); } return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugGC_MemoryFreeBlock_ZeroFreeMemory", false, delegate() { m_suspendCount++; m_ih.SetTemporaryInteropOnReturn( delegate() { m_suspendCount--; return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugGC_MemoryFreeBlock_DirtyFreeMemory", false, delegate() { m_suspendCount++; m_ih.SetTemporaryInteropOnReturn( delegate() { m_suspendCount--; return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugGC_MemoryFreeBlock_InitializeFromRawMemory", false, delegate() { uint baseAddress = m_ih.GetRegisterUInt32( EncDef.c_register_r1 ); uint sizeInBytes = m_ih.GetRegisterUInt32( EncDef.c_register_r2 ); m_ih.SetTemporaryInteropOnReturn( delegate() { AddRange( baseAddress, baseAddress + sizeInBytes ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugGC_ObjectHeader_InsertPlug", false, delegate() { uint pThis = m_ih.GetRegisterUInt32( EncDef.c_register_r0 ); uint size = m_ih.GetRegisterUInt32( EncDef.c_register_r1 ); m_suspendCount++; m_ih.SetTemporaryInteropOnReturn( delegate() { m_suspendCount--; if(FindRange( m_freeRanges, pThis ) < 0) { AddRange( pThis, pThis + size ); } return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); if(m_fVerbose) { m_ih.SetInteropOnWellKnownMethod( "DebugGC_DefaultTypeSystemManager_AllocateInner", false, delegate() { uint vTable = m_ih.GetRegisterUInt32( EncDef.c_register_r1 ); uint size = m_ih.GetRegisterUInt32( EncDef.c_register_r2 ); m_ih.SetTemporaryInteropOnReturn( delegate() { uint ptr = m_ih.GetRegisterUInt32( EncDef.c_register_r0 ); if(ptr != 0) { var td = m_memDelta.ImageInformation.GetTypeFromVirtualTable( vTable ); if(td == null) { ReportProblem( "Cannot decode vTable at {0:X8}", vTable ); } else { ReportInfo( "NewObject: {0:X8} {1} bytes, {2}", ptr, size, td.FullNameWithAbbreviation ); } } return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); } m_ih.SetInteropOnWellKnownMethod( "DebugGC_MemoryFreeBlock_Allocate", false, delegate() { uint size = m_ih.GetRegisterUInt32( EncDef.c_register_r2 ); m_suspendCount++; var freeRangesOld = new List< ProhibitedRange >( m_freeRanges.ToArray() ); m_ih.SetTemporaryInteropOnReturn( delegate() { m_suspendCount--; uint ptr = m_ih.GetRegisterUInt32( EncDef.c_register_r0 ); if(ptr != 0) { int pos; pos = FindRange( freeRangesOld, ptr ); if(pos < 0) { ReportProblem( "Allocated memory from a non-free range: 0x{0:X8}, {1} bytes", ptr, size ); } pos = FindRange( m_freeRanges, ptr ); if(pos >= 0) { ProhibitedRange rng = m_freeRanges[pos]; if(rng.m_addressEnd == ptr + size) { rng.m_addressEnd = ptr; } else { ReportProblem( "Memory still free after allocation: 0x{0:X8}, {1} bytes", ptr, size ); } } } return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); #if DEBUG_BRICKTABLE m_ih.SetInteropOnWellKnownMethod( "DebugBrickTable_VerifyBrickTable", false, delegate() { ReportInfo( "Verify" ); m_ih.SetTemporaryInteropOnReturn( delegate() { ReportInfo( "Verify Done" ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugBrickTable_Reset", false, delegate() { ReportInfo( "Reset" ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugBrickTable_MarkObject", false, delegate() { uint objectPtr = m_ih.GetRegisterUInt32( EncodingDefinition.c_register_r1 ); uint objectSize = m_ih.GetRegisterUInt32( EncodingDefinition.c_register_r2 ); ReportInfo( "Mark {0:X8}[{2:X8}] {1}", objectPtr, objectSize, objectPtr - 0x080008AC ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugBrickTable_FindLowerBoundForObjectPointer", false, delegate() { uint interiorPtr = m_ih.GetRegisterUInt32( EncodingDefinition.c_register_r1 ); m_ih.SetTemporaryInteropOnReturn( delegate() { uint res = m_ih.GetRegisterUInt32( EncodingDefinition.c_register_r0 ); ReportInfo( "Find {0:X8}[{2:X8}] {1:X8}", interiorPtr, res, interiorPtr - 0x080008AC ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); #endif } //--// private void CheckAccess( uint address , bool fDirty ) { if(m_suspendCount == 0 && this.m_simulator.AreTimingUpdatesEnabled) { int pos = FindRange( m_freeRanges, address ); if(pos >= 0) { if(fDirty) { // It's OK to overwrite a free block with dirty patterns. } else { ProhibitedRange rng = m_freeRanges[pos]; //// if(CheckStackTrace( "HeapInitialization" )) //// { //// return; //// } ReportProblem( "Bad access: 0x{0:X8}", address ); } } } } private void RemoveRange( uint addressStart , uint addressEnd ) { while(true) { int pos = FindRange( m_freeRanges, addressStart, addressEnd ); if(pos < 0) { return; } ProhibitedRange rng = m_freeRanges[pos]; bool fChunkOnLeft = rng.m_addressStart < addressStart; bool fChunkOnRight = rng.m_addressEnd > addressEnd; if(fChunkOnLeft) { if(fChunkOnRight) { var rng2 = new ProhibitedRange( addressEnd, rng.m_addressEnd ); m_freeRanges.Insert( pos + 1, rng2 ); rng.m_addressEnd = addressStart; } else { rng.m_addressEnd = addressStart; } } else { if(fChunkOnRight) { rng.m_addressStart = addressStart; } else { m_freeRanges.RemoveAt( pos ); } } } } private void AddRange( uint addressStart , uint addressEnd ) { RemoveRange( addressStart, addressEnd ); int pos = FindRange( m_freeRanges, addressStart, addressEnd ); if(pos < 0) { pos = ~pos; ProhibitedRange rng = new ProhibitedRange( addressStart, addressEnd ); m_freeRanges.Insert( pos, rng ); if(pos > 0) { ProhibitedRange rngPre = m_freeRanges[pos-1]; if(rngPre.m_addressEnd == rng.m_addressStart) { rngPre.m_addressEnd = rng.m_addressEnd; m_freeRanges.RemoveAt( pos ); rng = rngPre; pos--; } } while(pos < m_freeRanges.Count - 1) { ProhibitedRange rngPost = m_freeRanges[pos+1]; if(rngPost.m_addressStart > rng.m_addressEnd) { break; } rng.m_addressEnd = rngPost.m_addressEnd; m_freeRanges.RemoveAt( pos+1 ); } } else { ReportProblem( "Already a free range: 0x{0:X8}-0x{1:X8}", addressStart, addressEnd ); } } private bool CheckStackTrace( params string[] methods ) { m_memDelta.FlushCache(); ThreadStatus ts = ThreadStatus.GetCurrent( m_memDelta ); foreach(StackFrame sf in ts.StackTrace) { var methodName = sf.Method.ToShortString(); foreach(var method in methods) { if(methodName.Contains( method )) { return true; } } } return false; } private void ReportProblem( string fmt , params object[] parms ) { string issue = string.Format( fmt, parms ); m_memDelta.FlushCache(); ThreadStatus ts = ThreadStatus.GetCurrent( m_memDelta ); Emulation.Hosting.OutputSink sink; if(m_memDelta.Host.GetHostingService( out sink )) { sink.OutputLine( issue ); foreach(StackFrame sf in ts.StackTrace) { sink.OutputLine( "#### {0}", sf ); } } Emulation.Hosting.ProcessorControl svcPC; m_memDelta.Host.GetHostingService( out svcPC ); svcPC.StopExecution = true; } private void ReportInfo( string fmt , params object[] parms ) { string issue = string.Format( fmt, parms ); Emulation.Hosting.OutputSink sink; if(m_memDelta.Host.GetHostingService( out sink )) { sink.OutputLine( issue ); } } private static int FindRange( List< ProhibitedRange > freeRanges , uint address ) { return FindRange( freeRanges, address, address + 1 ); } private static int FindRange( List< ProhibitedRange > freeRanges , uint addressStart , uint addressEnd ) { int lo = 0; int hi = freeRanges.Count - 1; while(lo <= hi) { int mid = (lo + hi) / 2; int order = freeRanges[mid].Compare( addressStart, addressEnd ); if(order < 0) { lo = mid + 1; } else if(order > 0) { hi = mid - 1; } else { return mid; } } return ~lo; } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A river (for example, the broad majestic Shannon). /// </summary> public class RiverBodyOfWater_Core : TypeCore, IBodyOfWater { public RiverBodyOfWater_Core() { this._TypeId = 230; this._Id = "RiverBodyOfWater"; this._Schema_Org_Url = "http://schema.org/RiverBodyOfWater"; string label = ""; GetLabel(out label, "RiverBodyOfWater", typeof(RiverBodyOfWater_Core)); this._Label = label; this._Ancestors = new int[]{266,206,146,40}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{40}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System.IO; namespace Breakout { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SpriteFont menuFont, subtextFont; Vector2 screen; GameState gameState; Texture2D brick; Texture2D ball; Rectangle ballRct, paddleRct; Vector2 ballPosition, ballVelocity; int paddlePosition; Brick[,] gameGrid; string[,] strgrid_lv1; string[,] strgrid_lv2; readonly int[] GRID_COUNT = { 25, 9 }; readonly int[] BLOCK_SIZE = { 50, 25 }; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = GRID_COUNT[0] * BLOCK_SIZE[0]; graphics.PreferredBackBufferHeight = GRID_COUNT[1] * BLOCK_SIZE[1] + 500; graphics.ApplyChanges(); } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { this.IsMouseVisible = true; // TODO: Add your initialization logic here screen = new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height); gameState = GameState.MAIN_MENU; strgrid_lv1 = new string[GRID_COUNT[0], GRID_COUNT[1]]; gameGrid = new Brick[GRID_COUNT[0], GRID_COUNT[1]]; setGround(); base.Initialize(); } private void setGround() { //Random rnd = new Random(); //ballVelocity = new Vector2(rnd.Next(5, 10), rnd.Next(5, 10)); ballVelocity = new Vector2(5); ballPosition = new Vector2((GraphicsDevice.Viewport.Width / 2) - 10, GraphicsDevice.Viewport.Height - 100); ballRct = new Rectangle((int)ballPosition.X, (int)ballPosition.Y, 20, 20); paddlePosition = (GraphicsDevice.Viewport.Width / 2) - BLOCK_SIZE[0]; paddleRct = new Rectangle(paddlePosition, GraphicsDevice.Viewport.Height - BLOCK_SIZE[1] - 5, BLOCK_SIZE[0] * 2, BLOCK_SIZE[1]); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here menuFont = this.Content.Load<SpriteFont>("MenuFont"); subtextFont = this.Content.Load<SpriteFont>("SubtextFont"); brick = this.Content.Load<Texture2D>("White"); ball = this.Content.Load<Texture2D>("Ball"); ReadFileAsString(@"Content/level1.txt", strgrid_lv1); ReadFileAsString(@"Content/level2.txt", strgrid_lv2); } private void ReadFileAsString(string path, string[,] strArr) { try { using (StreamReader reader = new StreamReader(path)) { while (!reader.EndOfStream) { for (int y = 0; y < GRID_COUNT[1]; y++) { string line = reader.ReadLine(); for (int x = 0; x < GRID_COUNT[0]; x++) { strArr[x, y] = line.Substring(x, 1); } } } } } catch (Exception e) { Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } } private void LoadElements(string[,] strArr) { for (int y = 0; y < GRID_COUNT[1]; y++) { for (int x = 0; x < GRID_COUNT[0]; x++) { // bbb gg rr y rrr oooo if (strArr[x, y].ToUpper().Equals(".")) { gameGrid[x, y] = null; } else if (strArr[x, y].ToUpper().Equals("B")) { gameGrid[x, y] = new Brick(Color.Blue, new Rectangle(x * BLOCK_SIZE[0], y * BLOCK_SIZE[1], BLOCK_SIZE[0], BLOCK_SIZE[1]), 5); } else if (strArr[x, y].ToUpper().Equals("G")) { gameGrid[x, y] = new Brick(Color.Green, new Rectangle(x * BLOCK_SIZE[0], y * BLOCK_SIZE[1], BLOCK_SIZE[0], BLOCK_SIZE[1]), 10); } else if (strArr[x, y].ToUpper().Equals("R")) { gameGrid[x, y] = new Brick(Color.Red, new Rectangle(x * BLOCK_SIZE[0], y * BLOCK_SIZE[1], BLOCK_SIZE[0], BLOCK_SIZE[1]), 15); } else if (strArr[x, y].ToUpper().Equals("Y")) { gameGrid[x, y] = new Brick(Color.Yellow, new Rectangle(x * BLOCK_SIZE[0], y * BLOCK_SIZE[1], BLOCK_SIZE[0], BLOCK_SIZE[1]), 20); } else if (strArr[x, y].ToUpper().Equals("O")) { gameGrid[x, y] = new Brick(Color.Orange, new Rectangle(x * BLOCK_SIZE[0], y * BLOCK_SIZE[1], BLOCK_SIZE[0], BLOCK_SIZE[1]), 40); } } } } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit(); // TODO: Add your update logic here switch (gameState) { case GameState.MAIN_MENU: if (Keyboard.GetState().IsKeyDown(Keys.P)) { setGround(); LoadElements(strgrid_lv1); gameState = GameState.LEVEL1; } break; case GameState.LEVEL1: if (!(Keyboard.GetState().GetPressedKeys().Length >= 2)) { if (Keyboard.GetState().IsKeyDown(Keys.Left)) paddlePosition -= 10; else if (Keyboard.GetState().IsKeyDown(Keys.Right)) paddlePosition += 10; if ((paddlePosition + (BLOCK_SIZE[0] * 2)) >= GraphicsDevice.Viewport.Width) paddlePosition = GraphicsDevice.Viewport.Width - (BLOCK_SIZE[0] * 2); else if (paddlePosition <= 0) { paddlePosition = 0; } ballPosition.X += ballVelocity.X; ballPosition.Y -= ballVelocity.Y; for (int y = 0; y < GRID_COUNT[1]; y++) { for (int x = 0; x < GRID_COUNT[0]; x++) { if (gameGrid[x, y] != null) if (ballRct.Intersects(gameGrid[x, y].GetRect)) { if (ballPosition.Y <= gameGrid[x, y].GetRect.Bottom && ballPosition.X >= gameGrid[x, y].GetRect.X && (ballPosition.X + 20) <= (gameGrid[x, y].GetRect.X + BLOCK_SIZE[0]) || (ballPosition.Y + 20) >= gameGrid[x, y].GetRect.Top && ballPosition.X >= gameGrid[x, y].GetRect.X && (ballPosition.X + 20) <= (gameGrid[x, y].GetRect.X + BLOCK_SIZE[0])) ballVelocity.Y *= -1; else if (ballPosition.X >= gameGrid[x, y].GetRect.Left && ballPosition.Y >= gameGrid[x, y].GetRect.Y && (ballPosition.Y + 20) <= (gameGrid[x, y].GetRect.Y + BLOCK_SIZE[0]) || (ballPosition.X + 20) <= gameGrid[x, y].GetRect.Right && ballPosition.Y >= gameGrid[x, y].GetRect.Y && (ballPosition.Y + 20) <= (gameGrid[x, y].GetRect.Y + BLOCK_SIZE[0])) ballVelocity.X *= -1; gameGrid[x, y] = null; } } } //Console.WriteLine(checkNullArray()); if (ballPosition.X >= (GraphicsDevice.Viewport.Width - 20) || ballPosition.X <= 0) ballVelocity.X *= -1; if (ballPosition.Y >= GraphicsDevice.Viewport.Height) gameState = GameState.QUIT; else if (ballPosition.Y <= 0 || ((ballPosition.Y + 20) == paddleRct.Top && (ballPosition.X - 10) >= (paddlePosition - 10) && (ballPosition.X + 30) <= (paddlePosition + BLOCK_SIZE[0] * 2 + 10))) //else if (ballPosition.Y <= 0 || (ballPosition.Y + 20) == paddleRct.Top) ballVelocity.Y *= -1; ballRct = new Rectangle((int)ballPosition.X, (int)ballPosition.Y, 20, 20); paddleRct = new Rectangle(paddlePosition, GraphicsDevice.Viewport.Height - BLOCK_SIZE[1] - 5, BLOCK_SIZE[0] * 2, BLOCK_SIZE[1]); } break; case GameState.QUIT: if (Keyboard.GetState().IsKeyDown(Keys.R)) gameState = GameState.MAIN_MENU; break; } base.Update(gameTime); } private bool checkNullArray() { bool result = true; for (int y = 0; y < GRID_COUNT[1]; y++) { for (int x = 0; x < GRID_COUNT[0]; x++) { if (result && gameGrid[x, y] == null) { result = false; } } } return result; } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); // TODO: Add your drawing code here spriteBatch.Begin(); switch (gameState) { case GameState.MAIN_MENU: spriteBatch.DrawString(menuFont, "Breakout", new Vector2(screen.X / 2 - menuFont.MeasureString("Breakout").X / 2, 50), Color.White); spriteBatch.DrawString(subtextFont, "Play(P)", new Vector2(screen.X / 2 - subtextFont.MeasureString("Play(P)").X / 2, 200), Color.White); break; case GameState.LEVEL1: for (int y = 0; y < GRID_COUNT[1]; y++) { for (int x = 0; x < GRID_COUNT[0]; x++) { if (gameGrid[x, y] != null) spriteBatch.Draw(brick, gameGrid[x, y].GetRect, gameGrid[x, y].GetText); } } spriteBatch.Draw(ball, ballRct, Color.White); spriteBatch.Draw(brick, paddleRct, Color.White); break; case GameState.QUIT: spriteBatch.DrawString(menuFont, "Game Over", new Vector2(screen.X / 2 - menuFont.MeasureString("Game Over").X / 2, 50), Color.White); spriteBatch.DrawString(subtextFont, "Restart(R)", new Vector2(screen.X / 2 - subtextFont.MeasureString("Restart(R)").X / 2, 200), Color.White); break; } spriteBatch.End(); base.Draw(gameTime); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using Core; using DumbBotsNET.Api; using Entities; using Game; using Graphs; using IrrlichtNETCP; using Messaging; using Misc; namespace Scripting { /// <summary> /// Static class that allows the script to call simplified methods /// </summary> public class ScriptMethods : IPlayerApi { private class RandomLocationInfo { public int DestinationNode { get; set; } public uint Timeout { get; set; } } internal CombatEntity Entity { get; set; } internal CombatEntity Enemy { get; set; } private Dictionary<CombatEntity, RandomLocationInfo> _randomLocations; public ScriptMethods() { _randomLocations = new Dictionary<CombatEntity, RandomLocationInfo>(); } #region Extensibility public Point[] GetCustomEntityPositions() { Point[] pointArray = new Point[SceneNodeManager.CustomEntities.Count]; for (int i = 0; i < SceneNodeManager.CustomEntities.Count; i++) { pointArray[i] = new Point((int)SceneNodeManager.CustomEntities[i].Node.Position.X, (int)SceneNodeManager.CustomEntities[i].Node.Position.Z); } return pointArray; } public int GetCustomEntitiesDestroyed() { return Entity.CustomEntitiesDestroyed; } public bool CustomEntityVisible(Point point) { foreach (var customEntity in SceneNodeManager.CustomEntities) { if (customEntity.Node.Position.DistanceFrom(new Vector3D(point.X, 30, point.Y)) < 1) { return CollisionManager.EntityVisible(Entity, customEntity); } } return false; } #endregion Extensibility #region Entity movement public void Stop() { Entity.Node.RemoveAnimators(); Entity.Route.Clear(); } public bool MoveToPoint(Point p) { Vector3D pos = new Vector3D(p.X, 30, p.Y); var nodes = GetNodes.GetNearestNodesToPosition(pos); foreach (var node in nodes) { List<int> route = RouteManager.Search(Entity, GetNodes.GetNearestNodeToPosition(Entity.Node.Position), node); if (route.Count > 1) { Entity.Route = route; return true; } } return false; } public bool MoveUp() { Vector3D pos = Entity.Node.Position + new Vector3D(-100, 0, 0); List<int> route = RouteManager.Search(Entity, GetNodes.GetNearestNodeToPosition(Entity.Node.Position), GetNodes.GetNearestNodeToPosition(pos)); Entity.Route = route; return route.Count > 1; } public bool MoveUpLeft() { Vector3D pos = Entity.Node.Position + new Vector3D(-100, 0, -100); List<int> route = RouteManager.Search(Entity, GetNodes.GetNearestNodeToPosition(Entity.Node.Position), GetNodes.GetNearestNodeToPosition(pos)); Entity.Route = route; return route.Count > 1; } public bool MoveUpRight() { Vector3D pos = Entity.Node.Position + new Vector3D(-100, 0, 100); List<int> route = RouteManager.Search(Entity, GetNodes.GetNearestNodeToPosition(Entity.Node.Position), GetNodes.GetNearestNodeToPosition(pos)); Entity.Route = route; return route.Count > 1; } public bool MoveDown() { Vector3D pos = Entity.Node.Position + new Vector3D(100, 0, 0); List<int> route = RouteManager.Search(Entity, GetNodes.GetNearestNodeToPosition(Entity.Node.Position), GetNodes.GetNearestNodeToPosition(pos)); Entity.Route = route; return route.Count > 1; } public bool MoveDownLeft() { Vector3D pos = Entity.Node.Position + new Vector3D(100, 0, -100); List<int> route = RouteManager.Search(Entity, GetNodes.GetNearestNodeToPosition(Entity.Node.Position), GetNodes.GetNearestNodeToPosition(pos)); Entity.Route = route; return route.Count > 1; } public bool MoveDownRight() { Vector3D pos = Entity.Node.Position + new Vector3D(100, 0, 100); List<int> route = RouteManager.Search(Entity, GetNodes.GetNearestNodeToPosition(Entity.Node.Position), GetNodes.GetNearestNodeToPosition(pos)); Entity.Route = route; return route.Count > 1; } public bool MoveRight() { Vector3D pos = Entity.Node.Position + new Vector3D(0, 0, 100); List<int> route = RouteManager.Search(Entity, GetNodes.GetNearestNodeToPosition(Entity.Node.Position), GetNodes.GetNearestNodeToPosition(pos)); Entity.Route = route; return route.Count > 1; } public bool MoveLeft() { Vector3D pos = Entity.Node.Position + new Vector3D(0, 0, -100); List<int> route = RouteManager.Search(Entity, GetNodes.GetNearestNodeToPosition(Entity.Node.Position), GetNodes.GetNearestNodeToPosition(pos)); Entity.Route = route; return route.Count > 1; } public void MoveToRandomLocation() { if (!_randomLocations.ContainsKey(Entity)) _randomLocations.Add(Entity, new RandomLocationInfo()); int destination; if (_randomLocations[Entity].Timeout >= Globals.Device.Timer.Time && Entity.Route.Count > 1) { destination = _randomLocations[Entity].DestinationNode; } else { Random rand = new Random(); destination = rand.Next(LevelManager.SparseGraph.NumNodes); _randomLocations[Entity].DestinationNode = destination; _randomLocations[Entity].Timeout = Globals.Device.Timer.Time + 1000; } List<int> route = RouteManager.Search(Entity, GetNodes.GetNearestNodeToPosition(Entity.Node.Position), destination); Entity.Route = route; } #endregion Entity movement #region Get Items public void GetRandomBazooka() { if (SceneNodeManager.VisibleBazookaEntities.Count > 0) { Random rand = new Random(); Vector3D pos = SceneNodeManager.VisibleBazookaEntities[rand.Next(SceneNodeManager.VisibleBazookaEntities.Count)].Node.Position; List<int> route = RouteManager.Search(Entity, GetNodes.GetNearestNodeToPosition(Entity.Node.Position), GetNodes.GetNearestNodeToPosition(pos)); Entity.Route = route; } } public void GetNearestBazooka() { int shortestRoute = 5000; SceneNodeManager.VisibleBazookaEntities.ForEach(bazooka => { Vector3D pos = bazooka.Node.Position; List<int> route = RouteManager.Search(Entity, GetNodes.GetNearestNodeToPosition(Entity.Node.Position), GetNodes.GetNearestNodeToPosition(pos)); if (route.Count > 0 && route.Count < shortestRoute) { Entity.Route = route; shortestRoute = route.Count; } }); } public void GetRandomMedkit() { if (SceneNodeManager.VisibleMedkitEntities.Count > 0) { Random rand = new Random(); Vector3D pos = SceneNodeManager.VisibleMedkitEntities[rand.Next(SceneNodeManager.VisibleMedkitEntities.Count)].Node.Position; List<int> route = RouteManager.Search(Entity, GetNodes.GetNearestNodeToPosition(Entity.Node.Position), GetNodes.GetNearestNodeToPosition(pos)); Entity.Route = route; } } public void GetNearestMedkit() { int shortestRoute = 5000; SceneNodeManager.VisibleMedkitEntities.ForEach(medkit => { Vector3D pos = medkit.Node.Position; List<int> route = RouteManager.Search(Entity, GetNodes.GetNearestNodeToPosition(Entity.Node.Position), GetNodes.GetNearestNodeToPosition(pos)); if (route.Count > 0 && route.Count < shortestRoute) { Entity.Route = route; shortestRoute = route.Count; } }); } #endregion Get Items #region Messaging public void SendMessage(string message, TimeSpan time) { Message m = new Message(Entity.Node.ID, Entity.Node.ID, message, Globals.Device.Timer.Time + ((uint)time.TotalMilliseconds)); MessageDispatcher.AddMessageToQueue(m); } public void SendMessageToFoe(string message, TimeSpan time) { Message m = new Message(Entity.Node.ID, Enemy.Node.ID, message, Globals.Device.Timer.Time + ((uint)time.TotalMilliseconds)); MessageDispatcher.AddMessageToQueue(m); } public string FetchMessage() { var msg = MessageDispatcher.TryFetchMessage(Entity.Node.ID, Globals.Device.Timer.Time); return msg != null ? msg.MessageString : String.Empty; } #endregion Messaging #region Entity information public int GetHealth() { return Entity.Health; } public int GetAmmo() { return Entity.Ammo; } public Point GetPosition() { return new Point((int)Entity.Node.Position.X, (int)Entity.Node.Position.Z); } public int GetScoreDiff() { return Entity.Score - Enemy.Score; } public double GetHitAccuracy() { if (Entity.TotalShots > 0) { double hitsTaken = Enemy.HitsTaken; double totShots = Entity.TotalShots; return hitsTaken / totShots; } else { return 0; } } public int GetHitsTaken() { return Entity.HitsTaken; } public int GetTotalShots() { return Entity.TotalShots; } public int GetLookAngle() { return (int)Entity.TargetRotation.Y; } public Point GetPointInFrontOfPlayer() { return GetPointInFrontOfEntity(Entity); } #endregion Entity information #region Enemy information public bool GetEnemySighted() { return CollisionManager.EntityVisible(Entity, Enemy); } public Point GetEnemyPosition() { return new Point((int)Enemy.Node.Position.X, (int)Enemy.Node.Position.Z); } public int GetEnemyLookAngle() { return (int)Enemy.TargetRotation.Y; } public double GetDistanceFromEnemy() { return Entity.Node.Position.DistanceFrom(Enemy.Node.Position); } public Point GetPointInFrontOfEnemy() { return GetPointInFrontOfEntity(Enemy); } #endregion Enemy information #region Game information public TimeSpan GetGameTime() { return new TimeSpan(Globals.Device.Timer.Time); } public Point GetPositionFromMapPoint(Point point) { var position = GetNodes.GetPositionFromMapPoint(point); return new Point((int)position.X, (int)position.Z); } public bool PointVisible(Point p) { Line3D line = new Line3D(Entity.BoundingBox.Center, new Vector3D(p.X, 30, p.Y)); return CollisionManager.CanMoveBetween(line.Start, line.End); } public int GetNumberOfVisibleBazookas() { return SceneNodeManager.VisibleBazookaEntities.Count; } public int GetNumberofVisibleMedkits() { return SceneNodeManager.VisibleMedkitEntities.Count; } public Point[] GetAllMedkitLocations() { List<Point> pointList = new List<Point>(); foreach (var entity in SceneNodeManager.MedkitEntities) { pointList.Add(new Point((int)entity.Node.Position.X, (int)entity.Node.Position.Z)); } return pointList.ToArray(); } public Point[] GetVisibleMedkitLocations() { List<Point> pointList = new List<Point>(); foreach (var entity in SceneNodeManager.VisibleMedkitEntities) { pointList.Add(new Point((int)entity.Node.Position.X, (int)entity.Node.Position.Z)); } return pointList.ToArray(); } public Point[] GetAllBazookaLocations() { List<Point> pointList = new List<Point>(); foreach (var entity in SceneNodeManager.BazookaEntities) { pointList.Add(new Point((int)entity.Node.Position.X, (int)entity.Node.Position.Z)); } return pointList.ToArray(); } public Point[] GetVisibleBazookaLocations() { List<Point> pointList = new List<Point>(); foreach (var entity in SceneNodeManager.VisibleBazookaEntities) { pointList.Add(new Point((int)entity.Node.Position.X, (int)entity.Node.Position.Z)); } return pointList.ToArray(); } public Point[] GetAllWallLocations() { List<Point> pointList = new List<Point>(); foreach (var entity in SceneNodeManager.WallSceneNodes) { pointList.Add(new Point((int)entity.Node.Position.X, (int)entity.Node.Position.Z)); } return pointList.ToArray(); } public Point[] GetEnemyFiredRocketLocations() { List<Point> pointList = new List<Point>(); foreach (var entity in CombatManager.ProjectileList.Where(p => p.Owner == Enemy && p is RocketEntity)) { pointList.Add(new Point((int)entity.Node.Position.X, (int)entity.Node.Position.Z)); } return pointList.ToArray(); } public Point[] GetEnemyFiredBulletLocations() { List<Point> pointList = new List<Point>(); foreach (var entity in CombatManager.ProjectileList.Where(p => p.Owner == Enemy && p is BulletEntity)) { pointList.Add(new Point((int)entity.Node.Position.X, (int)entity.Node.Position.Z)); } return pointList.ToArray(); } #endregion Game information #region Display Text public void SayText(string message) { Globals.Scene.AddToDeletionQueue(Entity.FloatingText); Entity.FloatingText = SceneNodeManager.CreateBillboardText(Entity.Node, message); } public void SayText(string message, System.Drawing.Color colour) { Globals.Scene.AddToDeletionQueue(Entity.FloatingText); Entity.FloatingText = SceneNodeManager.CreateBillboardText(Entity.Node, message, colour); } #endregion Display Text #region Combat public void ShootRocket(Point pos) { CombatManager.FireRocket(Entity, pos); } public void ShootBullet(Point pos) { CombatManager.FireBullet(Entity, pos); } public void HurtSelf(int damage) { Entity.Health -= damage; } #endregion Combat #region Sound public void PlaySound(string filename) { if (SoundManager.PlaySound) { SoundManager.PlayCustom(filename); } } #endregion Sound #region Keyboard public bool IsKeyDown(params System.Windows.Forms.Keys[] keys) { return KeyboardHelper.KeyIsDown(keys); } #endregion Keyboard #region Helpers private Point GetPointInFrontOfEntity(CombatEntity entity) { var rotation = entity.TargetRotation + new Vector3D(0, 90, 0); var x = (float)(100 * Math.Cos(rotation.Y * NewMath.DEGTORAD)); var z = (float)(100 * Math.Sin(rotation.Y * NewMath.DEGTORAD)); var pointVector = entity.Node.Position + new Vector3D(x, 0, -z); return new Point((int)pointVector.X, (int)pointVector.Z); } #endregion Helpers } }
// Copyright ?2004, 2013, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // <http://www.mysql.com/about/legal/licensing/foss-exception.html>. // // 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; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.Text; using System.Collections.Generic; using MySql.Data.MySqlClient.Properties; using System.Data; namespace MySql.Data.MySqlClient { /// <summary> /// Summary description for PreparedStatement. /// </summary> internal class PreparableStatement : Statement { private int executionCount; private int statementId; #if RT RtBitArray nullMap; #else BitArray nullMap; #endif List<MySqlParameter> parametersToSend = new List<MySqlParameter>(); MySqlPacket packet; int dataPosition; int nullMapPosition; public PreparableStatement(MySqlCommand command, string text) : base(command, text) { } #region Properties public int ExecutionCount { get { return executionCount; } set { executionCount = value; } } public bool IsPrepared { get { return statementId > 0; } } public int StatementId { get { return statementId; } } #endregion public virtual void Prepare() { // strip out names from parameter markers string text; List<string> parameter_names = PrepareCommandText(out text); // ask our connection to send the prepare command MySqlField[] paramList = null; statementId = Driver.PrepareStatement(text, ref paramList); // now we need to assign our field names since we stripped them out // for the prepare for (int i = 0; i < parameter_names.Count; i++) { //paramList[i].ColumnName = (string) parameter_names[i]; string parameterName = (string)parameter_names[i]; MySqlParameter p = Parameters.GetParameterFlexible(parameterName, false); if (p == null) throw new InvalidOperationException( String.Format(Resources.ParameterNotFoundDuringPrepare, parameterName)); p.Encoding = paramList[i].Encoding; parametersToSend.Add(p); } // now prepare our null map int numNullBytes = 0; if (paramList != null && paramList.Length > 0) { #if RT nullMap = new RtBitArray(paramList.Length); #else nullMap = new BitArray(paramList.Length); #endif numNullBytes = (nullMap.Count + 7) / 8; } packet = new MySqlPacket(Driver.Encoding); // write out some values that do not change run to run packet.WriteByte(0); packet.WriteInteger(statementId, 4); packet.WriteByte((byte)0); // flags; always 0 for 4.1 packet.WriteInteger(1, 4); // interation count; 1 for 4.1 nullMapPosition = packet.Position; packet.Position += numNullBytes; // leave room for our null map packet.WriteByte(1); // rebound flag // write out the parameter types foreach (MySqlParameter p in parametersToSend) packet.WriteInteger(p.GetPSType(), 2); dataPosition = packet.Position; } public override void Execute() { // if we are not prepared, then call down to our base if (!IsPrepared) { base.Execute(); return; } //TODO: support long data here // create our null bitmap // we check this because Mono doesn't ignore the case where nullMapBytes // is zero length. // if (nullMapBytes.Length > 0) // { // byte[] bits = packet.Buffer; // nullMap.CopyTo(bits, // nullMap.CopyTo(nullMapBytes, 0); // start constructing our packet // if (Parameters.Count > 0) // nullMap.CopyTo(packet.Buffer, nullMapPosition); //if (parameters != null && parameters.Count > 0) //else // packet.WriteByte( 0 ); //TODO: only send rebound if parms change // now write out all non-null values packet.Position = dataPosition; for (int i = 0; i < parametersToSend.Count; i++) { MySqlParameter p = parametersToSend[i]; nullMap[i] = (p.Value == DBNull.Value || p.Value == null) || p.Direction == ParameterDirection.Output; if (nullMap[i]) continue; packet.Encoding = p.Encoding; p.Serialize(packet, true, Connection.Settings); } if (nullMap != null) nullMap.CopyTo(packet.Buffer, nullMapPosition); executionCount++; Driver.ExecuteStatement(packet); } public override bool ExecuteNext() { if (!IsPrepared) return base.ExecuteNext(); return false; } /// <summary> /// Prepares CommandText for use with the Prepare method /// </summary> /// <returns>Command text stripped of all paramter names</returns> /// <remarks> /// Takes the output of TokenizeSql and creates a single string of SQL /// that only contains '?' markers for each parameter. It also creates /// the parameterMap array list that includes all the paramter names in the /// order they appeared in the SQL /// </remarks> private List<string> PrepareCommandText(out string stripped_sql) { StringBuilder newSQL = new StringBuilder(); List<string> parameterMap = new List<string>(); int startPos = 0; string sql = ResolvedCommandText; MySqlTokenizer tokenizer = new MySqlTokenizer(sql); string parameter = tokenizer.NextParameter(); while (parameter != null) { if (parameter.IndexOf(StoredProcedure.ParameterPrefix) == -1) { newSQL.Append(sql.Substring(startPos, tokenizer.StartIndex - startPos)); newSQL.Append("?"); parameterMap.Add(parameter); startPos = tokenizer.StopIndex; } parameter = tokenizer.NextParameter(); } newSQL.Append(sql.Substring(startPos)); stripped_sql = newSQL.ToString(); return parameterMap; } public virtual void CloseStatement() { if (!IsPrepared) return; Driver.CloseStatement(statementId); statementId = 0; } } }
using System; using static OneOf.Functions; namespace OneOf { public class OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> : IOneOf { readonly T0 _value0; readonly T1 _value1; readonly T2 _value2; readonly T3 _value3; readonly T4 _value4; readonly T5 _value5; readonly T6 _value6; readonly T7 _value7; readonly T8 _value8; readonly T9 _value9; readonly T10 _value10; readonly T11 _value11; readonly T12 _value12; readonly T13 _value13; readonly T14 _value14; readonly T15 _value15; readonly T16 _value16; readonly T17 _value17; readonly T18 _value18; readonly T19 _value19; readonly T20 _value20; readonly T21 _value21; readonly T22 _value22; readonly int _index; protected OneOfBase(OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> input) { _index = input.Index; switch (_index) { case 0: _value0 = input.AsT0; break; case 1: _value1 = input.AsT1; break; case 2: _value2 = input.AsT2; break; case 3: _value3 = input.AsT3; break; case 4: _value4 = input.AsT4; break; case 5: _value5 = input.AsT5; break; case 6: _value6 = input.AsT6; break; case 7: _value7 = input.AsT7; break; case 8: _value8 = input.AsT8; break; case 9: _value9 = input.AsT9; break; case 10: _value10 = input.AsT10; break; case 11: _value11 = input.AsT11; break; case 12: _value12 = input.AsT12; break; case 13: _value13 = input.AsT13; break; case 14: _value14 = input.AsT14; break; case 15: _value15 = input.AsT15; break; case 16: _value16 = input.AsT16; break; case 17: _value17 = input.AsT17; break; case 18: _value18 = input.AsT18; break; case 19: _value19 = input.AsT19; break; case 20: _value20 = input.AsT20; break; case 21: _value21 = input.AsT21; break; case 22: _value22 = input.AsT22; break; default: throw new InvalidOperationException(); } } public object Value => _index switch { 0 => _value0, 1 => _value1, 2 => _value2, 3 => _value3, 4 => _value4, 5 => _value5, 6 => _value6, 7 => _value7, 8 => _value8, 9 => _value9, 10 => _value10, 11 => _value11, 12 => _value12, 13 => _value13, 14 => _value14, 15 => _value15, 16 => _value16, 17 => _value17, 18 => _value18, 19 => _value19, 20 => _value20, 21 => _value21, 22 => _value22, _ => throw new InvalidOperationException() }; public int Index => _index; public bool IsT0 => _index == 0; public bool IsT1 => _index == 1; public bool IsT2 => _index == 2; public bool IsT3 => _index == 3; public bool IsT4 => _index == 4; public bool IsT5 => _index == 5; public bool IsT6 => _index == 6; public bool IsT7 => _index == 7; public bool IsT8 => _index == 8; public bool IsT9 => _index == 9; public bool IsT10 => _index == 10; public bool IsT11 => _index == 11; public bool IsT12 => _index == 12; public bool IsT13 => _index == 13; public bool IsT14 => _index == 14; public bool IsT15 => _index == 15; public bool IsT16 => _index == 16; public bool IsT17 => _index == 17; public bool IsT18 => _index == 18; public bool IsT19 => _index == 19; public bool IsT20 => _index == 20; public bool IsT21 => _index == 21; public bool IsT22 => _index == 22; public T0 AsT0 => _index == 0 ? _value0 : throw new InvalidOperationException($"Cannot return as T0 as result is T{_index}"); public T1 AsT1 => _index == 1 ? _value1 : throw new InvalidOperationException($"Cannot return as T1 as result is T{_index}"); public T2 AsT2 => _index == 2 ? _value2 : throw new InvalidOperationException($"Cannot return as T2 as result is T{_index}"); public T3 AsT3 => _index == 3 ? _value3 : throw new InvalidOperationException($"Cannot return as T3 as result is T{_index}"); public T4 AsT4 => _index == 4 ? _value4 : throw new InvalidOperationException($"Cannot return as T4 as result is T{_index}"); public T5 AsT5 => _index == 5 ? _value5 : throw new InvalidOperationException($"Cannot return as T5 as result is T{_index}"); public T6 AsT6 => _index == 6 ? _value6 : throw new InvalidOperationException($"Cannot return as T6 as result is T{_index}"); public T7 AsT7 => _index == 7 ? _value7 : throw new InvalidOperationException($"Cannot return as T7 as result is T{_index}"); public T8 AsT8 => _index == 8 ? _value8 : throw new InvalidOperationException($"Cannot return as T8 as result is T{_index}"); public T9 AsT9 => _index == 9 ? _value9 : throw new InvalidOperationException($"Cannot return as T9 as result is T{_index}"); public T10 AsT10 => _index == 10 ? _value10 : throw new InvalidOperationException($"Cannot return as T10 as result is T{_index}"); public T11 AsT11 => _index == 11 ? _value11 : throw new InvalidOperationException($"Cannot return as T11 as result is T{_index}"); public T12 AsT12 => _index == 12 ? _value12 : throw new InvalidOperationException($"Cannot return as T12 as result is T{_index}"); public T13 AsT13 => _index == 13 ? _value13 : throw new InvalidOperationException($"Cannot return as T13 as result is T{_index}"); public T14 AsT14 => _index == 14 ? _value14 : throw new InvalidOperationException($"Cannot return as T14 as result is T{_index}"); public T15 AsT15 => _index == 15 ? _value15 : throw new InvalidOperationException($"Cannot return as T15 as result is T{_index}"); public T16 AsT16 => _index == 16 ? _value16 : throw new InvalidOperationException($"Cannot return as T16 as result is T{_index}"); public T17 AsT17 => _index == 17 ? _value17 : throw new InvalidOperationException($"Cannot return as T17 as result is T{_index}"); public T18 AsT18 => _index == 18 ? _value18 : throw new InvalidOperationException($"Cannot return as T18 as result is T{_index}"); public T19 AsT19 => _index == 19 ? _value19 : throw new InvalidOperationException($"Cannot return as T19 as result is T{_index}"); public T20 AsT20 => _index == 20 ? _value20 : throw new InvalidOperationException($"Cannot return as T20 as result is T{_index}"); public T21 AsT21 => _index == 21 ? _value21 : throw new InvalidOperationException($"Cannot return as T21 as result is T{_index}"); public T22 AsT22 => _index == 22 ? _value22 : throw new InvalidOperationException($"Cannot return as T22 as result is T{_index}"); public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2, Action<T3> f3, Action<T4> f4, Action<T5> f5, Action<T6> f6, Action<T7> f7, Action<T8> f8, Action<T9> f9, Action<T10> f10, Action<T11> f11, Action<T12> f12, Action<T13> f13, Action<T14> f14, Action<T15> f15, Action<T16> f16, Action<T17> f17, Action<T18> f18, Action<T19> f19, Action<T20> f20, Action<T21> f21, Action<T22> f22) { if (_index == 0 && f0 != null) { f0(_value0); return; } if (_index == 1 && f1 != null) { f1(_value1); return; } if (_index == 2 && f2 != null) { f2(_value2); return; } if (_index == 3 && f3 != null) { f3(_value3); return; } if (_index == 4 && f4 != null) { f4(_value4); return; } if (_index == 5 && f5 != null) { f5(_value5); return; } if (_index == 6 && f6 != null) { f6(_value6); return; } if (_index == 7 && f7 != null) { f7(_value7); return; } if (_index == 8 && f8 != null) { f8(_value8); return; } if (_index == 9 && f9 != null) { f9(_value9); return; } if (_index == 10 && f10 != null) { f10(_value10); return; } if (_index == 11 && f11 != null) { f11(_value11); return; } if (_index == 12 && f12 != null) { f12(_value12); return; } if (_index == 13 && f13 != null) { f13(_value13); return; } if (_index == 14 && f14 != null) { f14(_value14); return; } if (_index == 15 && f15 != null) { f15(_value15); return; } if (_index == 16 && f16 != null) { f16(_value16); return; } if (_index == 17 && f17 != null) { f17(_value17); return; } if (_index == 18 && f18 != null) { f18(_value18); return; } if (_index == 19 && f19 != null) { f19(_value19); return; } if (_index == 20 && f20 != null) { f20(_value20); return; } if (_index == 21 && f21 != null) { f21(_value21); return; } if (_index == 22 && f22 != null) { f22(_value22); return; } throw new InvalidOperationException(); } public TResult Match<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2, Func<T3, TResult> f3, Func<T4, TResult> f4, Func<T5, TResult> f5, Func<T6, TResult> f6, Func<T7, TResult> f7, Func<T8, TResult> f8, Func<T9, TResult> f9, Func<T10, TResult> f10, Func<T11, TResult> f11, Func<T12, TResult> f12, Func<T13, TResult> f13, Func<T14, TResult> f14, Func<T15, TResult> f15, Func<T16, TResult> f16, Func<T17, TResult> f17, Func<T18, TResult> f18, Func<T19, TResult> f19, Func<T20, TResult> f20, Func<T21, TResult> f21, Func<T22, TResult> f22) { if (_index == 0 && f0 != null) { return f0(_value0); } if (_index == 1 && f1 != null) { return f1(_value1); } if (_index == 2 && f2 != null) { return f2(_value2); } if (_index == 3 && f3 != null) { return f3(_value3); } if (_index == 4 && f4 != null) { return f4(_value4); } if (_index == 5 && f5 != null) { return f5(_value5); } if (_index == 6 && f6 != null) { return f6(_value6); } if (_index == 7 && f7 != null) { return f7(_value7); } if (_index == 8 && f8 != null) { return f8(_value8); } if (_index == 9 && f9 != null) { return f9(_value9); } if (_index == 10 && f10 != null) { return f10(_value10); } if (_index == 11 && f11 != null) { return f11(_value11); } if (_index == 12 && f12 != null) { return f12(_value12); } if (_index == 13 && f13 != null) { return f13(_value13); } if (_index == 14 && f14 != null) { return f14(_value14); } if (_index == 15 && f15 != null) { return f15(_value15); } if (_index == 16 && f16 != null) { return f16(_value16); } if (_index == 17 && f17 != null) { return f17(_value17); } if (_index == 18 && f18 != null) { return f18(_value18); } if (_index == 19 && f19 != null) { return f19(_value19); } if (_index == 20 && f20 != null) { return f20(_value20); } if (_index == 21 && f21 != null) { return f21(_value21); } if (_index == 22 && f22 != null) { return f22(_value22); } throw new InvalidOperationException(); } public bool TryPickT0(out T0 value, out OneOf<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT0 ? AsT0 : default; remainder = _index switch { 0 => default, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT0; } public bool TryPickT1(out T1 value, out OneOf<T0, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT1 ? AsT1 : default; remainder = _index switch { 0 => AsT0, 1 => default, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT1; } public bool TryPickT2(out T2 value, out OneOf<T0, T1, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT2 ? AsT2 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => default, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT2; } public bool TryPickT3(out T3 value, out OneOf<T0, T1, T2, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT3 ? AsT3 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => default, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT3; } public bool TryPickT4(out T4 value, out OneOf<T0, T1, T2, T3, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT4 ? AsT4 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => default, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT4; } public bool TryPickT5(out T5 value, out OneOf<T0, T1, T2, T3, T4, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT5 ? AsT5 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => default, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT5; } public bool TryPickT6(out T6 value, out OneOf<T0, T1, T2, T3, T4, T5, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT6 ? AsT6 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => default, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT6; } public bool TryPickT7(out T7 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT7 ? AsT7 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => default, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT7; } public bool TryPickT8(out T8 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT8 ? AsT8 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => default, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT8; } public bool TryPickT9(out T9 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT9 ? AsT9 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => default, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT9; } public bool TryPickT10(out T10 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT10 ? AsT10 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => default, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT10; } public bool TryPickT11(out T11 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT11 ? AsT11 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => default, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT11; } public bool TryPickT12(out T12 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT12 ? AsT12 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => default, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT12; } public bool TryPickT13(out T13 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T14, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT13 ? AsT13 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => default, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT13; } public bool TryPickT14(out T14 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T15, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT14 ? AsT14 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => default, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT14; } public bool TryPickT15(out T15 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T16, T17, T18, T19, T20, T21, T22> remainder) { value = IsT15 ? AsT15 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => default, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT15; } public bool TryPickT16(out T16 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T17, T18, T19, T20, T21, T22> remainder) { value = IsT16 ? AsT16 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => default, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT16; } public bool TryPickT17(out T17 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T18, T19, T20, T21, T22> remainder) { value = IsT17 ? AsT17 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => default, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT17; } public bool TryPickT18(out T18 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T19, T20, T21, T22> remainder) { value = IsT18 ? AsT18 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => default, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT18; } public bool TryPickT19(out T19 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T20, T21, T22> remainder) { value = IsT19 ? AsT19 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => default, 20 => AsT20, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT19; } public bool TryPickT20(out T20 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T21, T22> remainder) { value = IsT20 ? AsT20 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => default, 21 => AsT21, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT20; } public bool TryPickT21(out T21 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T22> remainder) { value = IsT21 ? AsT21 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => default, 22 => AsT22, _ => throw new InvalidOperationException() }; return this.IsT21; } public bool TryPickT22(out T22 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT22 ? AsT22 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, 22 => default, _ => throw new InvalidOperationException() }; return this.IsT22; } bool Equals(OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> other) => _index == other._index && _index switch { 0 => Equals(_value0, other._value0), 1 => Equals(_value1, other._value1), 2 => Equals(_value2, other._value2), 3 => Equals(_value3, other._value3), 4 => Equals(_value4, other._value4), 5 => Equals(_value5, other._value5), 6 => Equals(_value6, other._value6), 7 => Equals(_value7, other._value7), 8 => Equals(_value8, other._value8), 9 => Equals(_value9, other._value9), 10 => Equals(_value10, other._value10), 11 => Equals(_value11, other._value11), 12 => Equals(_value12, other._value12), 13 => Equals(_value13, other._value13), 14 => Equals(_value14, other._value14), 15 => Equals(_value15, other._value15), 16 => Equals(_value16, other._value16), 17 => Equals(_value17, other._value17), 18 => Equals(_value18, other._value18), 19 => Equals(_value19, other._value19), 20 => Equals(_value20, other._value20), 21 => Equals(_value21, other._value21), 22 => Equals(_value22, other._value22), _ => false }; public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj is OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> o && Equals(o); } public override string ToString() => _index switch { 0 => FormatValue(_value0), 1 => FormatValue(_value1), 2 => FormatValue(_value2), 3 => FormatValue(_value3), 4 => FormatValue(_value4), 5 => FormatValue(_value5), 6 => FormatValue(_value6), 7 => FormatValue(_value7), 8 => FormatValue(_value8), 9 => FormatValue(_value9), 10 => FormatValue(_value10), 11 => FormatValue(_value11), 12 => FormatValue(_value12), 13 => FormatValue(_value13), 14 => FormatValue(_value14), 15 => FormatValue(_value15), 16 => FormatValue(_value16), 17 => FormatValue(_value17), 18 => FormatValue(_value18), 19 => FormatValue(_value19), 20 => FormatValue(_value20), 21 => FormatValue(_value21), 22 => FormatValue(_value22), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the OneOf codegen.") }; public override int GetHashCode() { unchecked { int hashCode = _index switch { 0 => _value0?.GetHashCode(), 1 => _value1?.GetHashCode(), 2 => _value2?.GetHashCode(), 3 => _value3?.GetHashCode(), 4 => _value4?.GetHashCode(), 5 => _value5?.GetHashCode(), 6 => _value6?.GetHashCode(), 7 => _value7?.GetHashCode(), 8 => _value8?.GetHashCode(), 9 => _value9?.GetHashCode(), 10 => _value10?.GetHashCode(), 11 => _value11?.GetHashCode(), 12 => _value12?.GetHashCode(), 13 => _value13?.GetHashCode(), 14 => _value14?.GetHashCode(), 15 => _value15?.GetHashCode(), 16 => _value16?.GetHashCode(), 17 => _value17?.GetHashCode(), 18 => _value18?.GetHashCode(), 19 => _value19?.GetHashCode(), 20 => _value20?.GetHashCode(), 21 => _value21?.GetHashCode(), 22 => _value22?.GetHashCode(), _ => 0 } ?? 0; return (hashCode*397) ^ _index; } } } }