context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//--------------------------------------------------------------------------- // // <copyright file="MatrixCamera.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Markup; using System.Windows.Media.Media3D.Converters; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using System.Windows.Media.Imaging; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media.Media3D { sealed partial class MatrixCamera : Camera { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new MatrixCamera Clone() { return (MatrixCamera)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new MatrixCamera CloneCurrentValue() { return (MatrixCamera)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void ViewMatrixPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MatrixCamera target = ((MatrixCamera) d); target.PropertyChanged(ViewMatrixProperty); } private static void ProjectionMatrixPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MatrixCamera target = ((MatrixCamera) d); target.PropertyChanged(ProjectionMatrixProperty); } #region Public Properties /// <summary> /// ViewMatrix - Matrix3D. Default value is Matrix3D.Identity. /// </summary> public Matrix3D ViewMatrix { get { return (Matrix3D) GetValue(ViewMatrixProperty); } set { SetValueInternal(ViewMatrixProperty, value); } } /// <summary> /// ProjectionMatrix - Matrix3D. Default value is Matrix3D.Identity. /// </summary> public Matrix3D ProjectionMatrix { get { return (Matrix3D) GetValue(ProjectionMatrixProperty); } set { SetValueInternal(ProjectionMatrixProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new MatrixCamera(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <SecurityNote> /// Critical: This code calls into an unsafe code block /// TreatAsSafe: This code does not return any critical data.It is ok to expose /// Channels are safe to call into and do not go cross domain and cross process /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { // If we're told we can skip the channel check, then we must be on channel Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel)); if (skipOnChannelCheck || _duceResource.IsOnChannel(channel)) { base.UpdateResource(channel, skipOnChannelCheck); // Read values of properties into local variables Transform3D vTransform = Transform; // Obtain handles for properties that implement DUCE.IResource DUCE.ResourceHandle hTransform; if (vTransform == null || Object.ReferenceEquals(vTransform, Transform3D.Identity) ) { hTransform = DUCE.ResourceHandle.Null; } else { hTransform = ((DUCE.IResource)vTransform).GetHandle(channel); } // Pack & send command packet DUCE.MILCMD_MATRIXCAMERA data; unsafe { data.Type = MILCMD.MilCmdMatrixCamera; data.Handle = _duceResource.GetHandle(channel); data.htransform = hTransform; data.viewMatrix = CompositionResourceManager.Matrix3DToD3DMATRIX(ViewMatrix); data.projectionMatrix = CompositionResourceManager.Matrix3DToD3DMATRIX(ProjectionMatrix); // Send packed command structure channel.SendCommand( (byte*)&data, sizeof(DUCE.MILCMD_MATRIXCAMERA)); } } } internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel) { if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_MATRIXCAMERA)) { Transform3D vTransform = Transform; if (vTransform != null) ((DUCE.IResource)vTransform).AddRefOnChannel(channel); AddRefOnChannelAnimations(channel); UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ ); } return _duceResource.GetHandle(channel); } internal override void ReleaseOnChannelCore(DUCE.Channel channel) { Debug.Assert(_duceResource.IsOnChannel(channel)); if (_duceResource.ReleaseOnChannel(channel)) { Transform3D vTransform = Transform; if (vTransform != null) ((DUCE.IResource)vTransform).ReleaseOnChannel(channel); ReleaseOnChannelAnimations(channel); } } internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel) { // Note that we are in a lock here already. return _duceResource.GetHandle(channel); } internal override int GetChannelCountCore() { // must already be in composition lock here return _duceResource.GetChannelCount(); } internal override DUCE.Channel GetChannelCore(int index) { // Note that we are in a lock here already. return _duceResource.GetChannel(index); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the MatrixCamera.ViewMatrix property. /// </summary> public static readonly DependencyProperty ViewMatrixProperty; /// <summary> /// The DependencyProperty for the MatrixCamera.ProjectionMatrix property. /// </summary> public static readonly DependencyProperty ProjectionMatrixProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource(); internal static Matrix3D s_ViewMatrix = Matrix3D.Identity; internal static Matrix3D s_ProjectionMatrix = Matrix3D.Identity; #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static MatrixCamera() { // We check our static default fields which are of type Freezable // to make sure that they are not mutable, otherwise we will throw // if these get touched by more than one thread in the lifetime // of your app. (Windows OS Bug #947272) // // Initializations Type typeofThis = typeof(MatrixCamera); ViewMatrixProperty = RegisterProperty("ViewMatrix", typeof(Matrix3D), typeofThis, Matrix3D.Identity, new PropertyChangedCallback(ViewMatrixPropertyChanged), null, /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); ProjectionMatrixProperty = RegisterProperty("ProjectionMatrix", typeof(Matrix3D), typeofThis, Matrix3D.Identity, new PropertyChangedCallback(ProjectionMatrixPropertyChanged), null, /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); } #endregion Constructors } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Iterator; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.Iterator { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ChangeToYield), Shared] internal class CSharpAddYieldCodeFixProvider : AbstractIteratorCodeFixProvider { /// <summary> /// CS0029: Cannot implicitly convert from type 'x' to 'y' /// </summary> private const string CS0029 = "CS0029"; /// <summary> /// CS0266: Cannot implicitly convert from type 'x' to 'y'. An explicit conversion exists (are you missing a cast?) /// </summary> private const string CS0266 = "CS0266"; public override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(CS0029, CS0266); } } protected override async Task<CodeAction> GetCodeFixAsync(SyntaxNode root, SyntaxNode node, Document document, Diagnostic diagnostics, CancellationToken cancellationToken) { // Check if node is return statement if (!node.IsKind(SyntaxKind.ReturnStatement)) { return null; } var returnStatement = node as ReturnStatementSyntax; var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); ITypeSymbol methodReturnType; if (!TryGetMethodReturnType(node, model, cancellationToken, out methodReturnType)) { return null; } ITypeSymbol returnExpressionType; if (!TryGetExpressionType(model, returnStatement.Expression, out returnExpressionType)) { return null; } var typeArguments = methodReturnType.GetAllTypeArguments(); var shouldOfferYieldReturn = typeArguments.Count() != 1 ? IsCorrectTypeForYieldReturn(returnExpressionType, methodReturnType, model) : IsCorrectTypeForYieldReturn(typeArguments.Single(), returnExpressionType, methodReturnType, model); if (!shouldOfferYieldReturn) { return null; } var yieldStatement = SyntaxFactory.YieldStatement( SyntaxKind.YieldReturnStatement, returnStatement.Expression) .WithAdditionalAnnotations(Formatter.Annotation); root = root.ReplaceNode(returnStatement, yieldStatement); return new MyCodeAction(CSharpFeaturesResources.ChangeToYieldReturn, document.WithSyntaxRoot(root)); } private bool TryGetExpressionType(SemanticModel model, ExpressionSyntax expression, out ITypeSymbol returnExpressionType) { var info = model.GetTypeInfo(expression); returnExpressionType = info.Type; return returnExpressionType != null; } private bool TryGetMethodReturnType(SyntaxNode node, SemanticModel model, CancellationToken cancellationToken, out ITypeSymbol methodReturnType) { methodReturnType = null; var symbol = model.GetEnclosingSymbol(node.Span.Start, cancellationToken); var method = symbol as IMethodSymbol; if (method == null || method.ReturnsVoid) { return false; } methodReturnType = method.ReturnType; return methodReturnType != null; } private bool IsCorrectTypeForYieldReturn(ITypeSymbol typeArgument, ITypeSymbol returnExpressionType, ITypeSymbol methodReturnType, SemanticModel model) { var ienumerableSymbol = model.Compilation.GetTypeByMetadataName("System.Collections.IEnumerable"); var ienumeratorSymbol = model.Compilation.GetTypeByMetadataName("System.Collections.IEnumerator"); var ienumerableGenericSymbol = model.Compilation.GetTypeByMetadataName("System.Collections.Generic.IEnumerable`1"); var ienumeratorGenericSymbol = model.Compilation.GetTypeByMetadataName("System.Collections.Generic.IEnumerator`1"); if (ienumerableGenericSymbol == null || ienumerableSymbol == null || ienumeratorGenericSymbol == null || ienumeratorSymbol == null) { return false; } ienumerableGenericSymbol = ienumerableGenericSymbol.Construct(typeArgument); ienumeratorGenericSymbol = ienumeratorGenericSymbol.Construct(typeArgument); if (!CanConvertTypes(typeArgument, returnExpressionType, model)) { return false; } if (!(methodReturnType.Equals(ienumerableGenericSymbol) || methodReturnType.Equals(ienumerableSymbol) || methodReturnType.Equals(ienumeratorGenericSymbol) || methodReturnType.Equals(ienumeratorSymbol))) { return false; } return true; } private bool CanConvertTypes(ITypeSymbol typeArgument, ITypeSymbol returnExpressionType, SemanticModel model) { // return false if there is no conversion for the top level type if (!model.Compilation.ClassifyConversion(typeArgument, returnExpressionType).Exists) { return false; } // Classify conversion does not consider type parameters on its own so we will have to recurse through them var leftArguments = typeArgument.GetTypeArguments(); var rightArguments = returnExpressionType.GetTypeArguments(); // If we have a mismatch in the number of type arguments we can immediately return as there is no way the types are convertible if ((leftArguments != null && rightArguments != null) && leftArguments.Length != rightArguments.Length) { return false; } // If there are no more type arguments we assume they are convertible since the outer generic types are convertible if (leftArguments == null || !leftArguments.Any()) { return true; } // Check if all the type arguments are convertible for (int i = 0; i < leftArguments.Length; i++) { if (!CanConvertTypes(leftArguments[i], rightArguments[i], model)) { return false; } } // Type argument comparisons have all succeeded, return true return true; } private bool IsCorrectTypeForYieldReturn(ITypeSymbol returnExpressionType, ITypeSymbol methodReturnType, SemanticModel model) { var ienumerableSymbol = model.Compilation.GetTypeByMetadataName("System.Collections.IEnumerable"); var ienumeratorSymbol = model.Compilation.GetTypeByMetadataName("System.Collections.IEnumerator"); if (ienumerableSymbol == null || ienumeratorSymbol == null) { return false; } if (!(methodReturnType.Equals(ienumerableSymbol) || methodReturnType.Equals(ienumeratorSymbol))) { return false; } return true; } protected override bool TryGetNode(SyntaxNode root, TextSpan span, out SyntaxNode node) { node = null; var ancestors = root.FindToken(span.Start).GetAncestors<SyntaxNode>(); if (!ancestors.Any()) { return false; } node = ancestors.FirstOrDefault((n) => n.Span.Contains(span) && n != root && n.IsKind(SyntaxKind.ReturnStatement)); return node != null; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Document newDocument) : base(title, c => Task.FromResult(newDocument)) { } } } }
//////////////////////////////////////////////////////////////////////////////// // // // MIT X11 license, Copyright (c) 2005-2006 by: // // // // Authors: // // Michael Dominic K. <michaldominik@gmail.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. // // // //////////////////////////////////////////////////////////////////////////////// /* See notes about StoreHelper */ namespace Diva.Editor.Model { using System; using System.Collections.Generic; using Gtk; public class StuffTreeStore : TreeStore { // Fields ////////////////////////////////////////////////////// IStuffOrganizer organizer; // The organizer for this store StoreHelper tree; // A helper tree-like thing so we can quickly find stuff // Public methods ////////////////////////////////////////////// /* CONSTRUCTOR */ public StuffTreeStore (IStuffOrganizer organizer) : base (typeof (Gdk.Pixbuf), typeof (bool), typeof (string), typeof (string), typeof (string)) { this.organizer = organizer; organizer.NodeNameChange += OnNodeNameChanged; this.tree = new StoreHelper (); } /* Add new stuff */ public void Add (Core.Stuff stuff) { // Ids this stuff should be in int[] ids = organizer.GetNodeIdForStuff (stuff); foreach (int id in ids) { TreeIter iter; if (tree.HasNode (id)) iter = tree.GetIterForNode (id); else { Append (out iter); tree.AddNode (id, iter); } TreeIter subIter = Insert (iter, 0); tree.AddSubNode (id, subIter, stuff); RefillCategory (id); } RefillStuff (stuff); BindStuff (stuff); } public void Remove (Core.Stuff stuff) { int[] ids = tree.GetIdsForStuff (stuff); TreeIter[] iters = tree.GetItersForStuff (stuff); // First remove the iters foreach (TreeIter iter in iters) { TreeIter iteriter = iter; Remove (ref iteriter); } // Now remove the cats/nodes foreach (int id in ids) { tree.RemoveSubNode (id, stuff); // Check if we need to remove node... if (tree.GetCountForNode (id) == 0) { TreeIter nodeIter = tree.GetIterForNode (id); Remove (ref nodeIter); tree.RemoveNode (id); } else RefillCategory (id); } UnBindStuff (stuff); } public Core.Stuff GetStuffForIter (TreeIter iter) { return tree.GetStuffForIter (iter); } // Private methods ///////////////////////////////////////////// void RefillCategory (int id) { string major = organizer.GetMajorForNodeId (id, tree.GetCountForNode (id)); string minor = organizer.GetMinorForNodeId (id, tree.GetCountForNode (id)); string tags = organizer.GetTagsForNodeId (id, tree.GetCountForNode (id)); TreeIter iter = tree.GetIterForNode (id); // FIXME: Pixbuf? SetValue (iter, 1, false); SetValue (iter, 2, major); SetValue (iter, 3, minor); SetValue (iter, 4, tags); } void RefillStuff (Core.Stuff stuff) { TreeIter[] iters = tree.GetItersForStuff (stuff); foreach (TreeIter iter in iters) { SetValue (iter, 0, stuff.Pixbuf); SetValue (iter, 1, stuff.Border); SetValue (iter, 2, stuff.Major); SetValue (iter, 3, stuff.Minor); SetValue (iter, 4, stuff.TagsString); } } void BindStuff (Core.Stuff stuff) { stuff.Change += OnStuffChanged; } void UnBindStuff (Core.Stuff stuff) { stuff.Change -= OnStuffChanged; } public void OnStuffChanged (object sender, EventArgs args) { UpdateStuff (sender as Core.Stuff); } public void UpdateStuff (Core.Stuff stuff) { int[] newIds = organizer.GetNodeIdForStuff (stuff); int[] oldIds = tree.GetIdsForStuff (stuff); // Remove old foreach (int oldId in oldIds) { bool hasIt = false; foreach (int newId in newIds) if (newId == oldId) { hasIt = true; break; } if (! hasIt) { // We need to remove it TreeIter subIter = tree.GetIterForSubNode (oldId, stuff); Remove (ref subIter); tree.RemoveSubNode (oldId, stuff); // Check if we need to remove node... if (tree.GetCountForNode (oldId) == 0) { TreeIter nodeIter = tree.GetIterForNode (oldId); Remove (ref nodeIter); tree.RemoveNode (oldId); } else RefillCategory (oldId); } } // Add new foreach (int newId in newIds) { bool hasIt = false; foreach (int oldId in oldIds) if (newId == oldId) { hasIt = true; break; } if (! hasIt) { // We need to add it TreeIter iter; if (tree.HasNode (newId)) iter = tree.GetIterForNode (newId); else { Append (out iter); tree.AddNode (newId, iter); } TreeIter subIter = Insert (iter, 0); tree.AddSubNode (newId, subIter, stuff); RefillCategory (newId); } } // Update all the stuff RefillStuff (stuff); } public void OnNodeNameChanged (object o, NodeArgs args) { RefillCategory (args.NodeId); } } }
using System; using System.Collections.Generic; using System.Text; // Copyright (c) 2006, 2007 by Hugh Pyle, inguzaudio.com namespace DSPUtil { public interface ISampleBuffer { // void Reset(); void Skip(int n, out int nn, out bool moreSamples); ISample[] Read(int n, out int nn, out bool moreSamples); Complex[][] ReadComplex(int n, out int nn, out bool moreSamples); } // A padder. Adds silence to the start of the input. // If the pad argument is negative, skips that number of samples from input. public class Padder : SoundObj { int _pad; public Padder(int pad) { _pad = pad; } public Padder(ISoundObj input, int pad) { Input = input; _pad = pad; } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { if (_input == null) { yield break; } Sample nul = new Sample(NumChannels); int j = 0; while(j < _pad) { yield return nul; j++; } foreach (ISample sample in _input) { if (j >= -_pad) { yield return sample; } j++; } } } } // A trivial buffer which reads its input in batches (and can return in batches) // Doesn't support random access. [Serializable] public class SampleBuffer : SoundObj, ISampleBuffer { private ISampleBuffer _inputEnum; public SampleBuffer() { Reset(); } public SampleBuffer(ISoundObj input) { Input = input; Reset(); } private ISampleBuffer GetInputEnum() { if (_inputEnum == null) { _inputEnum = _input.GetBufferedEnumerator() as ISampleBuffer; } return _inputEnum; } public override void Reset() { _inputEnum = null; } public ISample[] Read(int n, out int nn, out bool moreSamples) { return GetInputEnum().Read(n, out nn, out moreSamples); } public Complex[][] ReadComplex(int n, out int nn, out bool moreSamples) { throw new NotImplementedException(); } public void Skip(int n, out int nn, out bool moreSamples) { GetInputEnum().Skip(n, out nn, out moreSamples); } private int _length = int.MaxValue; public int Length { get { return _length==int.MaxValue ? 0 : _length; } set { _length = value; } } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { if (_input == null) { yield break; } int nn; int n = Math.Min(DSPUtil.BUFSIZE, _length); bool moreSamples = true; while (moreSamples) { ISample[] tmp = GetInputEnum().Read(n, out nn, out moreSamples); n -= nn; for(int j=0; j<nn; j++) { yield return tmp[j]; } } } } /// <summary> /// Variant of Subset, supporting negative "start" values /// </summary> /// <param name="start"></param> /// <param name="count"></param> /// <returns></returns> public ISoundObj PaddedSubset(int start, int count) { bool started = false; ISampleBuffer sb = GetInputEnum(); ushort nc = NumChannels; return new CallbackSource(nc, SampleRate, delegate(long n) { int nn; bool more; if (start < 0) { start++; return new Sample(nc); } if (!started) { sb.Skip(start, out nn, out more); started = true; } if (n > count) { return null; } ISample[] sa = sb.Read(1, out nn, out more); if (sa.Length > 0) { return sa[0]; } else { return null; } }); } public ISoundObj Subset(int start) { return Subset(start, int.MaxValue - start); } public ISoundObj Subset(int start, int count) { bool started = false; ISampleBuffer sb = GetInputEnum(); return new CallbackSource(NumChannels, SampleRate, delegate(long n) { int nn; bool more; if (!started) { sb.Skip(start, out nn, out more); started = true; } if (n > count) { return null; } ISample[] sa = sb.Read(1, out nn, out more); if (sa.Length > 0) { return sa[0]; } else { return null; } }); } } // A lazy buffer which retains a copy of the entire stream; supports random access. // Example uses: // - Pull once from input, re-use the stream multiple times. // - More efficient than re-creating the input enum, // - exact same input if e.g. source is noise // - Pull only a subset of information from the source, e.g. for re-use or windowing // - we don't need to read the entire thing [Serializable] public class SoundBuffer : SoundObj, ISampleBuffer { private List<ISample> _samples; private ISampleBuffer _inputEnum = null; private bool _moreSamples = true; // there are samples in the source which we have not yet read private int _pos = 0; private ISample[] _buff; private int _bufflen; private Complex[][] _cbuff; private int _cbufflen; public SoundBuffer() { _samples = new List<ISample>(DSPUtil.BUFSIZE); } public SoundBuffer(ISoundObj input) { _samples = new List<ISample>(DSPUtil.BUFSIZE); Input = input; } public SoundBuffer(List<ISample> samples, ushort numChannels, uint sampleRate) { _samples = samples; Input = null; _nc = numChannels; _sr = sampleRate; } /// <summary> /// The number of samples currently in the buffer. /// This will often be less than the total number of samples available from the input. /// </summary> public int Count { get { return _samples.Count; } } public bool ReadTo(int n) { if (n < _samples.Count) { return true; } if (_input == null) { _moreSamples = false; return _moreSamples; } if (_inputEnum == null) { _inputEnum = _input.GetBufferedEnumerator() as ISampleBuffer; } int nn = n - _samples.Count; if (nn > 0 && _moreSamples) { if (n<int.MaxValue && _samples.Capacity < n) _samples.Capacity = n; int tot = 0; int nnn; while (_moreSamples && tot < nn) { ISample[] tmp = _inputEnum.Read(DSPUtil.BUFSIZE, out nnn, out _moreSamples); for (int j = 0; j < nnn; j++) { _samples.Add(tmp[j]); } tot += nnn; } } return nn < 0 || _moreSamples; } public int ReadAll() { ReadTo(int.MaxValue); return _samples.Count; } #region ISampleBuffer implementation public ISample[] Read(int n, out int nn, out bool moreSamples) { if (_buff == null || _bufflen < n) { _buff = new ISample[n]; _bufflen = n; } int nnn = _pos; int n4 = nnn + n; bool more = ReadTo(n4); nn = (more ? n : _samples.Count - nnn); // Trace.WriteLine("CopyTo {0} {1} {2} {3}", _pos, nnn, nn, _samples.Count); _samples.CopyTo(nnn, _buff, 0, (int)nn); moreSamples = more; _pos += (int)nn; return _buff; } public Complex[][] ReadComplex(int n, out int nn, out bool moreSamples) { if (_cbuff == null || _cbufflen < n) { _cbuff = new Complex[_nc][]; for (ushort c = 0; c < _nc; c++) { _cbuff[c] = new Complex[n]; } _cbufflen = n; } else { for (ushort c = 0; c < _nc; c++) { Array.Clear(_cbuff[c], 0, n); } } int nnn = _pos; int n4 = nnn + n; bool more = ReadTo(n4); nn = (more ? n : _samples.Count - nnn); // Trace.WriteLine("CopyTo {0} {1} {2} {3}", _pos, nnn, nn, _samples.Count); _samples.CopyTo(nnn, _buff, 0, (int)nn); for (int j = 0; j < nn; j++) { ISample s = _samples[nnn + j]; for (ushort c = 0; c < _nc; c++) { _cbuff[c][j].Re = s[c]; } } moreSamples = more; _pos += (int)nn; return _cbuff; } // public void Reset() // { // } public void Skip(int n, out int nn, out bool moreSamples) { Read(n, out nn, out moreSamples); } #endregion // Operations private int _maxPos = int.MaxValue; private double _maxVal = 0; private void FindMax() { for (int j = 0; j < _samples.Count; j++) { ISample s = _samples[j]; for (int c = 0; c < s.NumChannels; c++) { double v = Math.Abs(s[c]); if (v > _maxVal) { _maxVal = v; _maxPos = j; } } } } public int MaxPos() { if (_maxPos == int.MaxValue) { FindMax(); } return _maxPos; } public double MaxVal() { if (_maxPos == int.MaxValue) { FindMax(); } return _maxVal; } /// <summary> /// Normalize the buffer so maximum value is at (dBfs) /// </summary> /// <param name="dBfs">dB-of-fullscale for the new peak</param> /// <returns></returns> public double Normalize(double dBfs) { return Normalize(dBfs, true); } public double Normalize(double dBfs, bool doIt) { // Make sure the whole buffer is scaled double gain = 0; double max = 0; for (int j = 0; j < _samples.Count; j++) { ISample s = _samples[j]; for (int c = 0; c < s.NumChannels; c++) { max = Math.Max(max, Math.Abs(s[c])); } } if (max == 0) { return 0; } gain = MathUtil.gain(dBfs) / max; if (doIt) { ApplyGain(gain); } return gain; } /// <summary> /// Apply a gain (units) to the whole buffer. /// </summary> /// <param name="gain">units to scale by</param> public void ApplyGain(double gain) { for (int j = 0; j < _samples.Count; j++) { ISample s = _samples[j]; _samples[j] = new Sample(s, gain); } } /// <summary> /// Apply a window to the whole buffer. /// </summary> /// <param name="window">Cosine-based window to apply</param> public void ApplyWindow(CosWindow window) { window.Input = new CallbackSource(NumChannels, SampleRate, delegate(long j) { if (j >= _samples.Count) { return null; } return _samples[(int)j]; }); int n=0; foreach (Sample s in window) { _samples[n++] = s; } } public void PadTo(int n) { ReadTo(n); // Add null samples if we're past eof Sample s = new Sample(_input.NumChannels); while (_samples.Count < n) { _samples.Add(s); } } public void PadToPowerOfTwo() { // Ensure that the buffer's total length is a power of two. int n = MathUtil.NextPowerOfTwo(_samples.Count); PadTo(n); } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { _pos = 0; while(_pos < _samples.Count || _moreSamples) { if (!ReadTo(_pos + 1)) { yield break; } yield return _samples[(int)_pos]; _pos++; } } } /// <summary> /// Get an iterator for a subset of samples /// </summary> /// <param name="startPos">Start position (zero-based)</param> /// <param name="count">Number to return</param> /// <returns></returns> public IEnumerator<ISample> SampleSubset(int start, int count) { ReadTo(start + count); for(int j=start; j<start+count && j<_samples.Count; j++) { yield return _samples[j]; } } public ISoundObj Subset(int start) { return Subset(start, int.MaxValue-start); } public ISoundObj Subset(int start, int count) { ReadTo(start + count); return new CallbackSource(NumChannels, SampleRate, delegate(long j) { if (j >= 0 && j < count && (j + start) < _samples.Count) { return _samples[(int)(j + start)]; } return null; }); } // Array-index operator public ISample this[int arg] { get { ReadTo(arg); return _samples[arg]; } } public ISample[] ToArray() { return ToArray(0, -1); } public ISample[] ToArray(int startPos) { return ToArray(startPos, -1); } public ISample[] ToArray(int startPos, int count) { int n = count; if (count < 0) { ReadAll(); n = _samples.Count - startPos; } else { ReadTo(startPos + count); n = Math.Min(startPos + count, _samples.Count); } ISample[] ret = new ISample[n]; for (int j = startPos; j - startPos < n; j++) { ret[j - startPos] = _samples[j]; } return ret; } /// <summary> /// Return the buffer contents as an array of doubles /// </summary> public double[][] ToDoubleArray() { return ToDoubleArray(0, -1); } /// <summary> /// Return the buffer contents as an array of doubles /// </summary> /// <param name="startPos">Start position in the buffer</param> public double[][] ToDoubleArray(int startPos) { return ToDoubleArray(startPos, -1); } /// <summary> /// Return the buffer contents as an array of doubles /// </summary> /// <param name="startPos"></param> /// <param name="count">Length of the return array (will be null-padded if count exceeds data size)</param> /// <returns></returns> public double[][] ToDoubleArray(int startPos, int count) { int n = count; if (count < 0) { ReadAll(); n = _samples.Count - startPos; } else { ReadTo(startPos + count); n = Math.Min(startPos + count, _samples.Count); } double[][] ret = new double[NumChannels][]; for (int c = 0; c < NumChannels; c++) { ret[c] = new double[count<0 ? n : count]; } for (int j = startPos; j - startPos < n; j++) { ISample s = _samples[j]; for (int c = 0; c < NumChannels; c++) { ret[c][j - startPos] = s[c]; } } return ret; } public Complex[][] ToComplexArray() { return ToComplexArray(0, -1); } public Complex[][] ToComplexArray(int startPos) { return ToComplexArray(startPos, -1); } public Complex[][] ToComplexArray(int startPos, int count) { int n = count; if (count < 0) { ReadAll(); n = _samples.Count - startPos; } else { ReadTo(startPos + count); n = Math.Min(count, _samples.Count - startPos); } Complex[][] ret = new Complex[NumChannels][]; for (int c = 0; c < NumChannels; c++) { ret[c] = new Complex[n]; } for (int j = startPos; j - startPos < n; j++) { ISample s = _samples[j]; for (int c = 0; c < NumChannels; c++) { ret[c][j - startPos] = new Complex(s[c],0); } } return ret; } } /// <summary> /// A circular buffer. NB: only have one consumer of the iterator at a time!! /// </summary> public class CircularBuffer : SoundObj { private uint _length = 0; private uint _pos = 0; private ISample[] _data; private ISample _peak = null; private ISample _mean = null; private ISample _meandB = null; private ISample _stddev = null; private ISample _stddevdB = null; /// <summary> /// Create a circular buffer with a given size /// </summary> /// <param name="input">Input stream</param> /// <param name="bufsize">Size of the circular buffer</param> public CircularBuffer(ISoundObj input, uint bufsize) { _data = new ISample[bufsize]; _length = bufsize; Input = input; } /// <summary> /// Create a circular buffer with a given size /// </summary> /// <param name="bufsize">Size of the circular buffer</param> public CircularBuffer(uint bufsize) { _data = new ISample[bufsize]; _length = bufsize; } public override IEnumerator<ISample> Samples { get { if (_input == null) { yield break; } ushort nc = _input.NumChannels; _peak = new Sample(nc); foreach (ISample sample in _input) { // We'll stash this in our buffer // at position _pos. _data[_pos++] = sample; // Calculate peak for (ushort c = 0; c < nc; c++) { _peak[c] = Math.Max(_peak[c], sample[c]); } // Forget any previous mean & stddev _mean = null; _meandB = null; _stddev = null; _stddevdB = null; // Wrap the buffer if (_pos >= _length) { _pos = 0; } // return it yield return sample; } } } /// <summary> /// Access the nth sample. /// Sample zero is always the "current" sample /// (the one most recently returned from the iterator). /// Sample[-1] is the previous sample. /// Sample [1] is the oldest sample we have in buffer. /// </summary> /// <param name="arg">n</param> /// <returns>sample</returns> public ISample this[int arg] { get { // uint n = (uint)((arg - _pos) % _length); uint n = (uint)((((_pos + arg) % _length) + _length) % _length); ISample s = _data[n]; if (s == null) { s = new Sample(_nc); } return s; } } /// <summary> /// Peak value of all samples, ever /// </summary> /// <returns></returns> public ISample Peak() { return _peak; } /// <summary> /// "Average" - arithmetical mean of all samples in buffer /// </summary> /// <returns></returns> public ISample Mean() { if (_mean != null) { return _mean; } ushort nc = _input.NumChannels; _mean = new Sample(nc); for (int n = 0; n < _length; n++) { if (_data[n] != null) { for (ushort c = 0; c < nc; c++) { _mean[c] += _data[n][c]; } } } for (ushort c = 0; c < nc; c++) { _mean[c] /= _length; } return _mean; } /// <summary> /// "Average" - arithmetical mean of dB value of all samples in buffer /// </summary> /// <returns></returns> public ISample MeanDb() { if (_meandB != null) { return _meandB; } ushort nc = _input.NumChannels; _meandB = new Sample(nc); for (int n = 0; n < _length; n++) { if (_data[n] != null) { for (ushort c = 0; c < nc; c++) { _meandB[c] += MathUtil.dB(_data[n][c]); } } } for (ushort c = 0; c < nc; c++) { _meandB[c] /= _length; } return _meandB; } /// <summary> /// Standard deviation of all samples in buffer /// </summary> /// <returns></returns> public ISample StdDev() { if (_stddev != null) { return _stddev; } ISample mean = Mean(); ushort nc = _input.NumChannels; _stddev = new Sample(nc); for (int n = 0; n < _length; n++) { if (_data[n] != null) { for (ushort c = 0; c < nc; c++) { double dev = (_data[n][c] - mean[c]); _stddev[c] += (dev * dev); } } } for (ushort c = 0; c < nc; c++) { _stddev[c] = Math.Sqrt(_stddev[c]/_length); } return _stddev; } /// <summary> /// Standard deviation in dB of all samples in buffer /// </summary> /// <returns></returns> public ISample StdDevDb() { if (_stddevdB != null) { return _stddevdB; } ISample meandb = MeanDb(); ushort nc = _input.NumChannels; _stddevdB = new Sample(nc); for (int n = 0; n < _length; n++) { if (_data[n] != null) { for (ushort c = 0; c < nc; c++) { double devdb = (MathUtil.dB(_data[n][c]) - meandb[c]); _stddevdB[c] += (devdb * devdb); } } } for (ushort c = 0; c < nc; c++) { _stddevdB[c] = Math.Sqrt(_stddevdB[c] / _length); } return _stddevdB; } } // A "reader" buffer whose input is a sample array public class BufferReader : SoundObj { private Sample[] _data; public BufferReader() { //_data = null; } public BufferReader(Sample[] data) { _data = data; } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { if (_data == null) { yield break; } foreach (ISample sample in _data) { yield return sample; } } } } // A "reader" buffer whose input is an array of complex arrays (one per input channel) public enum ComplexBufferFlags { Both = 0, RealOnly = 1, ImaginaryOnly = 2, Magnitude = 3, Phase = 4 } public class ComplexBufferReader : SoundObj { private Complex[][] _data; private int _start; private int _end; private ComplexBufferFlags _flags; public ComplexBufferReader() { // _data = null; } public ComplexBufferReader(Complex[] data, int start, int end) { _data = new Complex[1][]; _data[0] = data; _start = Math.Max(start, 0); _end = Math.Min(end, data.Length); _flags = ComplexBufferFlags.RealOnly; NumChannels = 1; } public ComplexBufferReader(Complex[] data, int start, int end, ComplexBufferFlags flags) { _data = new Complex[1][]; _data[0] = data; _start = Math.Max(start, 0); _end = Math.Min(end, data.Length); _flags = flags; NumChannels = 1; } public ComplexBufferReader(Complex[][] data, ushort nChannels, int start, int end, ComplexBufferFlags flags) { _data = data; _start = Math.Max(start, 0); _end = Math.Min(end, data[0].Length); _flags = flags; NumChannels = (ushort)((_flags==ComplexBufferFlags.Both) ? (2 * nChannels) : nChannels); } public override int Iterations { get { return _end - _start; } } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { if (_data == null) { yield break; } for(int j=_start; j<_end; j++) { yield return _next(j); } } } internal ISample _next(int j) { ISample s = _nc == 2 ? new Sample2() : new Sample(_nc) as ISample; int cc = 0; for (int c = 0; c < _nc; c += ((_flags == ComplexBufferFlags.Both) ? 2 : 1)) { if (_flags == ComplexBufferFlags.Both) { s[c] = _data[cc][j].Re; s[c + 1] = _data[cc][j].Im; } else if (_flags == ComplexBufferFlags.RealOnly) { s[c] = _data[cc][j].Re; } else if (_flags == ComplexBufferFlags.ImaginaryOnly) { s[c] = _data[cc][j].Im; } else if (_flags == ComplexBufferFlags.Magnitude) { s[c] = _data[cc][j].Magnitude; } else if (_flags == ComplexBufferFlags.Phase) { s[c] = _data[cc][j].Phase; } cc++; } return s; } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Umbraco.Core.Configuration; using Umbraco.Core.IO; namespace Umbraco.Core { /// <summary> /// The XmlHelper class contains general helper methods for working with xml in umbraco. /// </summary> public class XmlHelper { /// <summary> /// Creates or sets an attribute on the XmlNode if an Attributes collection is available /// </summary> /// <param name="xml"></param> /// <param name="n"></param> /// <param name="name"></param> /// <param name="value"></param> public static void SetAttribute(XmlDocument xml, XmlNode n, string name, string value) { if (xml == null) throw new ArgumentNullException("xml"); if (n == null) throw new ArgumentNullException("n"); if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value cannot be null or whitespace.", "name"); if (n.Attributes == null) { return; } if (n.Attributes[name] == null) { var a = xml.CreateAttribute(name); a.Value = value; n.Attributes.Append(a); } else { n.Attributes[name].Value = value; } } /// <summary> /// Gets a value indicating whether a specified string contains only xml whitespace characters. /// </summary> /// <param name="s">The string.</param> /// <returns><c>true</c> if the string contains only xml whitespace characters.</returns> /// <remarks>As per XML 1.1 specs, space, \t, \r and \n.</remarks> public static bool IsXmlWhitespace(string s) { // as per xml 1.1 specs - anything else is significant whitespace s = s.Trim(' ', '\t', '\r', '\n'); return s.Length == 0; } /// <summary> /// Creates a new <c>XPathDocument</c> from an xml string. /// </summary> /// <param name="xml">The xml string.</param> /// <returns>An <c>XPathDocument</c> created from the xml string.</returns> public static XPathDocument CreateXPathDocument(string xml) { return new XPathDocument(new XmlTextReader(new StringReader(xml))); } /// <summary> /// Tries to create a new <c>XPathDocument</c> from an xml string. /// </summary> /// <param name="xml">The xml string.</param> /// <param name="doc">The XPath document.</param> /// <returns>A value indicating whether it has been possible to create the document.</returns> public static bool TryCreateXPathDocument(string xml, out XPathDocument doc) { try { doc = CreateXPathDocument(xml); return true; } catch (Exception) { doc = null; return false; } } /// <summary> /// Tries to create a new <c>XPathDocument</c> from a property value. /// </summary> /// <param name="value">The value of the property.</param> /// <param name="doc">The XPath document.</param> /// <returns>A value indicating whether it has been possible to create the document.</returns> /// <remarks>The value can be anything... Performance-wise, this is bad.</remarks> public static bool TryCreateXPathDocumentFromPropertyValue(object value, out XPathDocument doc) { // DynamicNode.ConvertPropertyValueByDataType first cleans the value by calling // XmlHelper.StripDashesInElementOrAttributeName - this is because the XML is // to be returned as a DynamicXml and element names such as "value-item" are // invalid and must be converted to "valueitem". But we don't have that sort of // problem here - and we don't need to bother with dashes nor dots, etc. doc = null; var xml = value as string; if (xml == null) return false; // no a string if (CouldItBeXml(xml) == false) return false; // string does not look like it's xml if (IsXmlWhitespace(xml)) return false; // string is whitespace, xml-wise if (TryCreateXPathDocument(xml, out doc) == false) return false; // string can't be parsed into xml var nav = doc.CreateNavigator(); if (nav.MoveToFirstChild()) { var name = nav.LocalName; // must not match an excluded tag if (UmbracoConfig.For.UmbracoSettings().Scripting.NotDynamicXmlDocumentElements.All(x => x.Element.InvariantEquals(name) == false)) return true; } doc = null; return false; } /// <summary> /// Tries to create a new <c>XElement</c> from a property value. /// </summary> /// <param name="value">The value of the property.</param> /// <param name="elt">The Xml element.</param> /// <returns>A value indicating whether it has been possible to create the element.</returns> /// <remarks>The value can be anything... Performance-wise, this is bad.</remarks> public static bool TryCreateXElementFromPropertyValue(object value, out XElement elt) { // see note above in TryCreateXPathDocumentFromPropertyValue... elt = null; var xml = value as string; if (xml == null) return false; // not a string if (CouldItBeXml(xml) == false) return false; // string does not look like it's xml if (IsXmlWhitespace(xml)) return false; // string is whitespace, xml-wise try { elt = XElement.Parse(xml, LoadOptions.None); } catch { elt = null; return false; // string can't be parsed into xml } var name = elt.Name.LocalName; // must not match an excluded tag if (UmbracoConfig.For.UmbracoSettings().Scripting.NotDynamicXmlDocumentElements.All(x => x.Element.InvariantEquals(name) == false)) return true; elt = null; return false; } /// <summary> /// Sorts the children of a parentNode. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="childNodesXPath">An XPath expression to select children of <paramref name="parentNode"/> to sort.</param> /// <param name="orderBy">A function returning the value to order the nodes by.</param> internal static void SortNodes( XmlNode parentNode, string childNodesXPath, Func<XmlNode, int> orderBy) { var sortedChildNodes = parentNode.SelectNodes(childNodesXPath).Cast<XmlNode>() .OrderBy(orderBy) .ToArray(); // append child nodes to last position, in sort-order // so all child nodes will go after the property nodes foreach (var node in sortedChildNodes) parentNode.AppendChild(node); // moves the node to the last position } /// <summary> /// Sorts the children of a parentNode if needed. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="childNodesXPath">An XPath expression to select children of <paramref name="parentNode"/> to sort.</param> /// <param name="orderBy">A function returning the value to order the nodes by.</param> /// <returns>A value indicating whether sorting was needed.</returns> /// <remarks>same as SortNodes but will do nothing if nodes are already sorted - should improve performances.</remarks> internal static bool SortNodesIfNeeded( XmlNode parentNode, string childNodesXPath, Func<XmlNode, int> orderBy) { // ensure orderBy runs only once per node // checks whether nodes are already ordered // and actually sorts only if needed var childNodesAndOrder = parentNode.SelectNodes(childNodesXPath).Cast<XmlNode>() .Select(x => Tuple.Create(x, orderBy(x))).ToArray(); var a = 0; foreach (var x in childNodesAndOrder) { if (a > x.Item2) { a = -1; break; } a = x.Item2; } if (a >= 0) return false; // append child nodes to last position, in sort-order // so all child nodes will go after the property nodes foreach (var x in childNodesAndOrder.OrderBy(x => x.Item2)) parentNode.AppendChild(x.Item1); // moves the node to the last position return true; } /// <summary> /// Sorts a single child node of a parentNode. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="childNodesXPath">An XPath expression to select children of <paramref name="parentNode"/> to sort.</param> /// <param name="node">The child node to sort.</param> /// <param name="orderBy">A function returning the value to order the nodes by.</param> /// <returns>A value indicating whether sorting was needed.</returns> /// <remarks>Assuming all nodes but <paramref name="node"/> are sorted, this will move the node to /// the right position without moving all the nodes (as SortNodes would do) - should improve perfs.</remarks> internal static bool SortNode( XmlNode parentNode, string childNodesXPath, XmlNode node, Func<XmlNode, int> orderBy) { var nodeSortOrder = orderBy(node); var childNodesAndOrder = parentNode.SelectNodes(childNodesXPath).Cast<XmlNode>() .Select(x => Tuple.Create(x, orderBy(x))).ToArray(); // only one node = node is in the right place already, obviously if (childNodesAndOrder.Length == 1) return false; // find the first node with a sortOrder > node.sortOrder var i = 0; while (i < childNodesAndOrder.Length && childNodesAndOrder[i].Item2 <= nodeSortOrder) i++; // if one was found if (i < childNodesAndOrder.Length) { // and node is just before, we're done already // else we need to move it right before the node that was found if (i == 0 || childNodesAndOrder[i - 1].Item1 != node) { parentNode.InsertBefore(node, childNodesAndOrder[i].Item1); return true; } } else // i == childNodesAndOrder.Length && childNodesAndOrder.Length > 1 { // and node is the last one, we're done already // else we need to append it as the last one // (and i > 1, see above) if (childNodesAndOrder[i - 1].Item1 != node) { parentNode.AppendChild(node); return true; } } return false; } // used by DynamicNode only, see note in TryCreateXPathDocumentFromPropertyValue public static string StripDashesInElementOrAttributeNames(string xml) { using (var outputms = new MemoryStream()) { using (TextWriter outputtw = new StreamWriter(outputms)) { using (var ms = new MemoryStream()) { using (var tw = new StreamWriter(ms)) { tw.Write(xml); tw.Flush(); ms.Position = 0; using (var tr = new StreamReader(ms)) { bool IsInsideElement = false, IsInsideQuotes = false; int ic = 0; while ((ic = tr.Read()) != -1) { if (ic == (int)'<' && !IsInsideQuotes) { if (tr.Peek() != (int)'!') { IsInsideElement = true; } } if (ic == (int)'>' && !IsInsideQuotes) { IsInsideElement = false; } if (ic == (int)'"') { IsInsideQuotes = !IsInsideQuotes; } if (!IsInsideElement || ic != (int)'-' || IsInsideQuotes) { outputtw.Write((char)ic); } } } } } outputtw.Flush(); outputms.Position = 0; using (TextReader outputtr = new StreamReader(outputms)) { return outputtr.ReadToEnd(); } } } } /// <summary> /// Imports a XML node from text. /// </summary> /// <param name="text">The text.</param> /// <param name="xmlDoc">The XML doc.</param> /// <returns></returns> public static XmlNode ImportXmlNodeFromText(string text, ref XmlDocument xmlDoc) { xmlDoc.LoadXml(text); return xmlDoc.FirstChild; } /// <summary> /// Opens a file as a XmlDocument. /// </summary> /// <param name="filePath">The relative file path. ei. /config/umbraco.config</param> /// <returns>Returns a XmlDocument class</returns> public static XmlDocument OpenAsXmlDocument(string filePath) { var reader = new XmlTextReader(IOHelper.MapPath(filePath)) {WhitespaceHandling = WhitespaceHandling.All}; var xmlDoc = new XmlDocument(); //Load the file into the XmlDocument xmlDoc.Load(reader); //Close off the connection to the file. reader.Close(); return xmlDoc; } /// <summary> /// creates a XmlAttribute with the specified name and value /// </summary> /// <param name="xd">The xmldocument.</param> /// <param name="name">The name of the attribute.</param> /// <param name="value">The value of the attribute.</param> /// <returns>a XmlAttribute</returns> public static XmlAttribute AddAttribute(XmlDocument xd, string name, string value) { if (xd == null) throw new ArgumentNullException("xd"); if (string.IsNullOrEmpty(name)) throw new ArgumentException("Value cannot be null or empty.", "name"); var temp = xd.CreateAttribute(name); temp.Value = value; return temp; } /// <summary> /// Creates a text XmlNode with the specified name and value /// </summary> /// <param name="xd">The xmldocument.</param> /// <param name="name">The node name.</param> /// <param name="value">The node value.</param> /// <returns>a XmlNode</returns> public static XmlNode AddTextNode(XmlDocument xd, string name, string value) { if (xd == null) throw new ArgumentNullException("xd"); if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value cannot be null or whitespace.", "name"); var temp = xd.CreateNode(XmlNodeType.Element, name, ""); temp.AppendChild(xd.CreateTextNode(value)); return temp; } /// <summary> /// Sets or Creates a text XmlNode with the specified name and value /// </summary> /// <param name="xd">The xmldocument.</param> /// <param name="parent">The node to set or create the child text node on</param> /// <param name="name">The node name.</param> /// <param name="value">The node value.</param> /// <returns>a XmlNode</returns> public static XmlNode SetTextNode(XmlDocument xd, XmlNode parent, string name, string value) { if (xd == null) throw new ArgumentNullException("xd"); if (parent == null) throw new ArgumentNullException("parent"); if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value cannot be null or whitespace.", "name"); var child = parent.SelectSingleNode(name); if (child != null) { child.InnerText = value; return child; } return AddTextNode(xd, name, value); } /// <summary> /// Sets or creates an Xml node from its inner Xml. /// </summary> /// <param name="xd">The xmldocument.</param> /// <param name="parent">The node to set or create the child text node on</param> /// <param name="name">The node name.</param> /// <param name="value">The node inner Xml.</param> /// <returns>a XmlNode</returns> public static XmlNode SetInnerXmlNode(XmlDocument xd, XmlNode parent, string name, string value) { if (xd == null) throw new ArgumentNullException("xd"); if (parent == null) throw new ArgumentNullException("parent"); if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value cannot be null or whitespace.", "name"); var child = parent.SelectSingleNode(name) ?? xd.CreateNode(XmlNodeType.Element, name, ""); child.InnerXml = value; return child; } /// <summary> /// Creates a cdata XmlNode with the specified name and value /// </summary> /// <param name="xd">The xmldocument.</param> /// <param name="name">The node name.</param> /// <param name="value">The node value.</param> /// <returns>A XmlNode</returns> public static XmlNode AddCDataNode(XmlDocument xd, string name, string value) { if (xd == null) throw new ArgumentNullException("xd"); if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value cannot be null or whitespace.", "name"); var temp = xd.CreateNode(XmlNodeType.Element, name, ""); temp.AppendChild(xd.CreateCDataSection(value)); return temp; } /// <summary> /// Sets or Creates a cdata XmlNode with the specified name and value /// </summary> /// <param name="xd">The xmldocument.</param> /// <param name="parent">The node to set or create the child text node on</param> /// <param name="name">The node name.</param> /// <param name="value">The node value.</param> /// <returns>a XmlNode</returns> public static XmlNode SetCDataNode(XmlDocument xd, XmlNode parent, string name, string value) { if (xd == null) throw new ArgumentNullException("xd"); if (parent == null) throw new ArgumentNullException("parent"); if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value cannot be null or whitespace.", "name"); var child = parent.SelectSingleNode(name); if (child != null) { child.InnerXml = "<![CDATA[" + value + "]]>"; ; return child; } return AddCDataNode(xd, name, value); } /// <summary> /// Gets the value of a XmlNode /// </summary> /// <param name="n">The XmlNode.</param> /// <returns>the value as a string</returns> public static string GetNodeValue(XmlNode n) { var value = string.Empty; if (n == null || n.FirstChild == null) return value; value = n.FirstChild.Value ?? n.InnerXml; return value.Replace("<!--CDATAOPENTAG-->", "<![CDATA[").Replace("<!--CDATACLOSETAG-->", "]]>"); } /// <summary> /// Determines whether the specified string appears to be XML. /// </summary> /// <param name="xml">The XML string.</param> /// <returns> /// <c>true</c> if the specified string appears to be XML; otherwise, <c>false</c>. /// </returns> public static bool CouldItBeXml(string xml) { if (string.IsNullOrEmpty(xml)) return false; xml = xml.Trim(); return xml.StartsWith("<") && xml.EndsWith(">") && xml.Contains('/'); } /// <summary> /// Splits the specified delimited string into an XML document. /// </summary> /// <param name="data">The data.</param> /// <param name="separator">The separator.</param> /// <param name="rootName">Name of the root.</param> /// <param name="elementName">Name of the element.</param> /// <returns>Returns an <c>System.Xml.XmlDocument</c> representation of the delimited string data.</returns> public static XmlDocument Split(string data, string[] separator, string rootName, string elementName) { return Split(new XmlDocument(), data, separator, rootName, elementName); } /// <summary> /// Splits the specified delimited string into an XML document. /// </summary> /// <param name="xml">The XML document.</param> /// <param name="data">The delimited string data.</param> /// <param name="separator">The separator.</param> /// <param name="rootName">Name of the root node.</param> /// <param name="elementName">Name of the element node.</param> /// <returns>Returns an <c>System.Xml.XmlDocument</c> representation of the delimited string data.</returns> public static XmlDocument Split(XmlDocument xml, string data, string[] separator, string rootName, string elementName) { // load new XML document. xml.LoadXml(string.Concat("<", rootName, "/>")); // get the data-value, check it isn't empty. if (!string.IsNullOrEmpty(data)) { // explode the values into an array var values = data.Split(separator, StringSplitOptions.None); // loop through the array items. foreach (string value in values) { // add each value to the XML document. var xn = XmlHelper.AddTextNode(xml, elementName, value); xml.DocumentElement.AppendChild(xn); } } // return the XML node. return xml; } /// <summary> /// Return a dictionary of attributes found for a string based tag /// </summary> /// <param name="tag"></param> /// <returns></returns> public static Dictionary<string, string> GetAttributesFromElement(string tag) { var m = Regex.Matches(tag, "(?<attributeName>\\S*)=\"(?<attributeValue>[^\"]*)\"", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); // fix for issue 14862: return lowercase attributes for case insensitive matching var d = m.Cast<Match>().ToDictionary(attributeSet => attributeSet.Groups["attributeName"].Value.ToString().ToLower(), attributeSet => attributeSet.Groups["attributeValue"].Value.ToString()); return d; } } }
using System; using System.IO; using Gibraltar.Data; using Gibraltar.Serialization; using Loupe.Extensibility.Data; using System.Diagnostics; #if NET5_0 || NETSTANDARD2_0_OR_GREATER using System.IO.Compression; #else using Ionic.Zlib; #endif #pragma warning disable 1591 namespace Gibraltar.Monitor.Serialization { public class GLFWriter : IDisposable { private const int MaxExpectedPacketSize = 1024; private const int BufferSize = 16 * 1024; private readonly Stream m_OutputStream; private readonly Stream m_PacketStream; private readonly PacketWriter m_PacketWriter; private readonly FileHeader m_FileHeader; private readonly SessionSummary m_SessionSummary; private readonly SessionHeader m_SessionHeader; private bool m_AutoFlush; private bool m_WeAreDisposed; /// <summary> /// Initialize the GLF writer for the provided session which has already been recorded. /// </summary> /// <param name="file">The file stream to write the session file into (should be empty)</param> /// <param name="sessionSummary"></param> /// <remarks>This constructor is designed for use with sessions that have already been completed and closed.</remarks> public GLFWriter(Stream file, SessionSummary sessionSummary) :this(file, sessionSummary, FileHeader.DefaultMajorVersion, FileHeader.DefaultMinorVersion) { } /// <summary> /// Initialize the GLF writer for the provided session which has already been recorded. /// </summary> /// <param name="file">The file stream to write the session file into (should be empty)</param> /// <param name="sessionSummary"></param> /// <param name="majorVersion">Major version of the serialization protocol</param> /// <param name="minorVersion">Minor version of the serialization protocol</param> /// <remarks>This constructor is designed for use with sessions that have already been completed and closed.</remarks> public GLFWriter(Stream file, SessionSummary sessionSummary, int majorVersion, int minorVersion) : this(file, sessionSummary, 1, null, majorVersion, minorVersion) { } /// <summary> /// Initialize the GLF writer for storing information about the current live session /// </summary> /// <param name="file">The file stream to write the session file into (should be empty)</param> /// <param name="sessionSummary"></param> /// <param name="fileSequence"></param> /// <param name="fileStartTime">Used during initial collection to indicate the real time this file became the active file.</param> /// <remarks>The file header is configured with a copy of the session summary, assuming that we're about to make a copy of the /// session. For live data collection the caller should supply the file start time to reflect the true time period /// covered by this file. </remarks> public GLFWriter(Stream file, SessionSummary sessionSummary, int fileSequence, DateTimeOffset? fileStartTime) : this(file, sessionSummary, fileSequence, fileStartTime, FileHeader.DefaultMajorVersion, FileHeader.DefaultMinorVersion) { } /// <summary> /// Initialize the GLF writer for storing information about the current live session /// </summary> /// <param name="file">The file stream to write the session file into (should be empty)</param> /// <param name="sessionSummary"></param> /// <param name="fileSequence"></param> /// <param name="fileStartTime">Used during initial collection to indicate the real time this file became the active file.</param> /// <param name="majorVersion">Major version of the serialization protocol</param> /// <param name="minorVersion">Minor version of the serialization protocol</param> /// <remarks>The file header is configured with a copy of the session summary, assuming that we're about to make a copy of the /// session. For live data collection the caller should supply the file start time to reflect the true time period /// covered by this file. </remarks> public GLFWriter(Stream file, SessionSummary sessionSummary, int fileSequence, DateTimeOffset? fileStartTime, int majorVersion, int minorVersion) { //for use to use the stream, it has to support if (file.CanSeek == false) { throw new ArgumentException("Provided stream can't be used because it doesn't support seeking", nameof(file)); } m_SessionSummary = sessionSummary; m_OutputStream = file; // This logic will store GZip compressed files for protocol version 2 and beyond if (majorVersion > 1) { //Be sure whatever GZipStream you use supports flushing.. #if NET461 || NET462 || NET47 || NET471 || NET472 || NET48 m_PacketStream = new GZipStream(m_OutputStream, CompressionMode.Compress, CompressionLevel.Default, true) { FlushMode = FlushType.Sync }; #else m_PacketStream = new GZipStream(m_OutputStream, CompressionLevel.Fastest, true); #endif } else { m_PacketStream = new MemoryStream(BufferSize + MaxExpectedPacketSize); } m_PacketWriter = new PacketWriter(m_PacketStream, majorVersion, minorVersion); //initialize the stream with the file header and session header m_FileHeader = new FileHeader(majorVersion, minorVersion); m_SessionHeader = new SessionHeader(sessionSummary); //There are two variants of the GLF format: One for a whole session, one for a session fragment. if (fileStartTime.HasValue) { m_SessionHeader.FileId = Guid.NewGuid(); m_SessionHeader.FileSequence = fileSequence; m_SessionHeader.FileStartDateTime = fileStartTime.Value; m_SessionHeader.FileEndDateTime = m_SessionHeader.EndDateTime; //by default, this is the last file - it won't be if we open another. m_SessionHeader.IsLastFile = true; } //we need to know how big the session header will be (it's variable sized) before we can figure out the data offset. byte[] sessionHeader = m_SessionHeader.RawData(); //where are we going to start our data block? m_FileHeader.DataOffset = FileHeader.HeaderSize + sessionHeader.Length; byte[] header = m_FileHeader.RawData(); m_OutputStream.Position = 0; //move to the start of the stream, we rely on this. m_OutputStream.Write(header, 0, FileHeader.HeaderSize); m_OutputStream.Write(sessionHeader, 0, sessionHeader.Length); m_OutputStream.Flush(); m_OutputStream.Position = m_FileHeader.DataOffset; //so we are sure we start writing our data at the correct spot. // When we added GZip compression to streams we noticed that we were sometimes // losing a lot of data that went unflushed while programmers were testing in // Visual Studio. To address this, we have the GZip stream flush to disk much // more aggressively when we detect that the debugger is attached. #if !DEBUG // We only want this behavior for release builds, not for our own debug builds // we might prefer the writing to be the more typical optimized behavior. AutoFlush = Debugger.IsAttached; #endif } public virtual void Write(IPacket packet) { m_PacketWriter.Write(packet); if (m_AutoFlush || (m_PacketStream is MemoryStream && m_PacketStream.Position >= BufferSize)) Flush(); } public virtual void Write(Stream sessionPacketStream) { FileSystemTools.StreamContentPump(sessionPacketStream, m_OutputStream); } public bool AutoFlush { get => m_AutoFlush; set => m_AutoFlush = value; } public void Flush() { UpdateSessionHeader(); if (m_PacketStream is MemoryStream) { int count = (int) m_PacketStream.Position; if (count > 0) { byte[] array = ((MemoryStream) m_PacketStream).ToArray(); m_OutputStream.Write(array, 0, count); m_OutputStream.Flush(); m_PacketStream.Position = 0; } } else { m_PacketStream.Flush(); m_OutputStream.Flush(); } } /// <summary> /// Update the session file with the latest session summary information. /// </summary> internal static void UpdateSessionHeader(GLFReader sourceFile, Stream updateFile) { long originalPosition = updateFile.Position; try { updateFile.Position = FileHeader.HeaderSize; byte[] header = sourceFile.SessionHeader.RawData(); updateFile.Write(header, 0, header.Length); } finally { updateFile.Position = originalPosition; //move back to wherever it was updateFile.Flush(); //and make sure it's been written to disk. } } /// <summary> /// Update the session file with the latest session summary information. /// </summary> private void UpdateSessionHeader() { long originalPosition = m_OutputStream.Position; try { m_OutputStream.Position = FileHeader.HeaderSize; //The file includes up through now (after all, we're flushing it to disk) m_SessionHeader.EndDateTime = m_SessionSummary.EndDateTime; //this is ONLY changing what we write out in the file & the index, not the main packet... if (m_SessionHeader.HasFileInfo) { m_SessionHeader.FileEndDateTime = m_SessionSummary.EndDateTime; //we convert to UTC during serialization, we want local time. } //session status updates are tricky... We don't want the stream to reflect running //once closed, but we do want to allow other changes. if ((m_SessionSummary.Status == SessionStatus.Crashed) || (m_SessionSummary.Status == SessionStatus.Normal)) { m_SessionHeader.StatusName = m_SessionSummary.Status.ToString(); } //plus we want the latest statistics m_SessionHeader.MessageCount = m_SessionSummary.MessageCount; m_SessionHeader.CriticalCount = m_SessionSummary.CriticalCount; m_SessionHeader.ErrorCount = m_SessionSummary.ErrorCount; m_SessionHeader.WarningCount = m_SessionSummary.WarningCount; byte[] header = m_SessionHeader.RawData(); m_OutputStream.Write(header, 0, header.Length); } finally { m_OutputStream.Position = originalPosition; //move back to wherever it was } } public virtual void Close(bool isLastFile) { //set our session end date in our header - this doesn't imply that we're clean or anything, just that this is the end. if (m_SessionSummary.Status == SessionStatus.Crashed) m_SessionHeader.StatusName = SessionStatus.Crashed.ToString(); else m_SessionHeader.StatusName = SessionStatus.Normal.ToString(); m_SessionHeader.IsLastFile = isLastFile; Flush(); //updates the session header on its own. //and we create our own PacketWriter, so handle that, too m_PacketWriter.Dispose(); } public SessionHeader SessionHeader { get { return m_SessionHeader; } } #region IDisposable Members ///<summary> ///Performs application-defined tasks associated with freeing, releasing, or resetting managed resources. ///</summary> ///<filterpriority>2</filterpriority> public void Dispose() { // Call the underlying implementation Dispose(true); // and SuppressFinalize because there won't be anything left to finalize GC.SuppressFinalize(this); } /// <summary> /// Performs the actual releasing of managed and unmanaged resources. /// Most usage should instead call Dispose(), which will call Dispose(true) for you /// and will suppress redundant finalization. /// </summary> /// <param name="releaseManaged">Indicates whether to release managed resources. /// This should only be called with true, except from the finalizer which should call Dispose(false).</param> protected virtual void Dispose(bool releaseManaged) { if (!m_WeAreDisposed) { m_WeAreDisposed = true; // Only Dispose stuff once if (releaseManaged) { // Free managed resources here (normal Dispose() stuff, which should itself call Dispose(true)) // Other objects may be referenced in this case // We already have a Close(), so just invoke that Close(false); // Ah, we didn't have a clean end, so don't set the last-file marker } // Free native resources here (alloc's, etc) // May be called from within the finalizer, so don't reference other objects here } } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using xlsgen; using System.IO; using DowUtils; namespace Factotum { public partial class ReportDefinitionImporter : Form { [DllImport("xlsgen.dll")] static extern IXlsEngine Start(); EOutage curOutage; EUnit curUnit; string[] colNames; string[] colHeads; // Collections of objects that will be inserted if the user clicks to Import EInspectedComponentCollection reportsToInsert; // A list of pending report definition changes. Each list item represents a proposed change to one // field of one InspectedComponent record. List<PendingChange> pendingChanges; List<string> reportNames; List<string> componentNames; // This flag tracks whether or not any Insertions or changes are required to get the database // in synch with the spreadsheet. It's used to control enabling of the Import button. bool AnyInsertionsOrChanges = false; // Constructor -- We MUST have an OutageID because every InspectedComponent belongs to an Outage. public ReportDefinitionImporter(Guid OutageID) { curOutage = new EOutage(OutageID); curUnit = new EUnit(curOutage.OutageUntID); InitializeComponent(); InitializeControls(); } // Initialize the form control values private void InitializeControls() { lblSiteName.Text = "Import for Outage: " + curUnit.UnitNameWithSite + " - " + curOutage.OutageName; DowUtils.Util.CenterControlHorizInForm(lblSiteName, this); // Initialize the array of allowed column names. The first row of the user's spreadsheet // must include all these names (in any order). initColNames(); btnImport.Enabled = false; } // The user clicked to select a file and preview changes private void btnSelectAndPreview_Click(object sender, EventArgs e) { // Setup and show the file open dialog openFileDialog1.InitialDirectory = Globals.FactotumDataFolder; openFileDialog1.FileName = null; openFileDialog1.Filter = "Excel files *.xls|*.xls"; DialogResult rslt = openFileDialog1.ShowDialog(); if (rslt == DialogResult.OK) { if (!ProcessFile(openFileDialog1.FileName)) { tvwItemAdd.Nodes.Clear(); tvwReportChange.Nodes.Clear(); } } } private bool ProcessFile(string xlsFile) { IXlsEngine engine; IXlsWorkbook wbk = null; IXlsWorksheet wks; // Xlsgen needs to create a spreadsheet file even though we're really only using it to read // data from the spreadsheet so we'll create a temporary file in the user's local settings temp // folder and delete it when we're finished. string tempFile = null; string tempXlsFile = null; // The last row of the spreadsheet that contains a report name int lastRow; // The indices of the columns int reportNameIdx = 0; int workOrderIdx = 0; int componentNameIdx = 0; // If the dialog result is OK, try to open the workbook and get the first sheet. try { tempFile = Path.GetTempFileName(); // XlsGen needs the file to have an xls suffix or it won't work. tempXlsFile = tempFile.Substring(0, tempFile.Length - 3) + "xls"; engine = Start(); wbk = engine.Open(xlsFile, tempXlsFile); // Get the first sheet. Any other sheets are ignored. wks = wbk.get_WorksheetByIndex(1); // Read the first row of the spreadsheet for column headings. readColHeadings(wks); // We have to have all three columns. if (!IsInArray(colHeads, "ReportName", out reportNameIdx)) { MessageBox.Show("A column called 'ReportName' for the Report Name is required", "Factotum Report Definition Importer", MessageBoxButtons.OK); return false; } if (!IsInArray(colHeads, "WorkOrder", out workOrderIdx)) { MessageBox.Show("A column called 'WorkOrder' for the Work Order Number is required", "Factotum Report Definition Importer", MessageBoxButtons.OK); return false; } if (!IsInArray(colHeads, "ComponentName", out componentNameIdx)) { MessageBox.Show("A column called 'ComponentName' for the Component Name is required", "Factotum Report Definition Importer", MessageBoxButtons.OK); return false; } // Read through rows until the component name is an empty string. // This function will return false if a partial row is found. if(!GetLastRow(wks, reportNameIdx, workOrderIdx, componentNameIdx,out lastRow)) return false; if (lastRow <= 1) { MessageBox.Show("No data rows found in the selected file.", "Factotum Report Definition Importer", MessageBoxButtons.OK); return false; } // Prepare the tree views tvwItemAdd.Nodes.Clear(); tvwReportChange.Nodes.Clear(); // Initialize the collections and lists reportsToInsert = new EInspectedComponentCollection(); pendingChanges = new List<PendingChange>(); reportNames = new List<string>(); componentNames = new List<string>(); // Process each row of the spreadsheet for (int row = 2; row <= lastRow; row++) { if (!ProcessRow(wks, row, reportNameIdx, workOrderIdx, componentNameIdx)) return false; } if (AnyInsertionsOrChanges) { btnImport.Enabled = true; foreach (TreeNode tn in tvwReportChange.Nodes) tn.Checked = true; tvwReportChange.ExpandAll(); tvwItemAdd.ExpandAll(); } else { MessageBox.Show("All Report Definition data in the selected file is already in the system.", "Factotum Report Definition Importer", MessageBoxButtons.OK); } } catch (Exception ex) { ExceptionLogger.LogException(ex); MessageBox.Show("An error occurred while trying to process the selected file.\nThe details have been recorded in 'error.log'.", "Factotum Report Definition Importer", MessageBoxButtons.OK); } finally { // In Xlsgen 2.0 and above, // Workbooks are automatically closed when the engine goes out of scope. // When I explicitly closed the workbook here, I was getting a sporadic run-time error // System.AccessViolationException: Attempted to read or write protected memory. // This is often an indication that other memory is corrupt. // at xlsgen.IXlsWorkbook.Close() // I wasn't able to generate this error in debug mode, just in release mode. // I can't reproduce the error now that the explicit Close() is removed. // Note: since we're not explicitly closing, we can't delete the tempfiles. Oh well... //if (wbk != null) wbk.Close(); // Note: when we called Path.GetTempFileName(), tempFile was actually created, so delete it. //if (File.Exists(tempFile)) File.Delete(tempFile); //if (File.Exists(tempXlsFile)) File.Delete(tempXlsFile); } return true; } private string TruncateTo(string s, int limit) { if (s == null) return null; if (s.Length > limit) return s.Substring(0, limit); return s; } // ----------------------------------------------------- // Process one row of the worksheet. // ----------------------------------------------------- private bool ProcessRow(IXlsWorksheet wks, int row, int reportNameIdx, int workOrderIdx, int componentNameIdx) { string reportName, workOrder, componentName; bool existingIsInactive; componentName = wks.get_Label(row, componentNameIdx + 1); // should be no way this can be null. componentName = TruncateTo(componentName, EComponent.CmpNameCharLimit); reportName = wks.get_Label(row, reportNameIdx + 1); // should be no way this can be null. reportName = TruncateTo(reportName, EInspectedComponent.IscNameCharLimit); workOrder = wks.get_Label(row, workOrderIdx + 1); // should be no way this can be null. workOrder = TruncateTo(workOrder, EInspectedComponent.IscWorkOrderCharLimit); // Notify the user if we have a duplicate component name. if (IsReportNameInList(reportName)) { MessageBox.Show("The Report Name " + reportName + " appears more than once in the file.", "Factotum Report Definition Importer", MessageBoxButtons.OK); return false; } // Notify the user if we have a duplicate component name. if (IsComponentNameInList(componentName)) { MessageBox.Show("The Component Name " + componentName + " appears more than once in the file.", "Factotum Report Definition Importer", MessageBoxButtons.OK); return false; } // If a component name is referenced that doesn't exist yet if (!EComponent.NameExistsForUnit( componentName, null, (Guid)curUnit.ID, out existingIsInactive)) { MessageBox.Show("Component Name " + componentName + " in row " + row + " is not defined for this facility.", "Factotum Report Definition Importer", MessageBoxButtons.OK); return false; } // Try to get an existing report for modification EInspectedComponent eReport = EInspectedComponent.FindForComponentName((Guid)curOutage.ID, componentName); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // New report case -- no report definition exists for that component yet. if (eReport == null) { if (EInspectedComponent.NameExistsForOutage(reportName, curOutage.ID, null)) { MessageBox.Show("Unable to add a report definition for component '" + componentName + "' in row " + row + "\r\nbecause the Report Name specified '" + reportName + "' is already being used for a different component.", "Factotum Report Definition Importer", MessageBoxButtons.OK); return false; } // create a new entity object eReport = new EInspectedComponent(); EComponent eComponent = EComponent.FindForComponentNameAndUnit(componentName, (Guid)curUnit.ID); // Don't set the outage ID yet. It's used by the entity to get a new EDS number, // so we need to set it right after the previous entity was saved. eReport.InspComponentCmpID = eComponent.ID; eReport.InspComponentName = reportName; eReport.InspComponentWorkOrder = workOrder; // add a subnode to the treeview node. AddInsertItemToTreeView("Report: " + reportName + " for Component: " + componentName); // add the object to a (to-be-inserted) collection reportsToInsert.Add(eReport); AnyInsertionsOrChanges = true; } else { // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Modify report case -- A report definition already exists for that component. int itemIdx; string tempStr; string colHead; string colDisplay; string oldDisplayValue; colHead = "ReportName"; colDisplay = "Report Name"; oldDisplayValue = eReport.InspComponentName; if (IsInArray(colHeads, colHead, out itemIdx)) { tempStr = wks.get_Label(row, itemIdx + 1); if (!Matches(oldDisplayValue, tempStr)) { // The user is trying to change the report name for the component. if (EInspectedComponent.NameExistsForOutage(reportName, curOutage.ID, null)) { MessageBox.Show("Unable to modify the report definition for component '" + componentName + "' in row " + row + "\r\nbecause the Report Name specified '" + reportName + "' is already being used for a different component.", "Factotum Report Definition Importer", MessageBoxButtons.OK); return false; } PendingChange pc = new PendingChange(componentName, colHead, colDisplay, oldDisplayValue, tempStr); pendingChanges.Add(pc); AddReportChangeToTreeView(pc); } } colHead = "WorkOrder"; colDisplay = "Work Order"; oldDisplayValue = eReport.InspComponentWorkOrder; if (IsInArray(colHeads, colHead, out itemIdx)) { tempStr = wks.get_Label(row, itemIdx + 1); if (!Matches(oldDisplayValue, tempStr)) { PendingChange pc = new PendingChange(componentName, colHead, colDisplay, oldDisplayValue, tempStr); pendingChanges.Add(pc); AddReportChangeToTreeView(pc); } } } componentNames.Add(componentName); reportNames.Add(reportName); return true; } // Add an insert item to the tree view under the appropriate item type. // If this is the first item of that type, add the type node first. private void AddInsertItemToTreeView(string ItemName) { // Found the node, so add the child tvwItemAdd.Nodes.Add(ItemName); AnyInsertionsOrChanges = true; } // Add a report change item to the tree view under the appropriate component name. // If this is the first changed field for that report, add the component name node first. private void AddReportChangeToTreeView(PendingChange pc) { TreeNode[] nodes; nodes = tvwReportChange.Nodes.Find(pc.ComponentName, false); if (nodes.Length > 0) { // Found the node, so add the child nodes[0].Nodes.Add(pc.TreeViewNodeText); } else { // Create the node, then add the child TreeNode tn = tvwReportChange.Nodes.Add(pc.ComponentName, pc.ComponentName); tn.Nodes.Add(pc.TreeViewNodeText); } AnyInsertionsOrChanges = true; } // Get the last data row of the spreadsheet. This is simply the last row that has all three // required values. If a row is found that is missing any of the three, an exception is raised. private bool GetLastRow(IXlsWorksheet wks, int reportNameColumn, int workOrderColumn, int componentNameColumn, out int lastRow) { int row = 2; lastRow = 0; string reportName = wks.get_Label(row, reportNameColumn + 1); string workOrder = wks.get_Label(row, workOrderColumn + 1); string componentName = wks.get_Label(row, componentNameColumn + 1); while (reportName.Length > 0 || workOrder.Length > 0 || componentName.Length > 0) { if (reportName.Length == 0 || workOrder.Length == 0 || componentName.Length == 0) { MessageBox.Show("Missing required information in row " + row, "Factotum Report Definition Importer", MessageBoxButtons.OK); return false; } row++; reportName = wks.get_Label(row, reportNameColumn + 1); workOrder = wks.get_Label(row, workOrderColumn + 1); componentName = wks.get_Label(row, componentNameColumn + 1); } lastRow = row - 1; return true; } // Read the column headings into an array private void readColHeadings(IXlsWorksheet wks) { int col = 0; //int idx = 0; string heading; List<string> tempHeadings; tempHeadings = new List<string>(20); while ((heading = wks.get_Label(1, col + 1)).Length > 0) { tempHeadings.Add(heading); col++; } colHeads = tempHeadings.ToArray(); //int idx = 0; //string heading; //// First check to be sure that all column headings are valid. //while ((heading = wks.get_Label(1,col+1)).Length > 0) //{ // if (!IsInArray(colNames, heading, out idx)) // { // return false; // } // col++; //} //// Add the column headings to the array //int cols = col; //colHeads = new string[cols]; //for (col = 0; col < cols; col++) colHeads[col] = wks.get_Label(1, col+1); //return true; } // Check if a string is in an array. If so, send out the index. // Note: this function assumes a 1-based array private bool IsInArray(string[] ar, string item, out int index) { for (int i = 0; i < ar.Length; i++) { if (ar[i].ToUpper() == item.ToUpper()) { index = i; return true; } } index = 0; return false; } // Check if a Report Name is already in our collection of Reports to be added. private bool IsReportNameInList(string ReportName) { foreach (string report in reportNames) { if (report == ReportName) return true; } return false; } // Check if a Component Name is already in our collection of Reports to be added. private bool IsComponentNameInList(string ComponentName) { foreach (string component in componentNames) { if (component == ComponentName) return true; } return false; } // Check if two strings 'match'. They 'match' if they are both null or are equal except for // possible casing differences. private bool Matches(string s1, string s2) { if (s1 == null && s2 == null) return true; else if (s1 == null || s2 == null) return false; else if (s1.ToUpper() == s2.ToUpper()) return true; else return false; } // Initialize the column names array that contains all allowed column names private void initColNames() { colNames = new string[] { "ReportName", "WorkOrder", "ComponentName" }; } // Handle the user's click on the Import button. This button should only be enabled if // a file has been selected and some changes proposed. private void btnImport_Click(object sender, EventArgs e) { // Save any parent entities that have been placed on 'to-insert' lists. // Go through the collection of components to be inserted for (int i = 0; i < reportsToInsert.Count; i++) { // Create a new report EInspectedComponent eReport = reportsToInsert[i]; // Set the Outage ID -- this causes a new sequential EDS number to be created. eReport.InspComponentOtgID = curOutage.ID; // Insert the report eReport.Save(); } // Go through all the nodes in the Component Changes tree to determine which items were checked. // Simultaneously step through the pendingChanges list. int change = 0; foreach (TreeNode node in tvwReportChange.Nodes) { // For each component node... string componentName = node.Name; EInspectedComponent eReport = EInspectedComponent.FindForComponentName((Guid)curOutage.ID, pendingChanges[change].ComponentName); bool somethingChanged = false; foreach (TreeNode child in node.Nodes) { // For each change previewed for the current component if (child.Checked) { somethingChanged = true; // Update the entity object with the values stored in each pending change. switch (pendingChanges[change].ColHead) { case "ReportName": eReport.InspComponentName = pendingChanges[change].NewDisplayValue; break; case "WorkOrder": eReport.InspComponentWorkOrder = pendingChanges[change].NewDisplayValue; break; default: throw new Exception("Unexpected Column name"); } } change++; } if (somethingChanged) { eReport.Save(); } } MessageBox.Show("Reports Imported Successfully", "Factotum"); Close(); } // Close the form private void btnCancel_Click(object sender, EventArgs e) { Close(); } // If a component is checked or un-checked, check or un-check all change items for that component. private void tvwComponentChange_AfterCheck(object sender, TreeViewEventArgs e) { if (e.Node.Level == 0) { bool isChecked = e.Node.Checked; tvwReportChange.AfterCheck -= new System.Windows.Forms.TreeViewEventHandler(tvwComponentChange_AfterCheck); foreach (TreeNode child in e.Node.Nodes) child.Checked = isChecked; tvwReportChange.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(tvwComponentChange_AfterCheck); } } // A subclass for managing pending changes to components. private class PendingChange { public string ComponentName; public string ColHead; public string ColumnDisplayName; public string OldDisplayValue; public string NewDisplayValue; // We have two public constructors which call a private one, as a sort of cheesy way // to use this object for both changes to string values and changes to decimal values. public PendingChange(string componentName, string colHead, string columnDisplayName, string oldDisplayValue, string newDisplayValue) { ComponentName = componentName; ColHead = colHead; ColumnDisplayName = columnDisplayName; OldDisplayValue = oldDisplayValue; NewDisplayValue = newDisplayValue; } // Get the text to insert in a component change TreeNode public string TreeViewNodeText { get { return ColumnDisplayName + ": " + OldDisplayValue + " --> " + NewDisplayValue; } } } // End Main class } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using Moq.Properties; namespace Moq { /// <summary> /// Utility factory class to use to construct multiple /// mocks when consistent verification is /// desired for all of them. /// </summary> /// <remarks> /// If multiple mocks will be created during a test, passing /// the desired <see cref="MockBehavior"/> (if different than the /// <see cref="MockBehavior.Default"/> or the one /// passed to the factory constructor) and later verifying each /// mock can become repetitive and tedious. /// <para> /// This factory class helps in that scenario by providing a /// simplified creation of multiple mocks with a default /// <see cref="MockBehavior"/> (unless overridden by calling /// <see cref="Create{T}(MockBehavior)"/>) and posterior verification. /// </para> /// </remarks> /// <example group="factory"> /// The following is a straightforward example on how to /// create and automatically verify strict mocks using a <see cref="MockFactory"/>: /// <code> /// var factory = new MockFactory(MockBehavior.Strict); /// /// var foo = factory.Create&lt;IFoo&gt;(); /// var bar = factory.Create&lt;IBar&gt;(); /// /// // no need to call Verifiable() on the setup /// // as we'll be validating all of them anyway. /// foo.Setup(f => f.Do()); /// bar.Setup(b => b.Redo()); /// /// // exercise the mocks here /// /// factory.VerifyAll(); /// // At this point all setups are already checked /// // and an optional MockException might be thrown. /// // Note also that because the mocks are strict, any invocation /// // that doesn't have a matching setup will also throw a MockException. /// </code> /// The following examples shows how to setup the factory /// to create loose mocks and later verify only verifiable setups: /// <code> /// var factory = new MockFactory(MockBehavior.Loose); /// /// var foo = factory.Create&lt;IFoo&gt;(); /// var bar = factory.Create&lt;IBar&gt;(); /// /// // this setup will be verified when we verify the factory /// foo.Setup(f => f.Do()).Verifiable(); /// /// // this setup will NOT be verified /// foo.Setup(f => f.Calculate()); /// /// // this setup will be verified when we verify the factory /// bar.Setup(b => b.Redo()).Verifiable(); /// /// // exercise the mocks here /// // note that because the mocks are Loose, members /// // called in the interfaces for which no matching /// // setups exist will NOT throw exceptions, /// // and will rather return default values. /// /// factory.Verify(); /// // At this point verifiable setups are already checked /// // and an optional MockException might be thrown. /// </code> /// The following examples shows how to setup the factory with a /// default strict behavior, overriding that default for a /// specific mock: /// <code> /// var factory = new MockFactory(MockBehavior.Strict); /// /// // this particular one we want loose /// var foo = factory.Create&lt;IFoo&gt;(MockBehavior.Loose); /// var bar = factory.Create&lt;IBar&gt;(); /// /// // specify setups /// /// // exercise the mocks here /// /// factory.Verify(); /// </code> /// </example> /// <seealso cref="MockBehavior"/> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This class has been renamed to MockRepository. MockFactory will be retired in v5.", false)] public partial class MockFactory { List<Mock> mocks = new List<Mock>(); MockBehavior defaultBehavior; DefaultValueProvider defaultValueProvider; private Switches switches; /// <summary> /// Initializes the factory with the given <paramref name="defaultBehavior"/> /// for newly created mocks from the factory. /// </summary> /// <param name="defaultBehavior">The behavior to use for mocks created /// using the <see cref="Create{T}()"/> factory method if not overridden /// by using the <see cref="Create{T}(MockBehavior)"/> overload.</param> public MockFactory(MockBehavior defaultBehavior) { this.defaultBehavior = defaultBehavior; this.defaultValueProvider = DefaultValueProvider.Empty; this.switches = Switches.Default; } /// <summary> /// Gets the default <see cref="MockBehavior"/> of mocks created by this repository. /// </summary> internal MockBehavior Behavior => this.defaultBehavior; /// <summary> /// Whether the base member virtual implementation will be called /// for mocked classes if no setup is matched. Defaults to <see langword="false"/>. /// </summary> public bool CallBase { get; set; } /// <summary> /// Specifies the behavior to use when returning default values for /// unexpected invocations on loose mocks. /// </summary> public DefaultValue DefaultValue { get { return this.DefaultValueProvider.Kind; } set { this.DefaultValueProvider = value switch { DefaultValue.Empty => DefaultValueProvider.Empty, DefaultValue.Mock => DefaultValueProvider.Mock, _ => throw new ArgumentOutOfRangeException(nameof(value)), }; } } /// <summary> /// Gets or sets the <see cref="Moq.DefaultValueProvider"/> instance that will be used /// e. g. to produce default return values for unexpected invocations. /// </summary> public DefaultValueProvider DefaultValueProvider { get => this.defaultValueProvider; set => this.defaultValueProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// Gets the mocks that have been created by this factory and /// that will get verified together. /// </summary> protected internal IEnumerable<Mock> Mocks { get { return mocks; } } /// <summary> /// A set of switches that influence how mocks created by this factory will operate. /// You can opt in or out of certain features via this property. /// </summary> public Switches Switches { get => this.switches; set => this.switches = value; } /// <summary> /// Creates a new mock with the default <see cref="MockBehavior"/> /// specified at factory construction time. /// </summary> /// <typeparam name="T">Type to mock.</typeparam> /// <returns>A new <see cref="Mock{T}"/>.</returns> /// <example ignore="true"> /// <code> /// var factory = new MockFactory(MockBehavior.Strict); /// /// var foo = factory.Create&lt;IFoo&gt;(); /// // use mock on tests /// /// factory.VerifyAll(); /// </code> /// </example> public Mock<T> Create<T>() where T : class { return CreateMock<T>(defaultBehavior, new object[0]); } /// <summary> /// Creates a new mock with the default <see cref="MockBehavior"/> /// specified at factory construction time and with the /// the given constructor arguments for the class. /// </summary> /// <remarks> /// The mock will try to find the best match constructor given the /// constructor arguments, and invoke that to initialize the instance. /// This applies only to classes, not interfaces. /// </remarks> /// <typeparam name="T">Type to mock.</typeparam> /// <param name="args">Constructor arguments for mocked classes.</param> /// <returns>A new <see cref="Mock{T}"/>.</returns> /// <example ignore="true"> /// <code> /// var factory = new MockFactory(MockBehavior.Default); /// /// var mock = factory.Create&lt;MyBase&gt;("Foo", 25, true); /// // use mock on tests /// /// factory.Verify(); /// </code> /// </example> public Mock<T> Create<T>(params object[] args) where T : class { // "fix" compiler picking this overload instead of // the one receiving the mock behavior. if (args != null && args.Length > 0 && args[0] is MockBehavior) { return CreateMock<T>((MockBehavior)args[0], args.Skip(1).ToArray()); } return CreateMock<T>(defaultBehavior, args); } /// <summary> /// Creates a new mock with the given <paramref name="behavior"/>. /// </summary> /// <typeparam name="T">Type to mock.</typeparam> /// <param name="behavior">Behavior to use for the mock, which overrides /// the default behavior specified at factory construction time.</param> /// <returns>A new <see cref="Mock{T}"/>.</returns> /// <example group="factory"> /// The following example shows how to create a mock with a different /// behavior to that specified as the default for the factory: /// <code> /// var factory = new MockFactory(MockBehavior.Strict); /// /// var foo = factory.Create&lt;IFoo&gt;(MockBehavior.Loose); /// </code> /// </example> public Mock<T> Create<T>(MockBehavior behavior) where T : class { return CreateMock<T>(behavior, new object[0]); } /// <summary> /// Creates a new mock with the given <paramref name="behavior"/> /// and with the given constructor arguments for the class. /// </summary> /// <remarks> /// The mock will try to find the best match constructor given the /// constructor arguments, and invoke that to initialize the instance. /// This applies only to classes, not interfaces. /// </remarks> /// <typeparam name="T">Type to mock.</typeparam> /// <param name="behavior">Behavior to use for the mock, which overrides /// the default behavior specified at factory construction time.</param> /// <param name="args">Constructor arguments for mocked classes.</param> /// <returns>A new <see cref="Mock{T}"/>.</returns> /// <example group="factory"> /// The following example shows how to create a mock with a different /// behavior to that specified as the default for the factory, passing /// constructor arguments: /// <code> /// var factory = new MockFactory(MockBehavior.Default); /// /// var mock = factory.Create&lt;MyBase&gt;(MockBehavior.Strict, "Foo", 25, true); /// </code> /// </example> public Mock<T> Create<T>(MockBehavior behavior, params object[] args) where T : class { return CreateMock<T>(behavior, args); } /// <summary> /// Creates an instance of the mock using the given constructor call including its /// argument values and with a specific <see cref="MockBehavior"/> behavior. /// </summary> /// <typeparam name="T">Type to mock.</typeparam> /// <param name="newExpression">Lambda expression that creates an instance of <typeparamref name="T"/>.</param> /// <param name="behavior">Behavior of the mock.</param> /// <returns>A new <see cref="Mock{T}"/>.</returns> /// <example ignore="true"> /// <code> /// var factory = new MockFactory(MockBehavior.Default); /// /// var mock = factory.Create&lt;MyClass&gt;(() => new MyClass("Foo", 25, true), MockBehavior.Loose); /// // use mock on tests /// /// factory.Verify(); /// </code> /// </example> public Mock<T> Create<T>(Expression<Func<T>> newExpression, MockBehavior behavior = MockBehavior.Default) where T : class { return Create<T>(behavior, Expressions.Visitors.ConstructorCallVisitor.ExtractArgumentValues(newExpression)); } /// <summary> /// Implements creation of a new mock within the factory. /// </summary> /// <typeparam name="T">Type to mock.</typeparam> /// <param name="behavior">The behavior for the new mock.</param> /// <param name="args">Optional arguments for the construction of the mock.</param> protected virtual Mock<T> CreateMock<T>(MockBehavior behavior, object[] args) where T : class { var mock = new Mock<T>(behavior, args); mocks.Add(mock); mock.CallBase = this.CallBase; mock.DefaultValueProvider = this.DefaultValueProvider; mock.Switches = this.switches; return mock; } /// <summary> /// Verifies all verifiable setups on all mocks created by this factory. /// </summary> /// <seealso cref="Mock.Verify()"/> /// <exception cref="MockException">One or more mocks had setups that were not satisfied.</exception> public virtual void Verify() { VerifyMocks(verifiable => verifiable.Verify()); } /// <summary> /// Verifies all setups on all mocks created by this factory. /// </summary> /// <seealso cref="Mock.Verify()"/> /// <exception cref="MockException">One or more mocks had setups that were not satisfied.</exception> public virtual void VerifyAll() { VerifyMocks(verifiable => verifiable.VerifyAll()); } /// <summary> /// Calls <see cref="Mock{T}.VerifyNoOtherCalls()"/> on all mocks created by this factory. /// </summary> /// <seealso cref="Mock{T}.VerifyNoOtherCalls()"/> /// <exception cref="MockException">One or more mocks had invocations that were not verified.</exception> public void VerifyNoOtherCalls() { VerifyMocks(mock => Mock.VerifyNoOtherCalls(mock)); } /// <summary> /// Invokes <paramref name="verifyAction"/> for each mock /// in <see cref="Mocks"/>, and accumulates the resulting /// verification exceptions that might be /// thrown from the action. /// </summary> /// <param name="verifyAction">The action to execute against /// each mock.</param> protected virtual void VerifyMocks(Action<Mock> verifyAction) { Guard.NotNull(verifyAction, nameof(verifyAction)); var errors = new List<MockException>(); foreach (var mock in mocks) { try { verifyAction(mock); } catch (MockException error) when (error.IsVerificationError) { errors.Add(error); } } if (errors.Count > 0) { throw MockException.Combined(errors, preamble: Resources.VerificationErrorsOfMockRepository); } } } }
// 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.Http.Headers; using System.Text; namespace System.Net.Http { public class HttpResponseMessage : IDisposable { private const HttpStatusCode defaultStatusCode = HttpStatusCode.OK; private HttpStatusCode _statusCode; private HttpResponseHeaders _headers; private string _reasonPhrase; private HttpRequestMessage _requestMessage; private Version _version; private HttpContent _content; private bool _disposed; public Version Version { get { return _version; } set { #if !PHONE if (value == null) { throw new ArgumentNullException(nameof(value)); } #endif CheckDisposed(); _version = value; } } public HttpContent Content { get { return _content; } set { CheckDisposed(); if (NetEventSource.IsEnabled) { if (value == null) { NetEventSource.ContentNull(this); } else { NetEventSource.Associate(this, value); } } _content = value; } } public HttpStatusCode StatusCode { get { return _statusCode; } set { if (((int)value < 0) || ((int)value > 999)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposed(); _statusCode = value; } } public string ReasonPhrase { get { if (_reasonPhrase != null) { return _reasonPhrase; } // Provide a default if one was not set. return HttpStatusDescription.Get(StatusCode); } set { if ((value != null) && ContainsNewLineCharacter(value)) { throw new FormatException(SR.net_http_reasonphrase_format_error); } CheckDisposed(); _reasonPhrase = value; // It's OK to have a 'null' reason phrase. } } public HttpResponseHeaders Headers { get { if (_headers == null) { _headers = new HttpResponseHeaders(); } return _headers; } } public HttpRequestMessage RequestMessage { get { return _requestMessage; } set { CheckDisposed(); if (value != null) NetEventSource.Associate(this, value); _requestMessage = value; } } public bool IsSuccessStatusCode { get { return ((int)_statusCode >= 200) && ((int)_statusCode <= 299); } } public HttpResponseMessage() : this(defaultStatusCode) { } public HttpResponseMessage(HttpStatusCode statusCode) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, statusCode); if (((int)statusCode < 0) || ((int)statusCode > 999)) { throw new ArgumentOutOfRangeException(nameof(statusCode)); } _statusCode = statusCode; _version = HttpUtilities.DefaultResponseVersion; if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } public HttpResponseMessage EnsureSuccessStatusCode() { if (!IsSuccessStatusCode) { // Disposing the content should help users: If users call EnsureSuccessStatusCode(), an exception is // thrown if the response status code is != 2xx. I.e. the behavior is similar to a failed request (e.g. // connection failure). Users don't expect to dispose the content in this case: If an exception is // thrown, the object is responsible fore cleaning up its state. if (_content != null) { _content.Dispose(); } throw new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_message_not_success_statuscode, (int)_statusCode, ReasonPhrase)); } return this; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("StatusCode: "); sb.Append((int)_statusCode); sb.Append(", ReasonPhrase: '"); sb.Append(ReasonPhrase ?? "<null>"); sb.Append("', Version: "); sb.Append(_version); sb.Append(", Content: "); sb.Append(_content == null ? "<null>" : _content.GetType().ToString()); sb.Append(", Headers:\r\n"); sb.Append(HeaderUtilities.DumpHeaders(_headers, _content == null ? null : _content.Headers)); return sb.ToString(); } private bool ContainsNewLineCharacter(string value) { foreach (char character in value) { if ((character == HttpRuleParser.CR) || (character == HttpRuleParser.LF)) { return true; } } return false; } #region IDisposable Members protected virtual void Dispose(bool disposing) { // The reason for this type to implement IDisposable is that it contains instances of types that implement // IDisposable (content). if (disposing && !_disposed) { _disposed = true; if (_content != null) { _content.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().ToString()); } } } }
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.MobileServices.Eventing; using Microsoft.WindowsAzure.MobileServices.Query; using Microsoft.WindowsAzure.MobileServices.Threading; using Newtonsoft.Json.Linq; namespace Microsoft.WindowsAzure.MobileServices.Sync { internal class MobileServiceSyncContext : IMobileServiceSyncContext, IDisposable { private MobileServiceSyncSettingsManager settings; private TaskCompletionSource<object> initializeTask; private MobileServiceClient client; /// <summary> /// Lock to ensure that multiple insert,update,delete operations don't interleave as they are added to queue and storage /// </summary> private AsyncReaderWriterLock storeQueueLock = new AsyncReaderWriterLock(); /// <summary> /// Variable for Store property. Not meant to be accessed directly. /// </summary> private IMobileServiceLocalStore _store; /// <summary> /// Queue for executing sync calls (push,pull) one after the other /// </summary> private ActionBlock syncQueue; /// <summary> /// Queue for pending operations (insert,delete,update) against remote table /// </summary> private OperationQueue opQueue; private StoreTrackingOptions storeTrackingOptions; private IMobileServiceLocalStore localOperationsStore; public IMobileServiceSyncHandler Handler { get; private set; } public IMobileServiceLocalStore Store { get { return this._store; } private set { IMobileServiceLocalStore oldStore = this._store; this._store = value; if (oldStore != null) { oldStore.Dispose(); } } } public bool IsInitialized { get { return this.initializeTask != null && this.initializeTask.Task.Status == TaskStatus.RanToCompletion; } } public MobileServiceSyncContext(MobileServiceClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.client = client; } public long PendingOperations { get { if (!this.IsInitialized) { return 0; } return this.opQueue.PendingOperations; } } public StoreTrackingOptions StoreTrackingOptions { get { return this.storeTrackingOptions; } } public Task InitializeAsync(IMobileServiceLocalStore store, IMobileServiceSyncHandler handler) { return InitializeAsync(store, handler, StoreTrackingOptions.None); } public async Task InitializeAsync(IMobileServiceLocalStore store, IMobileServiceSyncHandler handler, StoreTrackingOptions trackingOptions) { if (store == null) { throw new ArgumentNullException("store"); } handler = handler ?? new MobileServiceSyncHandler(); this.initializeTask = new TaskCompletionSource<object>(); using (await this.storeQueueLock.WriterLockAsync()) { this.Handler = handler; this.Store = store; this.storeTrackingOptions = trackingOptions; this.syncQueue = new ActionBlock(); await this.Store.InitializeAsync(); this.opQueue = await OperationQueue.LoadAsync(store); this.settings = new MobileServiceSyncSettingsManager(store); this.localOperationsStore = StoreChangeTrackerFactory.CreateTrackedStore(store, StoreOperationSource.Local, trackingOptions, this.client.EventManager, this.settings); this.initializeTask.SetResult(null); } } public async Task<JToken> ReadAsync(string tableName, string query) { await this.EnsureInitializedAsync(); var queryDescription = MobileServiceTableQueryDescription.Parse(tableName, query); using (await this.storeQueueLock.ReaderLockAsync()) { return await this.Store.ReadAsync(queryDescription); } } public async Task InsertAsync(string tableName, MobileServiceTableKind tableKind, string id, JObject item) { var operation = new InsertOperation(tableName, tableKind, id) { Table = await this.GetTable(tableName) }; await this.ExecuteOperationAsync(operation, item); } public async Task UpdateAsync(string tableName, MobileServiceTableKind tableKind, string id, JObject item) { var operation = new UpdateOperation(tableName, tableKind, id) { Table = await this.GetTable(tableName) }; await this.ExecuteOperationAsync(operation, item); } public async Task DeleteAsync(string tableName, MobileServiceTableKind tableKind, string id, JObject item) { var operation = new DeleteOperation(tableName, tableKind, id) { Table = await this.GetTable(tableName), Item = item // item will be deleted from store, so we need to put it in the operation queue }; await this.ExecuteOperationAsync(operation, item); } public async Task<JObject> LookupAsync(string tableName, string id) { await this.EnsureInitializedAsync(); return await this.Store.LookupAsync(tableName, id); } /// <summary> /// Pulls all items that match the given query from the associated remote table. /// </summary> /// <param name="tableName">The name of table to pull</param> /// <param name="tableKind">The kind of table</param> /// <param name="queryId">A string that uniquely identifies this query and is used to keep track of its sync state.</param> /// <param name="query">An OData query that determines which items to /// pull from the remote table.</param> /// <param name="options">An instance of <see cref="MobileServiceRemoteTableOptions"/></param> /// <param name="parameters">A dictionary of user-defined parameters and values to include in /// the request URI query string.</param> /// <param name="relatedTables"> /// List of tables that may have related records that need to be push before this table is pulled down. /// When no table is specified, all tables are considered related. /// </param> /// <param name="reader">An instance of <see cref="MobileServiceObjectReader"/></param> /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> token to observe /// </param> /// <param name="pullOptions"> /// PullOptions that determine how to pull data from the remote table /// </param> /// <returns> /// A task that completes when pull operation has finished. /// </returns> public async Task PullAsync(string tableName, MobileServiceTableKind tableKind, string queryId, string query, MobileServiceRemoteTableOptions options, IDictionary<string, string> parameters, IEnumerable<string> relatedTables, MobileServiceObjectReader reader, CancellationToken cancellationToken, PullOptions pullOptions) { await this.EnsureInitializedAsync(); if (parameters != null) { if (parameters.Keys.Any(k => k.Equals(MobileServiceTable.IncludeDeletedParameterName, StringComparison.OrdinalIgnoreCase))) { throw new ArgumentException("The key '{0}' is reserved and cannot be specified as a query parameter.".FormatInvariant(MobileServiceTable.IncludeDeletedParameterName)); } } var table = await this.GetTable(tableName); var queryDescription = MobileServiceTableQueryDescription.Parse(this.client.MobileAppUri, tableName, query); // local schema should be same as remote schema otherwise push can't function if (queryDescription.Selection.Any() || queryDescription.Projections.Any()) { throw new ArgumentException("Pull query with select clause is not supported.", "query"); } bool isIncrementalSync = !String.IsNullOrEmpty(queryId); if (isIncrementalSync) { if (queryDescription.Ordering.Any()) { throw new ArgumentException("Incremental pull query must not have orderby clause.", "query"); } if (queryDescription.Top.HasValue || queryDescription.Skip.HasValue) { throw new ArgumentException("Incremental pull query must not have skip or top specified.", "query"); } } if (!options.HasFlag(MobileServiceRemoteTableOptions.OrderBy) && queryDescription.Ordering.Any()) { throw new ArgumentException("The supported table options does not include orderby.", "query"); } if (!options.HasFlag(MobileServiceRemoteTableOptions.Skip) && queryDescription.Skip.HasValue) { throw new ArgumentException("The supported table options does not include skip.", "query"); } if (!options.HasFlag(MobileServiceRemoteTableOptions.Top) && queryDescription.Top.HasValue) { throw new ArgumentException("The supported table options does not include top.", "query"); } // let us not burden the server to calculate the count when we don't need it for pull queryDescription.IncludeTotalCount = false; using (var store = StoreChangeTrackerFactory.CreateTrackedStore(this.Store, StoreOperationSource.ServerPull, this.storeTrackingOptions, this.client.EventManager, this.settings)) { var action = new PullAction(table, tableKind, this, queryId, queryDescription, parameters, relatedTables, this.opQueue, this.settings, store, options, pullOptions, reader, cancellationToken); await this.ExecuteSyncAction(action); } } public async Task PurgeAsync(string tableName, MobileServiceTableKind tableKind, string queryId, string query, bool force, CancellationToken cancellationToken) { await this.EnsureInitializedAsync(); var table = await this.GetTable(tableName); var queryDescription = MobileServiceTableQueryDescription.Parse(tableName, query); using (var trackedStore = StoreChangeTrackerFactory.CreateTrackedStore(this.Store, StoreOperationSource.LocalPurge, this.storeTrackingOptions, this.client.EventManager, this.settings)) { var action = new PurgeAction(table, tableKind, queryId, queryDescription, force, this, this.opQueue, this.client.EventManager, this.settings, this.Store, cancellationToken); await this.ExecuteSyncAction(action); } } public Task PushAsync(CancellationToken cancellationToken) { return PushAsync(cancellationToken, MobileServiceTableKind.Table, new string[0]); } public async Task PushAsync(CancellationToken cancellationToken, MobileServiceTableKind tableKind, params string[] tableNames) { await this.EnsureInitializedAsync(); // use empty handler if its not a standard table push var handler = tableKind == MobileServiceTableKind.Table ? this.Handler : new MobileServiceSyncHandler(); using (var trackedStore = StoreChangeTrackerFactory.CreateTrackedStore(this.Store, StoreOperationSource.ServerPush, this.storeTrackingOptions, this.client.EventManager, this.settings)) { var action = new PushAction(this.opQueue, trackedStore, tableKind, tableNames, handler, this.client, this, cancellationToken); await this.ExecuteSyncAction(action); } } public async Task ExecuteSyncAction(SyncAction action) { Task discard = this.syncQueue.Post(action.ExecuteAsync, action.CancellationToken); await action.CompletionTask; } public virtual async Task<MobileServiceTable> GetTable(string tableName) { await this.EnsureInitializedAsync(); var table = this.client.GetTable(tableName) as MobileServiceTable; table.Features = MobileServiceFeatures.Offline; return table; } public Task CancelAndUpdateItemAsync(MobileServiceTableOperationError error, JObject item) { string itemId = error.Item.Value<string>(MobileServiceSystemColumns.Id); return this.ExecuteOperationSafeAsync(itemId, error.TableName, async () => { await this.TryCancelOperation(error); using (var trackedStore = StoreChangeTrackerFactory.CreateTrackedStore(this.Store, StoreOperationSource.LocalConflictResolution, this.storeTrackingOptions, this.client.EventManager, this.settings)) { await trackedStore.UpsertAsync(error.TableName, item, fromServer: true); } }); } public Task UpdateOperationAsync(MobileServiceTableOperationError error, JObject item) { string itemId = error.Item.Value<string>(MobileServiceSystemColumns.Id); return this.ExecuteOperationSafeAsync(itemId, error.TableName, async () => { await this.TryUpdateOperation(error, item); if (error.OperationKind != MobileServiceTableOperationKind.Delete) { using (var trackedStore = StoreChangeTrackerFactory.CreateTrackedStore(this.Store, StoreOperationSource.LocalConflictResolution, this.storeTrackingOptions, this.client.EventManager, this.settings)) { await trackedStore.UpsertAsync(error.TableName, item, fromServer: true); } } }); } private async Task TryUpdateOperation(MobileServiceTableOperationError error, JObject item) { if (!await this.opQueue.UpdateAsync(error.Id, error.OperationVersion, item)) { throw new InvalidOperationException("The operation has been updated and cannot be updated again"); } // delete errors for updated operation await this.Store.DeleteAsync(MobileServiceLocalSystemTables.SyncErrors, error.Id); } public Task CancelAndDiscardItemAsync(MobileServiceTableOperationError error) { string itemId = error.Item.Value<string>(MobileServiceSystemColumns.Id); return this.ExecuteOperationSafeAsync(itemId, error.TableName, async () => { await this.TryCancelOperation(error); using (var trackedStore = StoreChangeTrackerFactory.CreateTrackedStore(this.Store, StoreOperationSource.LocalConflictResolution, this.storeTrackingOptions, this.client.EventManager, this.settings)) { await trackedStore.DeleteAsync(error.TableName, itemId); } }); } public async Task DeferTableActionAsync(TableAction action) { IEnumerable<string> tableNames; if (action.RelatedTables == null) // no related table { tableNames = new[] { action.Table.TableName }; } else if (action.RelatedTables.Any()) // some related tables { tableNames = new[] { action.Table.TableName }.Concat(action.RelatedTables); } else // all tables are related { tableNames = Enumerable.Empty<string>(); } try { await this.PushAsync(action.CancellationToken, action.TableKind, tableNames.ToArray()); } finally { Task discard = this.syncQueue.Post(action.ExecuteAsync, action.CancellationToken); } } private async Task TryCancelOperation(MobileServiceTableOperationError error) { if (!await this.opQueue.DeleteAsync(error.Id, error.OperationVersion)) { throw new InvalidOperationException("The operation has been updated and cannot be cancelled."); } // delete errors for cancelled operation await this.Store.DeleteAsync(MobileServiceLocalSystemTables.SyncErrors, error.Id); } private async Task EnsureInitializedAsync() { if (this.initializeTask == null) { throw new InvalidOperationException("SyncContext is not yet initialized."); } else { // when the initialization has started we wait for it to complete await this.initializeTask.Task; } } private Task ExecuteOperationAsync(MobileServiceTableOperation operation, JObject item) { return this.ExecuteOperationSafeAsync(operation.ItemId, operation.TableName, async () => { MobileServiceTableOperation existing = await this.opQueue.GetOperationByItemIdAsync(operation.TableName, operation.ItemId); if (existing != null) { existing.Validate(operation); // make sure this operation is legal and collapses after any previous operation on same item already in the queue } try { await operation.ExecuteLocalAsync(this.localOperationsStore, item); // first execute operation on local store } catch (Exception ex) { if (ex is MobileServiceLocalStoreException) { throw; } throw new MobileServiceLocalStoreException("Failed to perform operation on local store.", ex); } if (existing != null) { existing.Collapse(operation); // cancel either existing, new or both operation // delete error for collapsed operation await this.Store.DeleteAsync(MobileServiceLocalSystemTables.SyncErrors, existing.Id); if (existing.IsCancelled) // if cancelled we delete it { await this.opQueue.DeleteAsync(existing.Id, existing.Version); } else if (existing.IsUpdated) { await this.opQueue.UpdateAsync(existing); } } // if validate didn't cancel the operation then queue it if (!operation.IsCancelled) { await this.opQueue.EnqueueAsync(operation); } }); } private async Task ExecuteOperationSafeAsync(string itemId, string tableName, Func<Task> action) { await this.EnsureInitializedAsync(); // take slowest lock first and quickest last in order to avoid blocking quick operations for long time using (await this.opQueue.LockItemAsync(itemId, CancellationToken.None)) // prevent any inflight operation on the same item using (await this.opQueue.LockTableAsync(tableName, CancellationToken.None)) // prevent interferance with any in-progress pull/purge action using (await this.storeQueueLock.WriterLockAsync()) // prevent any other operation from interleaving between store and queue insert { await action(); } } public void Dispose() { this.Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing && this._store != null) { this.settings.Dispose(); this._store.Dispose(); } } } }
using System.Threading.Tasks; using Microsoft.Extensions.Logging; using RapidCore.Network; using Skarp.HubSpotClient.Core.Requests; using Xunit; using Xunit.Abstractions; using Skarp.HubSpotClient.FunctionalTests.Mocks.LineItem; using Skarp.HubSpotClient.LineItem; using Skarp.HubSpotClient.LineItem.Dto; using Skarp.HubSpotClient.LineItem.Interfaces; using System.Linq; namespace Skarp.HubSpotClient.FunctionalTests.LineItem { public class HubSpotLineItemClientFunctionalTest : FunctionalTestBase<HubSpotLineItemClient> { private readonly HubSpotLineItemClient _client; public HubSpotLineItemClientFunctionalTest(ITestOutputHelper output) : base(output) { var mockHttpClient = new MockRapidHttpClient() .AddTestCase(new CreateLineItemMockTestCase()) .AddTestCase(new CreateBatchLineItemMockTestCase()) .AddTestCase(new GetLineItemMockTestCase()) .AddTestCase(new GetLineItemNotFoundMockTestCase()) .AddTestCase(new ListLineItemMockTestCase()) .AddTestCase(new UpdateLineItemMockTestCase()) .AddTestCase(new UpdateBatchLineItemMockTestCase()) .AddTestCase(new DeleteLineItemMockTestCase()) .AddTestCase(new DeleteBatchLineItemMockTestCase()) .AddTestCase(new ReadBatchLineItemMockTestCase()); _client = new HubSpotLineItemClient( mockHttpClient, Logger, new RequestSerializer(new RequestDataConverter(LoggerFactory.CreateLogger<RequestDataConverter>())), "https://api.hubapi.com/", "HapiKeyFisk" ); } [Fact] public async Task LineItemClient_can_create_LineItems() { var data = await _client.CreateAsync<LineItemHubSpotEntity>(new LineItemHubSpotEntity { Name = "A new line item", Price = 12.50M, ProductId = "12345", Quantity = 10, }); Assert.NotNull(data); // Should have replied with mocked data, so it does not really correspond to our input data, but it proves the "flow" Assert.Equal(9867220, data.Id); } [Fact] public async Task LineItemClient_batch_create_LineItem_works() { var data = await _client.CreateBatchAsync<LineItemHubSpotEntity>(new[] { new LineItemHubSpotEntity { Name = "This is a new LineItem", Quantity = 666, Price = 9.99M, ProductId = "12345" }, new LineItemHubSpotEntity { Name = "This is another new LineItem", Quantity = 999, Price = 12.45M, ProductId = "67890" } }); Assert.Equal(2, data.Count()); foreach (var item in data) { Assert.NotEqual(0, item.Id); Assert.NotEqual(0, item.Price); Assert.NotEqual(0, item.Quantity); Assert.NotNull(item.Name); Assert.NotNull(item.ProductId); } } [Fact] public async Task LineItemClient_can_get_LineItem() { const int lineItemId = 9867220; var options = new LineItemGetRequestOptions { IncludeDeletes = true }; options.PropertiesToInclude.Add("my_custom_property"); var data = await _client.GetByIdAsync<LineItemHubSpotEntity>(lineItemId, options); Assert.NotNull(data); Assert.Equal("This is a LineItem", data.Name); Assert.Equal(9.50M, data.Price); Assert.Equal(50, data.Quantity); Assert.Equal(lineItemId, data.Id); } [Fact] public async Task LineItemClient_can_list_LineItem() { var options = new LineItemListRequestOptions { Offset = 9867220 }; options.PropertiesToInclude.Add("my_custom_property"); var data = await _client.ListAsync<LineItemListHubSpotEntity<LineItemHubSpotEntity>>(options); Assert.NotNull(data); Assert.Equal(9867220, data.ContinuationOffset); Assert.True(data.MoreResultsAvailable); Assert.Equal(2, data.LineItems.Count()); foreach (var item in data.LineItems) { Assert.NotNull(item.ProductId); // sample response only has product Id's } } [Fact] public async Task LineItemClient_returns_null_when_LineItem_not_found() { const int lineItemId = 158; var data = await _client.GetByIdAsync<LineItemHubSpotEntity>(lineItemId); Assert.Null(data); } [Fact] public async Task LineItemClient_update_LineItem_works() { var data = await _client.UpdateAsync<LineItemHubSpotEntity>(new LineItemHubSpotEntity { Id = 9867220, Name = "This is an updated LineItem", Quantity = 666, Price = 9.99M, ProductId = "12345" }); Assert.NotNull(data); // Should have replied with mocked data, so it does not really correspond to our input data, but it proves the "flow" Assert.NotNull(data); Assert.Equal("This is a LineItem", data.Name); Assert.Equal(9.50M, data.Price); Assert.Equal(50, data.Quantity); Assert.Equal(9867220, data.Id); } [Fact] public async Task LineItemClient_delete_LineItem_works() { await _client.DeleteAsync(9867220); } [Fact] public async Task LineItemClient_batch_delete_LineItem_works() { var request = new ListOfLineItemIds(); request.Ids.Add(9867220); request.Ids.Add(9867221); await _client.DeleteBatchAsync(request); } [Fact] public async Task LineItemClient_batch_read_LineItem_works() { var request = new ListOfLineItemIds(); request.Ids.Add(9867220); request.Ids.Add(9867221); var response = await _client.ReadBatchAsync<LineItemHubSpotEntity>(request); Assert.Equal(2, response.Count()); Assert.Equal("1645342", response[9845651].ProductId); } [Fact] public async Task LineItemClient_batch_update_LineItem_works() { var data = await _client.UpdateBatchAsync<LineItemHubSpotEntity>(new[] { new LineItemHubSpotEntity { Id = 9867220, Name = "This is an updated LineItem", Quantity = 666, Price = 9.99M, ProductId = "12345" }, new LineItemHubSpotEntity { Id = 9867221, Name = "This is another updated LineItem", Quantity = 999, Price = 12.45M, ProductId = "67890" } }); Assert.Equal(2, data.Count()); foreach (var item in data) { Assert.NotEqual(0, item.Id); Assert.NotEqual(0, item.Price); Assert.NotEqual(0, item.Quantity); Assert.NotNull(item.Name); Assert.NotNull(item.ProductId); } } } }
/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ /* * Description: * What is this file about? * * Revision history: * Feb., 2016, @imzhenyu (Zhenyu Guo), done in Tron project and copied here * xxxx-xx-xx, author, fix bug about xxx */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; namespace rDSN.Tron.Utility { public static class TypeHelper { public static bool IsEnumerable(this Type type) { return type.GetInterface("IEnumerable") != null; } public static bool IsSymbols(this Type type) { return type.Name == "ISymbolCollection`1"; } public static bool IsSymbol(this Type type) { return type.Name == "ISymbol`1"; } public static bool IsAnonymous(this Type type) { return type.Name.StartsWith("<>f__AnonymousType"); } public static bool IsSimpleType(this Type type) { return type.IsPrimitive || type == typeof(Guid) || type == typeof(DateTime) || type == typeof(TimeSpan) || type == typeof(string) ; } public static string GetCompilableTypeName(this string typeName) { return typeName.Replace("::", "."); } private static void EchoLine(int indent, string line) { for (var i = 0; i < indent; i++) Console.Write(" "); Console.WriteLine(line); } public static void Echo(this object o, string name, int indent = 0, int maxdepth = int.MaxValue) { if (indent > maxdepth) return; if (o == null) { EchoLine(indent, name + " = [(null)]"); } else { var type = o.GetType(); EchoLine(indent, type.FullName + " " + name + " = ["); foreach (var m in type.GetFields()) { if (m.FieldType.IsSimpleType()) { EchoLine(indent + 1, "(field)" + m.Name + " = " + m.GetValue(o)); } else { m.GetValue(o).Echo(m.Name, indent + 1, maxdepth); } } foreach (var p in type.GetProperties()) { if (p.PropertyType.IsSimpleType()) { try { EchoLine(indent + 1, "(prop)" + p.Name + " = " + p.GetValue(o, new object[] { })); } catch (Exception) { EchoLine(indent + 1, "(prop)" + p.Name + " = ..."); } } else { p.GetValue(o, new object[] { }).Echo(p.Name, indent + 1, maxdepth); } } EchoLine(indent, "]"); } } public static bool IsInheritedTypeOf(this Type type, Type baseType) { while (type != null) { if (type == baseType || (baseType.IsGenericTypeDefinition && type.Name == baseType.Name) ) return true; type = type.BaseType; } return false; } public static FieldInfo GetFieldEx(this Type type, string name, BindingFlags flags) { do { var fld = type.GetField(name, flags); if (fld != null) return fld; type = type.BaseType; } while (type != null); return null; } public static PropertyInfo GetPropertyEx(this Type type, string name, BindingFlags flags) { do { var prop = type.GetProperty(name, flags); if (prop != null) return prop; type = type.BaseType; } while (type != null); return null; } public static object GetMemberValue(this object o, MemberInfo member) { if (member.MemberType == MemberTypes.Field) { var fld = member.DeclaringType.GetFieldEx(member.Name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); Trace.Assert(fld != null); if (o != null) { return fld.GetValue(o); } return fld.IsStatic ? fld.GetValue(null) : null; } if (member.MemberType != MemberTypes.Property) throw new Exception("member type '" + member.MemberType + "' for '" + member.Name + "' is not supported yet"); var prop = member.DeclaringType.GetPropertyEx(member.Name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); Trace.Assert(prop != null); return prop.GetValue(o, new object[] { }); } public static Type GetElementType(Type seqType) { if (seqType.IsEnumerable()) { var ienum = FindIEnumerable(seqType); return ienum == null ? seqType : ienum.GetGenericArguments()[0]; } if (seqType.IsSymbols()) { return seqType.GetGenericArguments()[0]; } return seqType.IsSymbol() ? seqType.GetGenericArguments()[0] : seqType; } private static Type FindIEnumerable(Type seqType) { while (true) { if (seqType == null || seqType == typeof (string)) return null; if (seqType.IsArray) return typeof (IEnumerable<>).MakeGenericType(seqType.GetElementType()); if (seqType.IsGenericType) { var type = seqType; foreach (var ienum in seqType.GetGenericArguments().Select(arg => typeof (IEnumerable<>).MakeGenericType(arg)).Where(ienum => ienum.IsAssignableFrom(type))) { return ienum; } } var ifaces = seqType.GetInterfaces(); if (ifaces.Length > 0) { foreach (var ienum in ifaces.Select(FindIEnumerable).Where(ienum => ienum != null)) { return ienum; } } if (seqType.BaseType == null || seqType.BaseType == typeof (object)) return null; seqType = seqType.BaseType; } } } }
using NUnit.Framework; using RefactoringEssentials.CSharp.Diagnostics; namespace RefactoringEssentials.Tests.CSharp.Diagnostics { [TestFixture] [Ignore("TODO: Issue not ported yet.")] public class FunctionNeverReturnsTests : CSharpDiagnosticTestBase { [Test] public void TestEnd() { var input = @" class TestClass { void TestMethod () { int i = 1; } }"; Test<FunctionNeverReturnsAnalyzer>(input, 0); } [Test] public void TestReturn() { var input = @" class TestClass { void TestMethod () { return; } }"; Test<FunctionNeverReturnsAnalyzer>(input, 0); } [Test] public void TestThrow() { var input = @" class TestClass { void TestMethod () { throw new System.NotImplementedException(); } }"; Test<FunctionNeverReturnsAnalyzer>(input, 0); } [Test] public void TestNeverReturns() { var input = @" class TestClass { void TestMethod () { while (true) ; } }"; Test<FunctionNeverReturnsAnalyzer>(input, 1); } [Test] public void TestIfWithoutElse() { var input = @" class TestClass { string TestMethod (int x) { if (x <= 0) return ""Hi""; return ""_"" + TestMethod(x - 1); } }"; Analyze<FunctionNeverReturnsAnalyzer>(input); } [Test] public void TestRecursive() { var input = @" class TestClass { void TestMethod () { TestMethod (); } }"; Test<FunctionNeverReturnsAnalyzer>(input, 1); } [Test] public void TestNonRecursive() { var input = @" class TestClass { void TestMethod () { TestMethod (0); } void TestMethod (int i) { } }"; Test<FunctionNeverReturnsAnalyzer>(input, 0); } [Test] public void TestVirtualNonRecursive() { var input = @" class Base { public Base parent; public virtual string Result { get { return parent.Result; } } }"; Test<FunctionNeverReturnsAnalyzer>(input, 0); } [Test] public void TestNonRecursiveProperty() { var input = @" class TestClass { int foo; int Foo { get { return foo; } set { if (Foo != value) foo = value; } } }"; Test<FunctionNeverReturnsAnalyzer>(input, 0); } [Test] public void TestGetterNeverReturns() { var input = @" class TestClass { int TestProperty { get { while (true) ; } } }"; Test<FunctionNeverReturnsAnalyzer>(input, 1); } [Test] public void TestRecursiveGetter() { var input = @" class TestClass { int TestProperty { get { return TestProperty; } } }"; Test<FunctionNeverReturnsAnalyzer>(input, 1); } [Test] public void TestRecursiveSetter() { var input = @" class TestClass { int TestProperty { set { TestProperty = value; } } }"; Test<FunctionNeverReturnsAnalyzer>(input, 1); } [Test] public void TestAutoProperty() { var input = @" class TestClass { int TestProperty { get; set; } }"; Analyze<FunctionNeverReturnsAnalyzer>(input); } [Test] public void TestMethodGroupNeverReturns() { var input = @" class TestClass { int TestMethod() { return TestMethod(); } int TestMethod(object o) { return TestMethod(); } }"; Test<FunctionNeverReturnsAnalyzer>(input, 1); } [Test] public void TestIncrementProperty() { var input = @" class TestClass { int TestProperty { get { return TestProperty++; } set { TestProperty++; } } }"; Test<FunctionNeverReturnsAnalyzer>(input, 2); } [Test] public void TestLambdaNeverReturns() { var input = @" class TestClass { void TestMethod() { System.Action action = () => { while (true) ; }; } }"; Test<FunctionNeverReturnsAnalyzer>(input, 1); } [Test] public void TestDelegateNeverReturns() { var input = @" class TestClass { void TestMethod() { System.Action action = delegate() { while (true) ; }; } }"; Test<FunctionNeverReturnsAnalyzer>(input, 1); } [Test] public void YieldBreak() { var input = @" class TestClass { System.Collections.Generic.IEnumerable<string> TestMethod () { yield break; } }"; Test<FunctionNeverReturnsAnalyzer>(input, 0); } [Test] public void TestDisable() { var input = @" class TestClass { // ReSharper disable once FunctionNeverReturns void TestMethod () { while (true) ; } }"; Analyze<FunctionNeverReturnsAnalyzer>(input); } [Test] public void TestBug254() { //https://github.com/icsharpcode/NRefactory/issues/254 var input = @" class TestClass { int state = 0; bool Foo() { return state < 10; } void TestMethod() { if (Foo()) { ++state; TestMethod (); } } }"; Analyze<FunctionNeverReturnsAnalyzer>(input); } [Test] public void TestSwitch() { //https://github.com/icsharpcode/NRefactory/issues/254 var input = @" class TestClass { int foo; void TestMethod() { switch (foo) { case 0: TestMethod(); } } }"; Analyze<FunctionNeverReturnsAnalyzer>(input); } [Test] public void TestSwitchWithDefault() { //https://github.com/icsharpcode/NRefactory/issues/254 var input = @" class TestClass { int foo; void TestMethod() { switch (foo) { case 0: case 1: TestMethod(); default: TestMethod(); } } }"; Test<FunctionNeverReturnsAnalyzer>(input, 1); } [Test] public void TestSwitchValue() { //https://github.com/icsharpcode/NRefactory/issues/254 var input = @" class TestClass { int foo; int TestMethod() { switch (TestMethod()) { case 0: return 0; } return 1; } }"; Test<FunctionNeverReturnsAnalyzer>(input, 1); } [Test] public void TestLinqFrom() { //https://github.com/icsharpcode/NRefactory/issues/254 var input = @" using System.Linq; using System.Collections.Generic; class TestClass { IEnumerable<int> TestMethod() { return from y in TestMethod() select y; } }"; Test<FunctionNeverReturnsAnalyzer>(input, 1); } [Test] public void TestWrongLinqContexts() { //https://github.com/icsharpcode/NRefactory/issues/254 var input = @" using System.Linq; using System.Collections.Generic; class TestClass { IEnumerable<int> TestMethod() { return from y in Enumerable.Empty<int>() from z in TestMethod() select y; } }"; Analyze<FunctionNeverReturnsAnalyzer>(input); } [Test] public void TestForeach() { //https://bugzilla.xamarin.com/show_bug.cgi?id=14732 var input = @" using System.Linq; class TestClass { void TestMethod() { foreach (var x in new int[0]) TestMethod(); } }"; Analyze<FunctionNeverReturnsAnalyzer>(input); } [Test] public void TestNoExecutionFor() { var input = @" using System.Linq; class TestClass { void TestMethod() { for (int i = 0; i < 0; ++i) TestMethod (); } }"; Analyze<FunctionNeverReturnsAnalyzer>(input); } [Test] public void TestNullCoalescing() { //https://bugzilla.xamarin.com/show_bug.cgi?id=14732 var input = @" using System.Linq; class TestClass { TestClass parent; int? value; int TestMethod() { return value ?? parent.TestMethod(); } }"; Analyze<FunctionNeverReturnsAnalyzer>(input); } [Test] public void TestPropertyGetterInSetter() { Analyze<FunctionNeverReturnsAnalyzer>(@"using System; class TestClass { int a; int Foo { get { return 1; } set { a = Foo; } } }"); } [Test] public void TestRecursiveFunctionBug() { Analyze<FunctionNeverReturnsAnalyzer>(@"using System; class TestClass { bool Foo (int i) { return i < 0 || Foo (i - 1); } }"); } /// <summary> /// Bug 17769 - Incorrect "method never returns" warning /// </summary> [Test] public void TestBug17769() { Analyze<FunctionNeverReturnsAnalyzer>(@" using System.Linq; class A { A[] list = new A[0]; public bool Test () { return list.Any (t => t.Test ()); } } "); } } }
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Realms.Exceptions; using Realms.Schema; namespace Realms { /// <summary> /// A Realm instance (also referred to as a Realm) represents a Realm database. /// </summary> /// <remarks> /// <b>Warning</b>: Realm instances are not thread safe and can not be shared across threads. /// You must call <see cref="GetInstance(RealmConfigurationBase)"/> on each thread in which you want to interact with the Realm. /// </remarks> public class Realm : IDisposable { #region static [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1409:RemoveUnnecessaryCode")] static Realm() { // TODO decide if this can be removed or if that would make signatures different } /// <summary> /// Factory for obtaining a <see cref="Realm"/> instance for this thread. /// </summary> /// <param name="databasePath"> /// Path to the realm, must be a valid full path for the current platform, relative subdirectory, or just filename. /// </param> /// <remarks> /// If you specify a relative path, sandboxing by the OS may cause failure if you specify anything other than a subdirectory. /// </remarks> /// <returns>A <see cref="Realm"/> instance.</returns> /// <exception cref="RealmFileAccessErrorException"> /// Thrown if the file system returns an error preventing file creation. /// </exception> public static Realm GetInstance(string databasePath) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } /// <summary> /// Factory for obtaining a <see cref="Realm"/> instance for this thread. /// </summary> /// <param name="config">Optional configuration.</param> /// <returns>A <see cref="Realm"/> instance.</returns> /// <exception cref="RealmFileAccessErrorException"> /// Thrown if the file system returns an error preventing file creation. /// </exception> public static Realm GetInstance(RealmConfigurationBase config = null) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } /// <summary> /// Compacts a Realm file. A Realm file usually contains free/unused space. This method removes this free space and the file size is thereby reduced. Objects within the Realm files are untouched. /// </summary> /// <remarks> /// The realm file must not be open on other threads. /// The file system should have free space for at least a copy of the Realm file. /// This method must not be called inside a transaction. /// The Realm file is left untouched if any file operation fails. /// </remarks> /// <param name="config">Optional configuration.</param> /// <returns><c>true</c> if successful, <c>false</c> if any file operation failed.</returns> public static bool Compact(RealmConfigurationBase config = null) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return false; } /// <summary> /// Deletes all the files associated with a realm. /// </summary> /// <param name="configuration">A <see cref="RealmConfigurationBase"/> which supplies the realm path.</param> public static void DeleteRealm(RealmConfigurationBase configuration) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); } #endregion /// <summary> /// Gets the <see cref="RealmConfigurationBase"/> that controls this realm's path and other settings. /// </summary> /// <value>The Realm's configuration.</value> public RealmConfigurationBase Config { get; } /// <summary> /// Gets the <see cref="RealmSchema"/> instance that describes all the types that can be stored in this <see cref="Realm"/>. /// </summary> /// <value>The Schema of the Realm.</value> public RealmSchema Schema { get; } /// <summary> /// Handler type used by <see cref="RealmChanged"/> /// </summary> /// <param name="sender">The <see cref="Realm"/> which has changed.</param> /// <param name="e">Currently an empty argument, in future may indicate more details about the change.</param> public delegate void RealmChangedEventHandler(object sender, EventArgs e); /// <summary> /// Triggered when a Realm has changed (i.e. a <see cref="Transaction"/> was committed). /// </summary> public event RealmChangedEventHandler RealmChanged; /// <summary> /// Triggered when a Realm-level exception has occurred. /// </summary> public event EventHandler<ErrorEventArgs> Error; /// <summary> /// Gets a value indicating whether the instance has been closed via <see cref="Dispose"/>. If <c>true</c>, you /// should not call methods on that instance. /// </summary> /// <value><c>true</c> if closed, <c>false</c> otherwise.</value> public bool IsClosed { get; } /// <summary> /// Dispose automatically closes the Realm if not already closed. /// </summary> public void Dispose() { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); } /// <summary> /// Determines whether this instance is the same core instance as the passed in argument. /// </summary> /// <remarks> /// You can, and should, have multiple instances open on different threads which have the same path and open the same Realm. /// </remarks> /// <returns><c>true</c> if this instance is the same core instance; otherwise, <c>false</c>.</returns> /// <param name="other">The Realm to compare with the current Realm.</param> public bool IsSameInstance(Realm other) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return false; } /// <summary> /// Factory for a managed object in a realm. Only valid within a write <see cref="Transaction"/>. /// </summary> /// <returns>A dynamically-accessed Realm object.</returns> /// <param name="className">The type of object to create as defined in the schema.</param> /// <exception cref="RealmInvalidTransactionException"> /// If you invoke this when there is no write <see cref="Transaction"/> active on the <see cref="Realm"/>. /// </exception> /// <remarks> /// <para> /// <b>WARNING:</b> if the dynamic object has a PrimaryKey then that must be the <b>first property set</b> /// otherwise other property changes may be lost. /// </para> /// <para> /// If the realm instance has been created from an un-typed schema (such as when migrating from an older version /// of a realm) the returned object will be purely dynamic. If the realm has been created from a typed schema as /// is the default case when calling <see cref="GetInstance(RealmConfigurationBase)"/> the returned /// object will be an instance of a user-defined class, as if created by <see cref="CreateObject{T}"/>. /// </para> /// </remarks> public dynamic CreateObject(string className) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } /// <summary> /// This <see cref="Realm"/> will start managing a <see cref="RealmObject"/> which has been created as a standalone object. /// </summary> /// <typeparam name="T"> /// The Type T must not only be a <see cref="RealmObject"/> but also have been processed by the Fody weaver, /// so it has persistent properties. /// </typeparam> /// <param name="obj">Must be a standalone object, <c>null</c> not allowed.</param> /// <param name="update">If <c>true</c>, and an object with the same primary key already exists, performs an update.</param> /// <exception cref="RealmInvalidTransactionException"> /// If you invoke this when there is no write <see cref="Transaction"/> active on the <see cref="Realm"/>. /// </exception> /// <exception cref="RealmObjectManagedByAnotherRealmException"> /// You can't manage an object with more than one <see cref="Realm"/>. /// </exception> /// <remarks> /// If the object is already managed by this <see cref="Realm"/>, this method does nothing. /// This method modifies the object in-place, meaning that after it has run, <c>obj</c> will be managed. /// Returning it is just meant as a convenience to enable fluent syntax scenarios. /// Cyclic graphs (<c>Parent</c> has <c>Child</c> that has a <c>Parent</c>) will result in undefined behavior. /// You have to break the cycle manually and assign relationships after all object have been managed. /// </remarks> /// <returns>The passed object, so that you can write <c>var person = realm.Add(new Person { Id = 1 });</c></returns> public T Add<T>(T obj, bool update = false) where T : RealmObject { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return default(T); } /// <summary> /// This <see cref="Realm"/> will start managing a <see cref="RealmObject"/> which has been created as a standalone object. /// </summary> /// <param name="obj">Must be a standalone object, <c>null</c> not allowed.</param> /// <param name="update">If <c>true</c>, and an object with the same primary key already exists, performs an update.</param> /// <exception cref="RealmInvalidTransactionException"> /// If you invoke this when there is no write <see cref="Transaction"/> active on the <see cref="Realm"/>. /// </exception> /// <exception cref="RealmObjectManagedByAnotherRealmException"> /// You can't manage an object with more than one <see cref="Realm"/>. /// </exception> /// <remarks> /// If the object is already managed by this <see cref="Realm"/>, this method does nothing. /// This method modifies the object in-place, meaning that after it has run, <c>obj</c> will be managed. /// Cyclic graphs (<c>Parent</c> has <c>Child</c> that has a <c>Parent</c>) will result in undefined behavior. /// You have to break the cycle manually and assign relationships after all object have been managed. /// </remarks> /// <returns>The passed object.</returns> public RealmObject Add(RealmObject obj, bool update = false) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } /// <summary> /// Factory for a write <see cref="Transaction"/>. Essential object to create scope for updates. /// </summary> /// <example> /// <code> /// using (var trans = realm.BeginWrite()) /// { /// realm.Add(new Dog /// { /// Name = "Rex" /// }); /// trans.Commit(); /// } /// </code> /// </example> /// <returns>A transaction in write mode, which is required for any creation or modification of objects persisted in a <see cref="Realm"/>.</returns> public Transaction BeginWrite() { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } /// <summary> /// Execute an action inside a temporary <see cref="Transaction"/>. If no exception is thrown, the <see cref="Transaction"/> /// will be committed. /// </summary> /// <remarks> /// Creates its own temporary <see cref="Transaction"/> and commits it after running the lambda passed to <c>action</c>. /// Be careful of wrapping multiple single property updates in multiple <see cref="Write"/> calls. /// It is more efficient to update several properties or even create multiple objects in a single <see cref="Write"/>, /// unless you need to guarantee finer-grained updates. /// </remarks> /// <example> /// <code> /// realm.Write(() => /// { /// realm.Add(new Dog /// { /// Name = "Eddie", /// Age = 5 /// }); /// }); /// </code> /// </example> /// <param name="action"> /// <see cref="Action"/> to perform inside a <see cref="Transaction"/>, creating, updating, or removing objects. /// </param> public void Write(Action action) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); } /// <summary> /// Execute an action inside a temporary <see cref="Transaction"/> on a worker thread, <b>if</b> called from UI thread. If no exception is thrown, /// the <see cref="Transaction"/> will be committed. /// </summary> /// <remarks> /// Opens a new instance of this Realm on a worker thread and executes <c>action</c> inside a write <see cref="Transaction"/>. /// <see cref="Realm"/>s and <see cref="RealmObject"/>s are thread-affine, so capturing any such objects in /// the <c>action</c> delegate will lead to errors if they're used on the worker thread. Note that it checks the /// <see cref="SynchronizationContext"/> to determine if <c>Current</c> is null, as a test to see if you are on the UI thread /// and will otherwise just call Write without starting a new thread. So if you know you are invoking from a worker thread, just call Write instead. /// </remarks> /// <example> /// <code> /// await realm.WriteAsync(tempRealm =&gt; /// { /// var pongo = tempRealm.All&lt;Dog&gt;().Single(d =&gt; d.Name == "Pongo"); /// var missis = tempRealm.All&lt;Dog&gt;().Single(d =&gt; d.Name == "Missis"); /// for (var i = 0; i &lt; 15; i++) /// { /// tempRealm.Add(new Dog /// { /// Breed = "Dalmatian", /// Mum = missis, /// Dad = pongo /// }); /// } /// }); /// </code> /// <b>Note</b> that inside the action, we use <c>tempRealm</c>. /// </example> /// <param name="action"> /// Action to perform inside a <see cref="Transaction"/>, creating, updating, or removing objects. /// </param> /// <returns>An awaitable <see cref="Task"/>.</returns> public Task WriteAsync(Action<Realm> action) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } /// <summary> /// Update the <see cref="Realm"/> instance and outstanding objects to point to the most recent persisted version. /// </summary> /// <returns> /// Whether the <see cref="Realm"/> had any updates. Note that this may return true even if no data has actually changed. /// </returns> public bool Refresh() { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return false; } /// <summary> /// Extract an iterable set of objects for direct use or further query. /// </summary> /// <typeparam name="T">The Type T must be a <see cref="RealmObject"/>.</typeparam> /// <returns>A queryable collection that without further filtering, allows iterating all objects of class T, in this <see cref="Realm"/>.</returns> public IQueryable<T> All<T>() where T : RealmObject { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } /// <summary> /// Get a view of all the objects of a particular type. /// </summary> /// <param name="className">The type of the objects as defined in the schema.</param> /// <remarks>Because the objects inside the view are accessed dynamically, the view cannot be queried into using LINQ or other expression predicates.</remarks> /// <returns>A queryable collection that without further filtering, allows iterating all objects of className, in this realm.</returns> public IQueryable<dynamic> All(string className) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } /// <summary> /// Fast lookup of an object from a class which has a PrimaryKey property. /// </summary> /// <typeparam name="T">The Type T must be a <see cref="RealmObject"/>.</typeparam> /// <param name="primaryKey"> /// Primary key to be matched exactly, same as an == search. /// An argument of type <c>long?</c> works for all integer properties, supported as PrimaryKey. /// </param> /// <returns><c>null</c> or an object matching the primary key.</returns> /// <exception cref="RealmClassLacksPrimaryKeyException"> /// If the <see cref="RealmObject"/> class T lacks <see cref="PrimaryKeyAttribute"/>. /// </exception> public T Find<T>(long? primaryKey) where T : RealmObject { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } /// <summary> /// Fast lookup of an object from a class which has a PrimaryKey property. /// </summary> /// <typeparam name="T">The Type T must be a <see cref="RealmObject"/>.</typeparam> /// <param name="primaryKey">Primary key to be matched exactly, same as an == search.</param> /// <returns><c>null</c> or an object matching the primary key.</returns> /// <exception cref="RealmClassLacksPrimaryKeyException"> /// If the <see cref="RealmObject"/> class T lacks <see cref="PrimaryKeyAttribute"/>. /// </exception> public T Find<T>(string primaryKey) where T : RealmObject { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } /// <summary> /// Fast lookup of an object for dynamic use, from a class which has a PrimaryKey property. /// </summary> /// <param name="className">Name of class in dynamic situation.</param> /// <param name="primaryKey"> /// Primary key to be matched exactly, same as an == search. /// An argument of type <c>long?</c> works for all integer properties, supported as PrimaryKey. /// </param> /// <returns><c>null</c> or an object matching the primary key.</returns> /// <exception cref="RealmClassLacksPrimaryKeyException"> /// If the <see cref="RealmObject"/> class T lacks <see cref="PrimaryKeyAttribute"/>. /// </exception> public RealmObject Find(string className, long? primaryKey) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } /// <summary> /// Fast lookup of an object for dynamic use, from a class which has a PrimaryKey property. /// </summary> /// <param name="className">Name of class in dynamic situation.</param> /// <param name="primaryKey">Primary key to be matched exactly, same as an == search.</param> /// <returns><c>null</c> or an object matching the primary key.</returns> /// <exception cref="RealmClassLacksPrimaryKeyException"> /// If the <see cref="RealmObject"/> class T lacks <see cref="PrimaryKeyAttribute"/>. /// </exception> public RealmObject Find(string className, string primaryKey) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } /// <summary> /// Removes a persistent object from this Realm, effectively deleting it. /// </summary> /// <param name="obj">Must be an object persisted in this Realm.</param> /// <exception cref="RealmInvalidTransactionException"> /// If you invoke this when there is no write <see cref="Transaction"/> active on the <see cref="Realm"/>. /// </exception> /// <exception cref="ArgumentNullException">If <c>obj</c> is <c>null</c>.</exception> /// <exception cref="ArgumentException">If you pass a standalone object.</exception> public void Remove(RealmObject obj) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); } /// <summary> /// Remove objects matching a query from the Realm. /// </summary> /// <typeparam name="T">Type of the objects to remove.</typeparam> /// <param name="range">The query to match for.</param> /// <exception cref="RealmInvalidTransactionException"> /// If you invoke this when there is no write <see cref="Transaction"/> active on the <see cref="Realm"/>. /// </exception> /// <exception cref="ArgumentException"> /// If <c>range</c> is not the result of <see cref="All{T}"/> or subsequent LINQ filtering. /// </exception> /// <exception cref="ArgumentNullException">If <c>range</c> is <c>null</c>.</exception> public void RemoveRange<T>(IQueryable<T> range) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); } /// <summary> /// Remove all objects of a type from the Realm. /// </summary> /// <typeparam name="T">Type of the objects to remove.</typeparam> /// <exception cref="RealmInvalidTransactionException"> /// If you invoke this when there is no write <see cref="Transaction"/> active on the <see cref="Realm"/>. /// </exception> /// <exception cref="ArgumentException"> /// If the type T is not part of the limited set of classes in this Realm's <see cref="Schema"/>. /// </exception> public void RemoveAll<T>() where T : RealmObject { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); } /// <summary> /// Remove all objects of a type from the Realm. /// </summary> /// <param name="className">Type of the objects to remove as defined in the schema.</param> /// <exception cref="RealmInvalidTransactionException"> /// If you invoke this when there is no write <see cref="Transaction"/> active on the <see cref="Realm"/>. /// </exception> /// <exception cref="ArgumentException"> /// If you pass <c>className</c> that does not belong to this Realm's schema. /// </exception> public void RemoveAll(string className) { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); } /// <summary> /// Remove all objects of all types managed by this Realm. /// </summary> /// <exception cref="RealmInvalidTransactionException"> /// If you invoke this when there is no write <see cref="Transaction"/> active on the <see cref="Realm"/>. /// </exception> public void RemoveAll() { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); } #region Thread Handover /// <summary> /// Returns the same object as the one referenced when the <see cref="ThreadSafeReference.Object{T}"/> was first created, /// but resolved for the current Realm for this thread. /// </summary> /// <param name="reference">The thread-safe reference to the thread-confined <see cref="RealmObject"/> to resolve in this <see cref="Realm"/>.</param> /// <typeparam name="T">The type of the object, contained in the reference.</typeparam> /// <returns> /// A thread-confined instance of the original <see cref="RealmObject"/> resolved for the current thread or <c>null</c> /// if the object has been deleted after the reference was created. /// </returns> public T ResolveReference<T>(ThreadSafeReference.Object<T> reference) where T : RealmObject { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } /// <summary> /// Returns the same collection as the one referenced when the <see cref="ThreadSafeReference.List{T}"/> was first created, /// but resolved for the current Realm for this thread. /// </summary> /// <param name="reference">The thread-safe reference to the thread-confined <see cref="IList{T}"/> to resolve in this <see cref="Realm"/>.</param> /// <typeparam name="T">The type of the object, contained in the collection.</typeparam> /// <returns> /// A thread-confined instance of the original <see cref="IList{T}"/> resolved for the current thread or <c>null</c> /// if the list's parent object has been deleted after the reference was created. /// </returns> public IList<T> ResolveReference<T>(ThreadSafeReference.List<T> reference) where T : RealmObject { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } /// <summary> /// Returns the same query as the one referenced when the <see cref="ThreadSafeReference.Query{T}"/> was first created, /// but resolved for the current Realm for this thread. /// </summary> /// <param name="reference">The thread-safe reference to the thread-confined <see cref="IQueryable{T}"/> to resolve in this <see cref="Realm"/>.</param> /// <typeparam name="T">The type of the object, contained in the query.</typeparam> /// <returns>A thread-confined instance of the original <see cref="IQueryable{T}"/> resolved for the current thread.</returns> public IQueryable<T> ResolveReference<T>(ThreadSafeReference.Query<T> reference) where T : RealmObject { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } #endregion #region Obsolete methods /// <summary> /// <b>Deprecated</b> Fast lookup of an object from a class which has a PrimaryKey property. /// </summary> /// <typeparam name="T">The Type T must be a RealmObject.</typeparam> /// <param name="id">Id to be matched exactly, same as an == search. <see cref="Int64"/> argument works for all integer properties supported as PrimaryKey.</param> /// <returns>Null or an object matching the id.</returns> /// <exception cref="RealmClassLacksPrimaryKeyException">If the RealmObject class T lacks an [PrimaryKey].</exception> [Obsolete("This method has been renamed. Use Find for the same results.")] public T ObjectForPrimaryKey<T>(long id) where T : RealmObject { return Find<T>(id); } /// <summary> /// <b>Deprecated</b> Fast lookup of an object from a class which has a PrimaryKey property. /// </summary> /// <typeparam name="T">The Type T must be a RealmObject.</typeparam> /// <param name="id">Id to be matched exactly, same as an == search.</param> /// <returns>Null or an object matching the id.</returns> /// <exception cref="RealmClassLacksPrimaryKeyException">If the RealmObject class T lacks an [PrimaryKey].</exception> [Obsolete("This method has been renamed. Use Find for the same results.")] public T ObjectForPrimaryKey<T>(string id) where T : RealmObject { return Find<T>(id); } /// <summary> /// <b>Deprecated</b> Fast lookup of an object for dynamic use, from a class which has a PrimaryKey property. /// </summary> /// <param name="className">Name of class in dynamic situation.</param> /// <param name="id">Id to be matched exactly, same as an == search.</param> /// <returns>Null or an object matching the id.</returns> /// <exception cref="RealmClassLacksPrimaryKeyException">If the RealmObject class lacks an [PrimaryKey].</exception> [Obsolete("This method has been renamed. Use Find for the same results.")] public RealmObject ObjectForPrimaryKey(string className, long id) { return Find(className, id); } /// <summary> /// <b>Deprecated</b> Fast lookup of an object for dynamic use, from a class which has a PrimaryKey property. /// </summary> /// <param name="className">Name of class in dynamic situation.</param> /// <param name="id">Id to be matched exactly, same as an == search.</param> /// <returns>Null or an object matching the id.</returns> /// <exception cref="RealmClassLacksPrimaryKeyException">If the RealmObject class lacks an [PrimaryKey].</exception> [Obsolete("This method has been renamed. Use Find for the same results.")] public RealmObject ObjectForPrimaryKey(string className, string id) { return Find(className, id); } /// <summary> /// <b>Deprecated</b> This realm will start managing a RealmObject which has been created as a standalone object. /// </summary> /// <typeparam name="T">The Type T must not only be a RealmObject but also have been processed by the Fody weaver, so it has persistent properties.</typeparam> /// <param name="obj">Must be a standalone object, null not allowed.</param> /// <param name="update">If true, and an object with the same primary key already exists, performs an update.</param> /// <exception cref="RealmInvalidTransactionException">If you invoke this when there is no write Transaction active on the realm.</exception> /// <exception cref="RealmObjectManagedByAnotherRealmException">You can't manage an object with more than one realm.</exception> [Obsolete("This method has been renamed. Use Add for the same results.")] public void Manage<T>(T obj, bool update) where T : RealmObject { Add(obj, update); } /// <summary> /// <b>Deprecated</b> Closes the Realm if not already closed. Safe to call repeatedly. /// Note that this will close the file. Other references to the same database /// on the same thread will be invalidated. /// </summary> [Obsolete("This method has been deprecated. Instead, dispose the realm to close it.")] public void Close() { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); } /// <summary> /// <b>Deprecated</b> Factory for a managed object in a realm. Only valid within a write <see cref="Transaction"/>. /// </summary> /// <remarks>Scheduled for removal in the next major release, as it is dangerous to call CreateObject and then assign a PrimaryKey.</remarks> /// <typeparam name="T">The Type T must be a RealmObject.</typeparam> /// <returns>An object which is already managed.</returns> /// <exception cref="RealmInvalidTransactionException">If you invoke this when there is no write Transaction active on the realm.</exception> [Obsolete("Please create an object with new and pass to Add instead")] public T CreateObject<T>() where T : RealmObject, new() { RealmPCLHelpers.ThrowProxyShouldNeverBeUsed(); return null; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Globalization { internal static class CalendricalCalculationsHelper { private const double FullCircleOfArc = 360.0; // 360.0; private const int HalfCircleOfArc = 180; private const double TwelveHours = 0.5; // half a day private const double Noon2000Jan01 = 730120.5; internal const double MeanTropicalYearInDays = 365.242189; private const double MeanSpeedOfSun = MeanTropicalYearInDays / FullCircleOfArc; private const double LongitudeSpring = 0.0; private const double TwoDegreesAfterSpring = 2.0; private const int SecondsPerDay = 24 * 60 * 60; // 24 hours * 60 minutes * 60 seconds private const int DaysInUniformLengthCentury = 36525; private const int SecondsPerMinute = 60; private const int MinutesPerDegree = 60; private static readonly long s_startOf1810 = GetNumberOfDays(new DateTime(1810, 1, 1)); private static readonly long s_startOf1900Century = GetNumberOfDays(new DateTime(1900, 1, 1)); private static readonly double[] s_coefficients1900to1987 = new double[] { -0.00002, 0.000297, 0.025184, -0.181133, 0.553040, -0.861938, 0.677066, -0.212591 }; private static readonly double[] s_coefficients1800to1899 = new double[] { -0.000009, 0.003844, 0.083563, 0.865736, 4.867575, 15.845535, 31.332267, 38.291999, 28.316289, 11.636204, 2.043794 }; private static readonly double[] s_coefficients1700to1799 = new double[] { 8.118780842, -0.005092142, 0.003336121, -0.0000266484 }; private static readonly double[] s_coefficients1620to1699 = new double[] { 196.58333, -4.0675, 0.0219167 }; private static readonly double[] s_lambdaCoefficients = new double[] { 280.46645, 36000.76983, 0.0003032 }; private static readonly double[] s_anomalyCoefficients = new double[] { 357.52910, 35999.05030, -0.0001559, -0.00000048 }; private static readonly double[] s_eccentricityCoefficients = new double[] { 0.016708617, -0.000042037, -0.0000001236 }; private static readonly double[] s_coefficients = new double[] { Angle(23, 26, 21.448), Angle(0, 0, -46.8150), Angle(0, 0, -0.00059), Angle(0, 0, 0.001813) }; private static readonly double[] s_coefficientsA = new double[] { 124.90, -1934.134, 0.002063 }; private static readonly double[] s_coefficientsB = new double[] { 201.11, 72001.5377, 0.00057 }; private static double RadiansFromDegrees(double degree) { return degree * Math.PI / 180; } private static double SinOfDegree(double degree) { return Math.Sin(RadiansFromDegrees(degree)); } private static double CosOfDegree(double degree) { return Math.Cos(RadiansFromDegrees(degree)); } private static double TanOfDegree(double degree) { return Math.Tan(RadiansFromDegrees(degree)); } public static double Angle(int degrees, int minutes, double seconds) { return ((seconds / SecondsPerMinute + minutes) / MinutesPerDegree) + degrees; } private static double Obliquity(double julianCenturies) { return PolynomialSum(s_coefficients, julianCenturies); } internal static long GetNumberOfDays(DateTime date) { return date.Ticks / GregorianCalendar.TicksPerDay; } private static int GetGregorianYear(double numberOfDays) { return new DateTime(Math.Min((long)(Math.Floor(numberOfDays) * GregorianCalendar.TicksPerDay), DateTime.MaxValue.Ticks)).Year; } private enum CorrectionAlgorithm { Default, Year1988to2019, Year1900to1987, Year1800to1899, Year1700to1799, Year1620to1699 } private struct EphemerisCorrectionAlgorithmMap { public EphemerisCorrectionAlgorithmMap(int year, CorrectionAlgorithm algorithm) { _lowestYear = year; _algorithm = algorithm; } internal int _lowestYear; internal CorrectionAlgorithm _algorithm; } private static readonly EphemerisCorrectionAlgorithmMap[] s_ephemerisCorrectionTable = new EphemerisCorrectionAlgorithmMap[] { // lowest year that starts algorithm, algorithm to use new EphemerisCorrectionAlgorithmMap(2020, CorrectionAlgorithm.Default), new EphemerisCorrectionAlgorithmMap(1988, CorrectionAlgorithm.Year1988to2019), new EphemerisCorrectionAlgorithmMap(1900, CorrectionAlgorithm.Year1900to1987), new EphemerisCorrectionAlgorithmMap(1800, CorrectionAlgorithm.Year1800to1899), new EphemerisCorrectionAlgorithmMap(1700, CorrectionAlgorithm.Year1700to1799), new EphemerisCorrectionAlgorithmMap(1620, CorrectionAlgorithm.Year1620to1699), new EphemerisCorrectionAlgorithmMap(int.MinValue, CorrectionAlgorithm.Default) // default must be last }; private static double Reminder(double divisor, double dividend) { double whole = Math.Floor(divisor / dividend); return divisor - (dividend * whole); } private static double NormalizeLongitude(double longitude) { longitude = Reminder(longitude, FullCircleOfArc); if (longitude < 0) { longitude += FullCircleOfArc; } return longitude; } public static double AsDayFraction(double longitude) { return longitude / FullCircleOfArc; } private static double PolynomialSum(double[] coefficients, double indeterminate) { double sum = coefficients[0]; double indeterminateRaised = 1; for (int i = 1; i < coefficients.Length; i++) { indeterminateRaised *= indeterminate; sum += (coefficients[i] * indeterminateRaised); } return sum; } private static double CenturiesFrom1900(int gregorianYear) { long july1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 7, 1)); return (double)(july1stOfYear - s_startOf1900Century) / DaysInUniformLengthCentury; } // the following formulas defines a polynomial function which gives us the amount that the earth is slowing down for specific year ranges private static double DefaultEphemerisCorrection(int gregorianYear) { Debug.Assert(gregorianYear < 1620 || 2020 <= gregorianYear); long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1)); double daysSinceStartOf1810 = january1stOfYear - s_startOf1810; double x = TwelveHours + daysSinceStartOf1810; return ((Math.Pow(x, 2) / 41048480) - 15) / SecondsPerDay; } private static double EphemerisCorrection1988to2019(int gregorianYear) { Debug.Assert(1988 <= gregorianYear && gregorianYear <= 2019); return (double)(gregorianYear - 1933) / SecondsPerDay; } private static double EphemerisCorrection1900to1987(int gregorianYear) { Debug.Assert(1900 <= gregorianYear && gregorianYear <= 1987); double centuriesFrom1900 = CenturiesFrom1900(gregorianYear); return PolynomialSum(s_coefficients1900to1987, centuriesFrom1900); } private static double EphemerisCorrection1800to1899(int gregorianYear) { Debug.Assert(1800 <= gregorianYear && gregorianYear <= 1899); double centuriesFrom1900 = CenturiesFrom1900(gregorianYear); return PolynomialSum(s_coefficients1800to1899, centuriesFrom1900); } private static double EphemerisCorrection1700to1799(int gregorianYear) { Debug.Assert(1700 <= gregorianYear && gregorianYear <= 1799); double yearsSince1700 = gregorianYear - 1700; return PolynomialSum(s_coefficients1700to1799, yearsSince1700) / SecondsPerDay; } private static double EphemerisCorrection1620to1699(int gregorianYear) { Debug.Assert(1620 <= gregorianYear && gregorianYear <= 1699); double yearsSince1600 = gregorianYear - 1600; return PolynomialSum(s_coefficients1620to1699, yearsSince1600) / SecondsPerDay; } // ephemeris-correction: correction to account for the slowing down of the rotation of the earth private static double EphemerisCorrection(double time) { int year = GetGregorianYear(time); foreach (EphemerisCorrectionAlgorithmMap map in s_ephemerisCorrectionTable) { if (map._lowestYear <= year) { switch (map._algorithm) { case CorrectionAlgorithm.Default: return DefaultEphemerisCorrection(year); case CorrectionAlgorithm.Year1988to2019: return EphemerisCorrection1988to2019(year); case CorrectionAlgorithm.Year1900to1987: return EphemerisCorrection1900to1987(year); case CorrectionAlgorithm.Year1800to1899: return EphemerisCorrection1800to1899(year); case CorrectionAlgorithm.Year1700to1799: return EphemerisCorrection1700to1799(year); case CorrectionAlgorithm.Year1620to1699: return EphemerisCorrection1620to1699(year); } break; // break the loop and assert eventually } } Debug.Fail("Not expected to come here"); return DefaultEphemerisCorrection(year); } public static double JulianCenturies(double moment) { double dynamicalMoment = moment + EphemerisCorrection(moment); return (dynamicalMoment - Noon2000Jan01) / DaysInUniformLengthCentury; } private static bool IsNegative(double value) { return Math.Sign(value) == -1; } private static double CopySign(double value, double sign) { return (IsNegative(value) == IsNegative(sign)) ? value : -value; } // equation-of-time; approximate the difference between apparent solar time and mean solar time // formal definition is EOT = GHA - GMHA // GHA is the Greenwich Hour Angle of the apparent (actual) Sun // GMHA is the Greenwich Mean Hour Angle of the mean (fictitious) Sun // http://www.esrl.noaa.gov/gmd/grad/solcalc/ // http://en.wikipedia.org/wiki/Equation_of_time private static double EquationOfTime(double time) { double julianCenturies = JulianCenturies(time); double lambda = PolynomialSum(s_lambdaCoefficients, julianCenturies); double anomaly = PolynomialSum(s_anomalyCoefficients, julianCenturies); double eccentricity = PolynomialSum(s_eccentricityCoefficients, julianCenturies); double epsilon = Obliquity(julianCenturies); double tanHalfEpsilon = TanOfDegree(epsilon / 2); double y = tanHalfEpsilon * tanHalfEpsilon; double dividend = ((y * SinOfDegree(2 * lambda)) - (2 * eccentricity * SinOfDegree(anomaly)) + (4 * eccentricity * y * SinOfDegree(anomaly) * CosOfDegree(2 * lambda)) - (0.5 * Math.Pow(y, 2) * SinOfDegree(4 * lambda)) - (1.25 * Math.Pow(eccentricity, 2) * SinOfDegree(2 * anomaly))); const double Divisor = 2 * Math.PI; double equation = dividend / Divisor; // approximation of equation of time is not valid for dates that are many millennia in the past or future // thus limited to a half day return CopySign(Math.Min(Math.Abs(equation), TwelveHours), equation); } private static double AsLocalTime(double apparentMidday, double longitude) { // slightly inaccurate since equation of time takes mean time not apparent time as its argument, but the difference is negligible double universalTime = apparentMidday - AsDayFraction(longitude); return apparentMidday - EquationOfTime(universalTime); } // midday public static double Midday(double date, double longitude) { return AsLocalTime(date + TwelveHours, longitude) - AsDayFraction(longitude); } private static double InitLongitude(double longitude) { return NormalizeLongitude(longitude + HalfCircleOfArc) - HalfCircleOfArc; } // midday-in-tehran public static double MiddayAtPersianObservationSite(double date) { return Midday(date, InitLongitude(52.5)); // 52.5 degrees east - longitude of UTC+3:30 which defines Iranian Standard Time } private static double PeriodicTerm(double julianCenturies, int x, double y, double z) { return x * SinOfDegree(y + z * julianCenturies); } private static double SumLongSequenceOfPeriodicTerms(double julianCenturies) { double sum = 0.0; sum += PeriodicTerm(julianCenturies, 403406, 270.54861, 0.9287892); sum += PeriodicTerm(julianCenturies, 195207, 340.19128, 35999.1376958); sum += PeriodicTerm(julianCenturies, 119433, 63.91854, 35999.4089666); sum += PeriodicTerm(julianCenturies, 112392, 331.2622, 35998.7287385); sum += PeriodicTerm(julianCenturies, 3891, 317.843, 71998.20261); sum += PeriodicTerm(julianCenturies, 2819, 86.631, 71998.4403); sum += PeriodicTerm(julianCenturies, 1721, 240.052, 36000.35726); sum += PeriodicTerm(julianCenturies, 660, 310.26, 71997.4812); sum += PeriodicTerm(julianCenturies, 350, 247.23, 32964.4678); sum += PeriodicTerm(julianCenturies, 334, 260.87, -19.441); sum += PeriodicTerm(julianCenturies, 314, 297.82, 445267.1117); sum += PeriodicTerm(julianCenturies, 268, 343.14, 45036.884); sum += PeriodicTerm(julianCenturies, 242, 166.79, 3.1008); sum += PeriodicTerm(julianCenturies, 234, 81.53, 22518.4434); sum += PeriodicTerm(julianCenturies, 158, 3.5, -19.9739); sum += PeriodicTerm(julianCenturies, 132, 132.75, 65928.9345); sum += PeriodicTerm(julianCenturies, 129, 182.95, 9038.0293); sum += PeriodicTerm(julianCenturies, 114, 162.03, 3034.7684); sum += PeriodicTerm(julianCenturies, 99, 29.8, 33718.148); sum += PeriodicTerm(julianCenturies, 93, 266.4, 3034.448); sum += PeriodicTerm(julianCenturies, 86, 249.2, -2280.773); sum += PeriodicTerm(julianCenturies, 78, 157.6, 29929.992); sum += PeriodicTerm(julianCenturies, 72, 257.8, 31556.493); sum += PeriodicTerm(julianCenturies, 68, 185.1, 149.588); sum += PeriodicTerm(julianCenturies, 64, 69.9, 9037.75); sum += PeriodicTerm(julianCenturies, 46, 8.0, 107997.405); sum += PeriodicTerm(julianCenturies, 38, 197.1, -4444.176); sum += PeriodicTerm(julianCenturies, 37, 250.4, 151.771); sum += PeriodicTerm(julianCenturies, 32, 65.3, 67555.316); sum += PeriodicTerm(julianCenturies, 29, 162.7, 31556.08); sum += PeriodicTerm(julianCenturies, 28, 341.5, -4561.54); sum += PeriodicTerm(julianCenturies, 27, 291.6, 107996.706); sum += PeriodicTerm(julianCenturies, 27, 98.5, 1221.655); sum += PeriodicTerm(julianCenturies, 25, 146.7, 62894.167); sum += PeriodicTerm(julianCenturies, 24, 110.0, 31437.369); sum += PeriodicTerm(julianCenturies, 21, 5.2, 14578.298); sum += PeriodicTerm(julianCenturies, 21, 342.6, -31931.757); sum += PeriodicTerm(julianCenturies, 20, 230.9, 34777.243); sum += PeriodicTerm(julianCenturies, 18, 256.1, 1221.999); sum += PeriodicTerm(julianCenturies, 17, 45.3, 62894.511); sum += PeriodicTerm(julianCenturies, 14, 242.9, -4442.039); sum += PeriodicTerm(julianCenturies, 13, 115.2, 107997.909); sum += PeriodicTerm(julianCenturies, 13, 151.8, 119.066); sum += PeriodicTerm(julianCenturies, 13, 285.3, 16859.071); sum += PeriodicTerm(julianCenturies, 12, 53.3, -4.578); sum += PeriodicTerm(julianCenturies, 10, 126.6, 26895.292); sum += PeriodicTerm(julianCenturies, 10, 205.7, -39.127); sum += PeriodicTerm(julianCenturies, 10, 85.9, 12297.536); sum += PeriodicTerm(julianCenturies, 10, 146.1, 90073.778); return sum; } private static double Aberration(double julianCenturies) { return (0.0000974 * CosOfDegree(177.63 + (35999.01848 * julianCenturies))) - 0.005575; } private static double Nutation(double julianCenturies) { double a = PolynomialSum(s_coefficientsA, julianCenturies); double b = PolynomialSum(s_coefficientsB, julianCenturies); return (-0.004778 * SinOfDegree(a)) - (0.0003667 * SinOfDegree(b)); } public static double Compute(double time) { double julianCenturies = JulianCenturies(time); double lambda = 282.7771834 + (36000.76953744 * julianCenturies) + (0.000005729577951308232 * SumLongSequenceOfPeriodicTerms(julianCenturies)); double longitude = lambda + Aberration(julianCenturies) + Nutation(julianCenturies); return InitLongitude(longitude); } public static double AsSeason(double longitude) { return (longitude < 0) ? (longitude + FullCircleOfArc) : longitude; } private static double EstimatePrior(double longitude, double time) { double timeSunLastAtLongitude = time - (MeanSpeedOfSun * AsSeason(InitLongitude(Compute(time) - longitude))); double longitudeErrorDelta = InitLongitude(Compute(timeSunLastAtLongitude) - longitude); return Math.Min(time, timeSunLastAtLongitude - (MeanSpeedOfSun * longitudeErrorDelta)); } // persian-new-year-on-or-before // number of days is the absolute date. The absolute date is the number of days from January 1st, 1 A.D. // 1/1/0001 is absolute date 1. internal static long PersianNewYearOnOrBefore(long numberOfDays) { double date = (double)numberOfDays; double approx = EstimatePrior(LongitudeSpring, MiddayAtPersianObservationSite(date)); long lowerBoundNewYearDay = (long)Math.Floor(approx) - 1; long upperBoundNewYearDay = lowerBoundNewYearDay + 3; // estimate is generally within a day of the actual occurrence (at the limits, the error expands, since the calculations rely on the mean tropical year which changes...) long day = lowerBoundNewYearDay; for (; day != upperBoundNewYearDay; ++day) { double midday = MiddayAtPersianObservationSite((double)day); double l = Compute(midday); if ((LongitudeSpring <= l) && (l <= TwoDegreesAfterSpring)) { break; } } Debug.Assert(day != upperBoundNewYearDay); return day - 1; } } }
// 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.Linq; using System.Linq.Expressions; using Microsoft.AspNetCore.Mvc.ViewFeatures; namespace Microsoft.AspNetCore.Mvc.ModelBinding { /// <summary> /// Extensions methods for <see cref="ModelStateDictionary"/>. /// </summary> public static class ModelStateDictionaryExtensions { /// <summary> /// Adds the specified <paramref name="errorMessage"/> to the <see cref="ModelStateEntry.Errors"/> instance /// that is associated with the specified <paramref name="expression"/>. If the maximum number of allowed /// errors has already been recorded, ensures that a <see cref="TooManyModelErrorsException"/> exception is /// recorded instead. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <param name="modelState">The <see cref="ModelStateDictionary"/> instance this method extends.</param> /// <param name="expression">An expression to be evaluated against an item in the current model.</param> /// <param name="errorMessage">The error message to add.</param> public static void AddModelError<TModel>( this ModelStateDictionary modelState, Expression<Func<TModel, object>> expression, string errorMessage) { if (modelState == null) { throw new ArgumentNullException(nameof(modelState)); } if (expression == null) { throw new ArgumentNullException(nameof(expression)); } if (errorMessage == null) { throw new ArgumentNullException(nameof(errorMessage)); } modelState.AddModelError(GetExpressionText(expression), errorMessage); } /// <summary> /// Adds the specified <paramref name="exception"/> to the <see cref="ModelStateEntry.Errors"/> instance /// that is associated with the specified <paramref name="expression"/>. If the maximum number of allowed /// errors has already been recorded, ensures that a <see cref="TooManyModelErrorsException"/> exception is /// recorded instead. /// </summary> /// <remarks> /// This method allows adding the <paramref name="exception"/> to the current <see cref="ModelStateDictionary"/> /// when <see cref="ModelMetadata"/> is not available or the exact <paramref name="exception"/> /// must be maintained for later use (even if it is for example a <see cref="FormatException"/>). /// </remarks> /// <typeparam name="TModel">The type of the model.</typeparam> /// <param name="modelState">The <see cref="ModelStateDictionary"/> instance this method extends.</param> /// <param name="expression">An expression to be evaluated against an item in the current model.</param> /// <param name="exception">The <see cref="Exception"/> to add.</param> public static void TryAddModelException<TModel>( this ModelStateDictionary modelState, Expression<Func<TModel, object>> expression, Exception exception) { if (modelState == null) { throw new ArgumentNullException(nameof(modelState)); } if (expression == null) { throw new ArgumentNullException(nameof(expression)); } modelState.TryAddModelException(GetExpressionText(expression), exception); } /// <summary> /// Adds the specified <paramref name="exception"/> to the <see cref="ModelStateEntry.Errors"/> instance /// that is associated with the specified <paramref name="expression"/>. If the maximum number of allowed /// errors has already been recorded, ensures that a <see cref="TooManyModelErrorsException"/> exception is /// recorded instead. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <param name="modelState">The <see cref="ModelStateDictionary"/> instance this method extends.</param> /// <param name="expression">An expression to be evaluated against an item in the current model.</param> /// <param name="exception">The <see cref="Exception"/> to add.</param> /// <param name="metadata">The <see cref="ModelMetadata"/> associated with the model.</param> public static void AddModelError<TModel>( this ModelStateDictionary modelState, Expression<Func<TModel, object>> expression, Exception exception, ModelMetadata metadata) { if (modelState == null) { throw new ArgumentNullException(nameof(modelState)); } if (expression == null) { throw new ArgumentNullException(nameof(expression)); } if (metadata == null) { throw new ArgumentNullException(nameof(metadata)); } modelState.AddModelError(GetExpressionText(expression), exception, metadata); } /// <summary> /// Removes the specified <paramref name="expression"/> from the <see cref="ModelStateDictionary"/>. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <param name="modelState">The <see cref="ModelStateDictionary"/> instance this method extends.</param> /// <param name="expression">An expression to be evaluated against an item in the current model.</param> /// <returns> /// true if the element is successfully removed; otherwise, false. /// This method also returns false if <paramref name="expression"/> was not found in the model-state dictionary. /// </returns> public static bool Remove<TModel>( this ModelStateDictionary modelState, Expression<Func<TModel, object>> expression) { if (modelState == null) { throw new ArgumentNullException(nameof(modelState)); } if (expression == null) { throw new ArgumentNullException(nameof(expression)); } return modelState.Remove(GetExpressionText(expression)); } /// <summary> /// Removes all the entries for the specified <paramref name="expression"/> from the /// <see cref="ModelStateDictionary"/>. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <param name="modelState">The <see cref="ModelStateDictionary"/> instance this method extends.</param> /// <param name="expression">An expression to be evaluated against an item in the current model.</param> public static void RemoveAll<TModel>( this ModelStateDictionary modelState, Expression<Func<TModel, object>> expression) { if (modelState == null) { throw new ArgumentNullException(nameof(modelState)); } if (expression == null) { throw new ArgumentNullException(nameof(expression)); } string modelKey = GetExpressionText(expression); if (string.IsNullOrEmpty(modelKey)) { var modelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(typeof(TModel)); for (var i = 0; i < modelMetadata.Properties.Count; i++) { var property = modelMetadata.Properties[i]; var childKey = property.BinderModelName ?? property.PropertyName; var entries = modelState.FindKeysWithPrefix(childKey).ToArray(); foreach (var entry in entries) { modelState.Remove(entry.Key); } } } else { var entries = modelState.FindKeysWithPrefix(modelKey).ToArray(); foreach (var entry in entries) { modelState.Remove(entry.Key); } } } private static string GetExpressionText(LambdaExpression expression) { // We check if expression is wrapped with conversion to object expression // and unwrap it if necessary, because Expression<Func<TModel, object>> // automatically creates a convert to object expression for expressions // returning value types var unaryExpression = expression.Body as UnaryExpression; if (IsConversionToObject(unaryExpression)) { return ExpressionHelper.GetUncachedExpressionText(Expression.Lambda( unaryExpression.Operand, expression.Parameters[0])); } return ExpressionHelper.GetUncachedExpressionText(expression); } private static bool IsConversionToObject(UnaryExpression expression) { return expression?.NodeType == ExpressionType.Convert && expression.Operand?.NodeType == ExpressionType.MemberAccess && expression.Type == typeof(object); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named01a.named01a { // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with named parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); return tf.Foo(x: 2); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named01b.named01b { // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with named parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived tf = new Derived(); dynamic d = 2; return tf.Foo(x: d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named01c.named01c { // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with named parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); dynamic d = 2; return tf.Foo(x: d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named02a.named02a { // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with named parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x, int y) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); return tf.Foo(y: 1, x: 2); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named02b.named02b { // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with named parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x, int y) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived tf = new Derived(); dynamic d1 = 1; dynamic d2 = 2; return tf.Foo(y: d1, x: d2); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named02c.named02c { // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with named parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x, int y) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); dynamic d1 = 1; dynamic d2 = 2; return tf.Foo(y: d1, x: d2); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named03a.named03a { // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with and incorrect parameter</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); try { tf.Foo(Invalid: 2); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadNamedArgument, e.Message, "Foo", "Invalid"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named03c.named03c { // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with and incorrect parameter</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); dynamic d = 2; try { tf.Foo(Invalid: d); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadNamedArgument, e.Message, "Foo", "Invalid"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional03.optional03 { // <Area>Optional Parameters</Area> // <Title> Basic Optional Parameter</Title> // <Description>Basic testing of a simple function with non-optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x) { if (x == 2) return 1; else return 0; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); try { tf.Foo(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional02a.optional02a { // <Area>Optional Parameters</Area> // <Title> Basic Optional Parameter</Title> // <Description>Basic testing of a simple function with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x = 2) { if (x == 2) return 1; else return 0; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); return tf.Foo(1); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional02b.optional02b { // <Area>Optional Parameters</Area> // <Title> Basic Optional Parameter</Title> // <Description>Basic testing of a simple function with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x = 2) { if (x == 2) return 1; else return 0; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived tf = new Derived(); dynamic d = 1; return tf.Foo(d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional02c.optional02c { // <Area>Optional Parameters</Area> // <Title> Basic Optional Parameter</Title> // <Description>Basic testing of a simple function with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x = 2) { if (x == 2) return 1; else return 0; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); dynamic d = 1; return tf.Foo(d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional01.optional01 { // <Area>Optional Parameters</Area> // <Title> Basic Optional Parameter</Title> // <Description>Basic testing of a simple function with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x = 2) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); return tf.Foo(); } } //</Code> }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // 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.Threading; using System.Threading.Tasks; using Windows.Storage; using Windows.Storage.Pickers; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Microsoft.Live; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace FileUploadDownload { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { private static readonly string[] scopes = new string[]{ LiveScopes.Signin, LiveScopes.Basic, LiveScopes.SkydriveUpdate }; private LiveAuthClient authClient; private LiveConnectClient liveClient; private CancellationTokenSource cts; private string fileName; public MainPage() { this.InitializeComponent(); CheckPendingBackgroundOperations(); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { this.InitializePage(); } private async void InitializePage() { try { this.authClient = new LiveAuthClient(); LiveLoginResult loginResult = await this.authClient.InitializeAsync(scopes); if (loginResult.Status == LiveConnectSessionStatus.Connected) { if (this.authClient.CanLogout) { this.btnLogin.Content = "Sign Out"; } else { this.btnLogin.Visibility = Visibility.Collapsed; } this.liveClient = new LiveConnectClient(loginResult.Session); } } catch (LiveAuthException) { // TODO: Display the exception } } private async void btnLogin_Click(object sender, RoutedEventArgs e) { try { if (this.btnLogin.Content.ToString() == "Sign In") { LiveLoginResult loginResult = await this.authClient.LoginAsync(scopes); if (loginResult.Status == LiveConnectSessionStatus.Connected) { if (this.authClient.CanLogout) { this.btnLogin.Content = "Sign Out"; } else { this.btnLogin.Visibility = Visibility.Collapsed; } this.liveClient = new LiveConnectClient(loginResult.Session); } } else { this.authClient.Logout(); this.btnLogin.Content = "Sign In"; } } catch (LiveAuthException) { // TODO: Display the exception } } private async void btnSelectUploadFile_Click(object sender, RoutedEventArgs e) { if (this.liveClient == null) { this.ShowMessage("Please sign in first."); return; } if (string.IsNullOrEmpty(this.tbuploadUrl.Text)) { this.ShowMessage("Please specify the upload folder path."); return; } try { string folderPath = this.tbuploadUrl.Text; var picker = new FileOpenPicker { ViewMode = PickerViewMode.Thumbnail, SuggestedStartLocation = PickerLocationId.PicturesLibrary }; picker.FileTypeFilter.Add("*"); StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { this.fileName = file.Name; this.progressBar.Value = 0; var progressHandler = new Progress<LiveOperationProgress>( (progress) => { this.progressBar.Value = progress.ProgressPercentage; }); this.ShowProgress(); this.cts = new CancellationTokenSource(); LiveUploadOperation operation = await this.liveClient.CreateBackgroundUploadAsync( folderPath, file.Name, file, OverwriteOption.Rename); LiveOperationResult result = await operation.StartAsync( this.cts.Token, progressHandler); dynamic fileData = result.Result; string downloadUrl = fileData.id + "/content"; this.tbdownloadUrl.Text = downloadUrl; this.ShowMessage("Upload completed"); } } catch (TaskCanceledException) { this.ShowMessage("User has cancelled the operation."); } catch (Exception exp) { this.ShowMessage(exp.ToString()); } } private async void btnSelectDownloadFile_Click(object sender, RoutedEventArgs e) { if (this.liveClient == null) { this.ShowMessage("Please sign in first."); return; } if (string.IsNullOrEmpty(this.tbdownloadUrl.Text)) { this.ShowMessage("Please specify the link to the file to be downloaded."); return; } try { string fileLink = this.tbdownloadUrl.Text; var roamingSettings = ApplicationData.Current.RoamingSettings; roamingSettings.Values["FileName"] = this.fileName; var appSettingContainer = roamingSettings.CreateContainer( "FileUploadDownload Settings", ApplicationDataCreateDisposition.Always); appSettingContainer.Values[this.fileName] = true; var roamingFolder = ApplicationData.Current.RoamingFolder; var storageDir = await roamingFolder.CreateFolderAsync( "FileUploadDownload sample", CreationCollisionOption.OpenIfExists); var storageFile = await storageDir.CreateFileAsync(this.fileName, CreationCollisionOption.ReplaceExisting); if (storageFile != null) { this.progressBar.Value = 0; var progressHandler = new Progress<LiveOperationProgress>( (progress) => { this.progressBar.Value = progress.ProgressPercentage; }); this.ShowProgress(); this.cts = new CancellationTokenSource(); LiveDownloadOperation operation = await this.liveClient.CreateBackgroundDownloadAsync( fileLink, storageFile); LiveDownloadOperationResult result = await operation.StartAsync(this.cts.Token, progressHandler); this.ShowMessage("Download completed."); } } catch (TaskCanceledException) { this.ShowMessage("User has cancelled the operation."); } catch (Exception exp) { this.ShowMessage(exp.ToString()); } } private void btnCancel_Click(object sender, RoutedEventArgs e) { if (this.cts != null) { this.cts.Cancel(); } } private void ShowProgress() { this.btnCancel.IsEnabled = true; this.tbMessage.Visibility = Visibility.Collapsed; this.progressBar.Value = 0; this.progressBar.Visibility = Visibility.Visible; } private void ShowMessage(string message) { this.btnCancel.IsEnabled = false; this.tbMessage.Text = message; this.tbMessage.Visibility = Visibility.Visible; this.progressBar.Visibility = Visibility.Collapsed; } private async void CheckPendingBackgroundOperations() { var downloadOperations = await Microsoft.Live.LiveConnectClient.GetCurrentBackgroundDownloadsAsync(); foreach (var operation in downloadOperations) { try { var result = await operation.AttachAsync(); // Process download completed results. } catch (Exception ex) { // Handle download error } } var uploadOperations = await Microsoft.Live.LiveConnectClient.GetCurrentBackgroundUploadsAsync(); foreach (var operation in uploadOperations) { try { var result = await operation.AttachAsync(); // Process upload completed results. } catch (Exception ex) { // Handle upload error } } } } }
#region File Description //----------------------------------------------------------------------------- // GameplayScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Threading; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Net; #endregion namespace NetworkStateManagement { /// <summary> /// This screen implements the actual game logic. It is just a /// placeholder to get the idea across: you'll probably want to /// put some more interesting gameplay in here! /// </summary> class GameplayScreen : GameScreen { #region Fields NetworkSession networkSession; ContentManager content; SpriteFont gameFont; Vector2 playerPosition = new Vector2(100, 100); Vector2 enemyPosition = new Vector2(100, 100); Random random = new Random(); float pauseAlpha; #endregion #region Properties /// <summary> /// The logic for deciding whether the game is paused depends on whether /// this is a networked or single player game. If we are in a network session, /// we should go on updating the game even when the user tabs away from us or /// brings up the pause menu, because even though the local player is not /// responding to input, other remote players may not be paused. In single /// player modes, however, we want everything to pause if the game loses focus. /// </summary> new bool IsActive { get { if (networkSession == null) { // Pause behavior for single player games. return base.IsActive; } else { // Pause behavior for networked games. return !IsExiting; } } } #endregion #region Initialization /// <summary> /// Constructor. /// </summary> public GameplayScreen(NetworkSession networkSession) { this.networkSession = networkSession; TransitionOnTime = TimeSpan.FromSeconds(1.5); TransitionOffTime = TimeSpan.FromSeconds(0.5); } /// <summary> /// Load graphics content for the game. /// </summary> public override void LoadContent() { if (content == null) content = new ContentManager(ScreenManager.Game.Services, "Content"); gameFont = content.Load<SpriteFont>("gamefont"); // A real game would probably have more content than this sample, so // it would take longer to load. We simulate that by delaying for a // while, giving you a chance to admire the beautiful loading screen. Thread.Sleep(1000); // once the load has finished, we use ResetElapsedTime to tell the game's // timing mechanism that we have just finished a very long frame, and that // it should not try to catch up. ScreenManager.Game.ResetElapsedTime(); } /// <summary> /// Unload graphics content used by the game. /// </summary> public override void UnloadContent() { content.Unload(); } #endregion #region Update and Draw /// <summary> /// Updates the state of the game. /// </summary> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, false); // Gradually fade in or out depending on whether we are covered by the pause screen. if (coveredByOtherScreen) pauseAlpha = Math.Min(pauseAlpha + 1f / 32, 1); else pauseAlpha = Math.Max(pauseAlpha - 1f / 32, 0); if (IsActive) { // Apply some random jitter to make the enemy move around. const float randomization = 10; enemyPosition.X += (float)(random.NextDouble() - 0.5) * randomization; enemyPosition.Y += (float)(random.NextDouble() - 0.5) * randomization; // Apply a stabilizing force to stop the enemy moving off the screen. Vector2 targetPosition = new Vector2(200, 200); enemyPosition = Vector2.Lerp(enemyPosition, targetPosition, 0.05f); // TODO: this game isn't very fun! You could probably improve // it by inserting something more interesting in this space :-) } // If we are in a network game, check if we should return to the lobby. if ((networkSession != null) && !IsExiting) { if (networkSession.SessionState == NetworkSessionState.Lobby) { LoadingScreen.Load(ScreenManager, true, null, new BackgroundScreen(), new LobbyScreen(networkSession)); } } } /// <summary> /// Lets the game respond to player input. Unlike the Update method, /// this will only be called when the gameplay screen is active. /// </summary> public override void HandleInput(InputState input) { if (input == null) throw new ArgumentNullException("input"); if (ControllingPlayer.HasValue) { // In single player games, handle input for the controlling player. HandlePlayerInput(input, ControllingPlayer.Value); } else if (networkSession != null) { // In network game modes, handle input for all the // local players who are participating in the session. foreach (LocalNetworkGamer gamer in networkSession.LocalGamers) { if (!HandlePlayerInput(input, gamer.SignedInGamer.PlayerIndex)) break; } } } /// <summary> /// Handles input for the specified player. In local game modes, this is called /// just once for the controlling player. In network modes, it can be called /// more than once if there are multiple profiles playing on the local machine. /// Returns true if we should continue to handle input for subsequent players, /// or false if this player has paused the game. /// </summary> bool HandlePlayerInput(InputState input, PlayerIndex playerIndex) { // Look up inputs for the specified player profile. KeyboardState keyboardState = input.CurrentKeyboardStates[(int)playerIndex]; GamePadState gamePadState = input.CurrentGamePadStates[(int)playerIndex]; // The game pauses either if the user presses the pause button, or if // they unplug the active gamepad. This requires us to keep track of // whether a gamepad was ever plugged in, because we don't want to pause // on PC if they are playing with a keyboard and have no gamepad at all! bool gamePadDisconnected = !gamePadState.IsConnected && input.GamePadWasConnected[(int)playerIndex]; if (input.IsPauseGame(playerIndex) || gamePadDisconnected) { ScreenManager.AddScreen(new PauseMenuScreen(networkSession), playerIndex); return false; } // Otherwise move the player position. Vector2 movement = Vector2.Zero; if (keyboardState.IsKeyDown(Keys.Left)) movement.X--; if (keyboardState.IsKeyDown(Keys.Right)) movement.X++; if (keyboardState.IsKeyDown(Keys.Up)) movement.Y--; if (keyboardState.IsKeyDown(Keys.Down)) movement.Y++; Vector2 thumbstick = gamePadState.ThumbSticks.Left; movement.X += thumbstick.X; movement.Y -= thumbstick.Y; if (movement.Length() > 1) movement.Normalize(); playerPosition += movement * 2; return true; } /// <summary> /// Draws the gameplay screen. /// </summary> public override void Draw(GameTime gameTime) { // This game has a blue background. Why? Because! ScreenManager.GraphicsDevice.Clear(ClearOptions.Target, Color.CornflowerBlue, 0, 0); // Our player and enemy are both actually just text strings. SpriteBatch spriteBatch = ScreenManager.SpriteBatch; spriteBatch.Begin(); spriteBatch.DrawString(gameFont, "// TODO", playerPosition, Color.Green); spriteBatch.DrawString(gameFont, "Insert Gameplay Here", enemyPosition, Color.DarkRed); if (networkSession != null) { string message = "Players: " + networkSession.AllGamers.Count; Vector2 messagePosition = new Vector2(100, 480); spriteBatch.DrawString(gameFont, message, messagePosition, Color.White); } spriteBatch.End(); // If the game is transitioning on or off, fade it out to black. if (TransitionPosition > 0 || pauseAlpha > 0) { float alpha = MathHelper.Lerp(1f - TransitionAlpha, 1f, pauseAlpha / 2); ScreenManager.FadeBackBufferToBlack(alpha); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Orleans.Concurrency; using Orleans.Runtime; namespace Orleans.CodeGeneration { internal static class GrainInterfaceUtils { [Serializable] internal class RulesViolationException : ArgumentException { public RulesViolationException(string message, List<string> violations) : base(message) { Violations = violations; } public List<string> Violations { get; private set; } } public static bool IsGrainInterface(Type t) { if (t.GetTypeInfo().IsClass) return false; if (t == typeof(IGrainObserver) || t == typeof(IAddressable) || t == typeof(IGrainExtension)) return false; if (t == typeof(IGrain) || t == typeof(IGrainWithGuidKey) || t == typeof(IGrainWithIntegerKey) || t == typeof(IGrainWithGuidCompoundKey) || t == typeof(IGrainWithIntegerCompoundKey)) return false; if (t == typeof (ISystemTarget)) return false; return typeof (IAddressable).IsAssignableFrom(t); } public static MethodInfo[] GetMethods(Type grainType, bool bAllMethods = true) { var methodInfos = new List<MethodInfo>(); GetMethodsImpl(grainType, grainType, methodInfos); var flags = BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance; if (!bAllMethods) flags |= BindingFlags.DeclaredOnly; MethodInfo[] infos = grainType.GetMethods(flags); IEqualityComparer<MethodInfo> methodComparer = new MethodInfoComparer(); foreach (var methodInfo in infos) if (!methodInfos.Contains(methodInfo, methodComparer)) methodInfos.Add(methodInfo); return methodInfos.ToArray(); } public static string GetParameterName(ParameterInfo info) { var n = info.Name; return string.IsNullOrEmpty(n) ? "arg" + info.Position : n; } public static bool IsTaskType(Type t) { var typeInfo = t.GetTypeInfo(); return t == typeof (Task) || (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition().FullName == "System.Threading.Tasks.Task`1"); } /// <summary> /// Whether method is read-only, i.e. does not modify grain state, /// a method marked with [ReadOnly]. /// </summary> /// <param name="info"></param> /// <returns></returns> public static bool IsReadOnly(MethodInfo info) { return info.GetCustomAttributes(typeof (ReadOnlyAttribute), true).Any(); } public static bool IsAlwaysInterleave(MethodInfo methodInfo) { return methodInfo.GetCustomAttributes(typeof (AlwaysInterleaveAttribute), true).Any(); } public static bool IsUnordered(MethodInfo methodInfo) { var declaringTypeInfo = methodInfo.DeclaringType.GetTypeInfo(); return declaringTypeInfo.GetCustomAttributes(typeof(UnorderedAttribute), true).Any() || (declaringTypeInfo.GetInterfaces().Any( i => i.GetTypeInfo().GetCustomAttributes(typeof(UnorderedAttribute), true).Any() && declaringTypeInfo.GetRuntimeInterfaceMap(i).TargetMethods.Contains(methodInfo))) || IsStatelessWorker(methodInfo); } public static bool IsStatelessWorker(TypeInfo grainTypeInfo) { return grainTypeInfo.GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any() || grainTypeInfo.GetInterfaces() .Any(i => i.GetTypeInfo().GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any()); } public static bool IsStatelessWorker(MethodInfo methodInfo) { var declaringTypeInfo = methodInfo.DeclaringType.GetTypeInfo(); return declaringTypeInfo.GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any() || (declaringTypeInfo.GetInterfaces().Any( i => i.GetTypeInfo().GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any() && declaringTypeInfo.GetRuntimeInterfaceMap(i).TargetMethods.Contains(methodInfo))); } public static Dictionary<int, Type> GetRemoteInterfaces(Type type, bool checkIsGrainInterface = true) { var dict = new Dictionary<int, Type>(); if (IsGrainInterface(type)) dict.Add(GetGrainInterfaceId(type), type); Type[] interfaces = type.GetInterfaces(); foreach (Type interfaceType in interfaces.Where(i => !checkIsGrainInterface || IsGrainInterface(i))) dict.Add(GetGrainInterfaceId(interfaceType), interfaceType); return dict; } public static int ComputeMethodId(MethodInfo methodInfo) { var strMethodId = new StringBuilder(methodInfo.Name + "("); ParameterInfo[] parameters = methodInfo.GetParameters(); bool bFirstTime = true; foreach (ParameterInfo info in parameters) { if (!bFirstTime) strMethodId.Append(","); strMethodId.Append(info.ParameterType.Name); var typeInfo = info.ParameterType.GetTypeInfo(); if (typeInfo.IsGenericType) { Type[] args = typeInfo.GetGenericArguments(); foreach (Type arg in args) strMethodId.Append(arg.Name); } bFirstTime = false; } strMethodId.Append(")"); return Utils.CalculateIdHash(strMethodId.ToString()); } public static int GetGrainInterfaceId(Type grainInterface) { return GetTypeCode(grainInterface); } public static bool IsTaskBasedInterface(Type type) { var methods = type.GetMethods(); // An interface is task-based if it has at least one method that returns a Task or at least one parent that's task-based. return methods.Any(m => IsTaskType(m.ReturnType)) || type.GetInterfaces().Any(IsTaskBasedInterface); } public static bool IsGrainType(Type grainType) { return typeof (IGrain).IsAssignableFrom(grainType); } public static int GetGrainClassTypeCode(Type grainClass) { return GetTypeCode(grainClass); } internal static bool TryValidateInterfaceRules(Type type, out List<string> violations) { violations = new List<string>(); bool success = ValidateInterfaceMethods(type, violations); return success && ValidateInterfaceProperties(type, violations); } internal static void ValidateInterfaceRules(Type type) { List<string> violations; if (!TryValidateInterfaceRules(type, out violations)) { if (ConsoleText.IsConsoleAvailable) { foreach (var violation in violations) ConsoleText.WriteLine("ERROR: " + violation); } throw new RulesViolationException( string.Format("{0} does not conform to the grain interface rules.", type.FullName), violations); } } internal static void ValidateInterface(Type type) { if (!IsGrainInterface(type)) throw new ArgumentException(String.Format("{0} is not a grain interface", type.FullName)); ValidateInterfaceRules(type); } private static bool ValidateInterfaceMethods(Type type, List<string> violations) { bool success = true; MethodInfo[] methods = type.GetMethods(); foreach (MethodInfo method in methods) { if (method.IsSpecialName) continue; if (IsPureObserverInterface(method.DeclaringType)) { if (method.ReturnType != typeof (void)) { success = false; violations.Add(String.Format("Method {0}.{1} must return void because it is defined within an observer interface.", type.FullName, method.Name)); } } else if (!IsTaskType(method.ReturnType)) { success = false; violations.Add(String.Format("Method {0}.{1} must return Task or Task<T> because it is defined within a grain interface.", type.FullName, method.Name)); } ParameterInfo[] parameters = method.GetParameters(); foreach (ParameterInfo parameter in parameters) { if (parameter.IsOut) { success = false; violations.Add(String.Format("Argument {0} of method {1}.{2} is an output parameter. Output parameters are not allowed in grain interfaces.", GetParameterName(parameter), type.FullName, method.Name)); } if (parameter.ParameterType.GetTypeInfo().IsByRef) { success = false; violations.Add(String.Format("Argument {0} of method {1}.{2} is an a reference parameter. Reference parameters are not allowed.", GetParameterName(parameter), type.FullName, method.Name)); } } } return success; } private static bool ValidateInterfaceProperties(Type type, List<string> violations) { bool success = true; PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { success = false; violations.Add(String.Format("Properties are not allowed on grain interfaces: {0}.{1}.", type.FullName, property.Name)); } return success; } /// <summary> /// decide whether the class is derived from Grain /// </summary> private static bool IsPureObserverInterface(Type t) { if (!typeof (IGrainObserver).IsAssignableFrom(t)) return false; if (t == typeof (IGrainObserver)) return true; if (t == typeof (IAddressable)) return false; bool pure = false; foreach (Type iface in t.GetInterfaces()) { if (iface == typeof (IAddressable)) // skip IAddressable that will be in the list regardless continue; if (iface == typeof (IGrainExtension)) // Skip IGrainExtension, it's just a marker that can go on observer or grain interfaces continue; pure = IsPureObserverInterface(iface); if (!pure) return false; } return pure; } private class MethodInfoComparer : IEqualityComparer<MethodInfo> { #region IEqualityComparer<InterfaceInfo> Members public bool Equals(MethodInfo x, MethodInfo y) { var xString = new StringBuilder(x.Name); var yString = new StringBuilder(y.Name); ParameterInfo[] parms = x.GetParameters(); foreach (ParameterInfo info in parms) { var typeInfo = info.ParameterType.GetTypeInfo(); xString.Append(typeInfo.Name); if (typeInfo.IsGenericType) { Type[] args = info.ParameterType.GetGenericArguments(); foreach (Type arg in args) xString.Append(arg.Name); } } parms = y.GetParameters(); foreach (ParameterInfo info in parms) { yString.Append(info.ParameterType.Name); var typeInfo = info.ParameterType.GetTypeInfo(); if (typeInfo.IsGenericType) { Type[] args = info.ParameterType.GetGenericArguments(); foreach (Type arg in args) yString.Append(arg.Name); } } return String.CompareOrdinal(xString.ToString(), yString.ToString()) == 0; } public int GetHashCode(MethodInfo obj) { throw new NotImplementedException(); } #endregion } /// <summary> /// Recurses through interface graph accumulating methods /// </summary> /// <param name="grainType">Grain type</param> /// <param name="serviceType">Service interface type</param> /// <param name="methodInfos">Accumulated </param> private static void GetMethodsImpl(Type grainType, Type serviceType, List<MethodInfo> methodInfos) { Type[] iTypes = GetRemoteInterfaces(serviceType, false).Values.ToArray(); IEqualityComparer<MethodInfo> methodComparer = new MethodInfoComparer(); var typeInfo = grainType.GetTypeInfo(); foreach (Type iType in iTypes) { var mapping = new InterfaceMapping(); if (typeInfo.IsClass) mapping = typeInfo.GetRuntimeInterfaceMap(iType); if (typeInfo.IsInterface || mapping.TargetType == grainType) { foreach (var methodInfo in iType.GetMethods()) { if (typeInfo.IsClass) { var mi = methodInfo; var match = mapping.TargetMethods.Any(info => methodComparer.Equals(mi, info) && info.DeclaringType == grainType); if (match) if (!methodInfos.Contains(mi, methodComparer)) methodInfos.Add(mi); } else if (!methodInfos.Contains(methodInfo, methodComparer)) { methodInfos.Add(methodInfo); } } } } } private static int GetTypeCode(Type grainInterfaceOrClass) { var typeInfo = grainInterfaceOrClass.GetTypeInfo(); var attr = typeInfo.GetCustomAttributes<TypeCodeOverrideAttribute>(false).FirstOrDefault(); if (attr != null && attr.TypeCode > 0) { return attr.TypeCode; } var fullName = TypeUtils.GetTemplatedName( TypeUtils.GetFullName(grainInterfaceOrClass), grainInterfaceOrClass, grainInterfaceOrClass.GetGenericArguments(), t => false); return Utils.CalculateIdHash(fullName); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using DotSpatial.Data; using DotSpatial.NTSExtension; using DotSpatial.NTSExtension.Voronoi; using NetTopologySuite.Geometries; namespace DotSpatial.Analysis { /// <summary> /// This class provides an application programming interface to access the Voronoi calculations that are wrapped by a tool. /// </summary> public static class Voronoi { #region Methods /// <summary> /// The Voronoi Graph calculation creates a delaunay tesselation where /// each point is effectively converted into triangles. /// </summary> /// <param name="points">The points to use for creating the tesselation.</param> /// <returns>The generated line featureset.</returns> public static IFeatureSet DelaunayLines(IFeatureSet points) { double[] vertices = points.Vertex; VoronoiGraph gp = Fortune.ComputeVoronoiGraph(vertices); FeatureSet result = new FeatureSet(); foreach (VoronoiEdge edge in gp.Edges) { Coordinate c1 = edge.RightData.ToCoordinate(); Coordinate c2 = edge.LeftData.ToCoordinate(); LineString ls = new LineString(new[] { c1, c2 }); result.AddFeature(ls); } return result; } /// <summary> /// The Voronoi Graph calculation creates the lines that form a voronoi diagram. /// </summary> /// <param name="points">The points to use for creating the tesselation.</param> /// <returns>An IFeatureSet that is the resulting set of lines in the diagram.</returns> public static IFeatureSet VoronoiLines(IFeatureSet points) { double[] vertices = points.Vertex; VoronoiGraph gp = Fortune.ComputeVoronoiGraph(vertices); HandleBoundaries(gp, points.Extent.ToEnvelope()); FeatureSet result = new FeatureSet(); foreach (VoronoiEdge edge in gp.Edges) { Coordinate c1 = edge.VVertexA.ToCoordinate(); Coordinate c2 = edge.VVertexB.ToCoordinate(); LineString ls = new LineString(new[] { c1, c2 }); result.AddFeature(ls); } return result; } /// <summary> /// The Voronoi Graph calculation creates the lines that form a voronoi diagram. /// </summary> /// <param name="points">The points to use for creating the tesselation.</param> /// <param name="cropToExtent">The normal polygons have sharp angles that extend like stars. /// Cropping will ensure that the original featureset extent plus a small extra buffer amount /// is the outer extent of the polygons. Errors seem to occur if the exact extent is used.</param> /// <returns>The IFeatureSet containing the lines that were formed in the diagram.</returns> public static IFeatureSet VoronoiPolygons(IFeatureSet points, bool cropToExtent) { IFeatureSet fs = new FeatureSet(); VoronoiPolygons(points, fs, cropToExtent); return fs; } /// <summary> /// The Voronoi Graph calculation creates the lines that form a voronoi diagram. /// </summary> /// <param name="points">The points to use for creating the tesselation.</param> /// <param name="result">The output featureset.</param> /// <param name="cropToExtent">The normal polygons have sharp angles that extend like stars. /// Cropping will ensure that the original featureset extent plus a small extra buffer amount /// is the outer extent of the polygons. Errors seem to occur if the exact extent is used.</param> public static void VoronoiPolygons(IFeatureSet points, IFeatureSet result, bool cropToExtent) { double[] vertices = points.Vertex; VoronoiGraph gp = Fortune.ComputeVoronoiGraph(vertices); Extent ext = points.Extent; ext.ExpandBy(ext.Width / 100, ext.Height / 100); Envelope env = ext.ToEnvelope(); Polygon bounds = env.ToPolygon(); // Convert undefined coordinates to a defined coordinate. HandleBoundaries(gp, env); for (int i = 0; i < vertices.Length / 2; i++) { List<VoronoiEdge> myEdges = new List<VoronoiEdge>(); Vector2 v = new Vector2(vertices, i * 2); foreach (VoronoiEdge edge in gp.Edges) { if (!v.Equals(edge.RightData) && !v.Equals(edge.LeftData)) { continue; } myEdges.Add(edge); } List<Coordinate> coords = new List<Coordinate>(); VoronoiEdge firstEdge = myEdges[0]; coords.Add(firstEdge.VVertexA.ToCoordinate()); coords.Add(firstEdge.VVertexB.ToCoordinate()); Vector2 previous = firstEdge.VVertexB; myEdges.Remove(myEdges[0]); Vector2 start = firstEdge.VVertexA; while (myEdges.Count > 0) { for (int j = 0; j < myEdges.Count; j++) { VoronoiEdge edge = myEdges[j]; if (edge.VVertexA.Equals(previous)) { previous = edge.VVertexB; Coordinate c = previous.ToCoordinate(); coords.Add(c); myEdges.Remove(edge); break; } // couldn't match by adding to the end, so try adding to the beginning if (edge.VVertexB.Equals(start)) { start = edge.VVertexA; coords.Insert(0, start.ToCoordinate()); myEdges.Remove(edge); break; } // I don't like the reverse situation, but it seems necessary. if (edge.VVertexB.Equals(previous)) { previous = edge.VVertexA; Coordinate c = previous.ToCoordinate(); coords.Add(c); myEdges.Remove(edge); break; } if (edge.VVertexA.Equals(start)) { start = edge.VVertexB; coords.Insert(0, start.ToCoordinate()); myEdges.Remove(edge); break; } } } for (int j = 0; j < coords.Count; j++) { Coordinate cA = coords[j]; // Remove NAN values if (double.IsNaN(cA.X) || double.IsNaN(cA.Y)) { coords.Remove(cA); } // Remove duplicate coordinates for (int k = j + 1; k < coords.Count; k++) { Coordinate cB = coords[k]; if (cA.Equals2D(cB)) { coords.Remove(cB); } } } foreach (Coordinate coord in coords) { if (double.IsNaN(coord.X) || double.IsNaN(coord.Y)) { coords.Remove(coord); } } if (coords.Count <= 2) { continue; } Polygon pg = new Polygon(new LinearRing(coords.ToArray())); if (cropToExtent) { try { Geometry g = pg.Intersection(bounds); Polygon p = g as Polygon; if (p != null) { Feature f = new Feature(p, result); f.CopyAttributes(points.Features[i]); } } catch (Exception) { Feature f = new Feature(pg, result); f.CopyAttributes(points.Features[i]); } } else { Feature f = new Feature(pg, result); f.CopyAttributes(points.Features[i]); } } } /// <summary> /// The original algorithm simply allows edges that have one defined point and /// another "NAN" point. Simply excluding the not a number coordinates fails /// to preserve the known direction of the ray. We only need to extend this /// long enough to encounter the bounding box, not infinity. /// </summary> /// <param name="graph">The VoronoiGraph with the edge list.</param> /// <param name="bounds">The polygon bounding the datapoints.</param> private static void HandleBoundaries(VoronoiGraph graph, Envelope bounds) { List<LineString> boundSegments = new List<LineString>(); List<VoronoiEdge> unboundEdges = new List<VoronoiEdge>(); // Identify bound edges for intersection testing foreach (VoronoiEdge edge in graph.Edges) { if (edge.VVertexA.ContainsNan() || edge.VVertexB.ContainsNan()) { unboundEdges.Add(edge); continue; } boundSegments.Add(new LineString(new[] { edge.VVertexA.ToCoordinate(), edge.VVertexB.ToCoordinate() })); } // calculate a length to extend a ray to look for intersections Envelope env = bounds; double h = env.Height; double w = env.Width; double len = Math.Sqrt((w * w) + (h * h)); // len is now long enough to pass entirely through the dataset no matter where it starts foreach (VoronoiEdge edge in unboundEdges) { // the unbound line passes thorugh start Coordinate start = edge.VVertexB.ContainsNan() ? edge.VVertexA.ToCoordinate() : edge.VVertexB.ToCoordinate(); // the unbound line should have a direction normal to the line joining the left and right source points double dx = edge.LeftData.X - edge.RightData.X; double dy = edge.LeftData.Y - edge.RightData.Y; double l = Math.Sqrt((dx * dx) + (dy * dy)); // the slope of the bisector between left and right double sx = -dy / l; double sy = dx / l; Coordinate center = bounds.Centre; if ((start.X > center.X && start.Y > center.Y) || (start.X < center.X && start.Y < center.Y)) { sx = dy / l; sy = -dx / l; } Coordinate end1 = new Coordinate(start.X + (len * sx), start.Y + (len * sy)); Coordinate end2 = new Coordinate(start.X - (sx * len), start.Y - (sy * len)); Coordinate end = (end1.Distance(center) < end2.Distance(center)) ? end2 : end1; if (bounds.Contains(end)) { end = new Coordinate(start.X - (sx * len), start.Y - (sy * len)); } if (edge.VVertexA.ContainsNan()) { edge.VVertexA = new Vector2(end.X, end.Y); } else { edge.VVertexB = new Vector2(end.X, end.Y); } } } #endregion } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #define DEBUG #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ namespace NLog.UnitTests.Common { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using NLog.Common; using Xunit; using Xunit.Extensions; public class InternalLoggerTests_Trace : NLogTestBase { [Theory] [InlineData(null, null)] [InlineData(false, null)] [InlineData(null, false)] [InlineData(false, false)] public void ShouldNotLogInternalWhenLogToTraceIsDisabled(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Trace, internalLogToTrace, logToTrace); InternalLogger.Trace("Logger1 Hello"); Assert.Equal(0, mockTraceListener.Messages.Count); } [Theory] [InlineData(null, null)] [InlineData(false, null)] [InlineData(null, false)] [InlineData(false, false)] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldNotLogInternalWhenLogLevelIsOff(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Off, internalLogToTrace, logToTrace); InternalLogger.Trace("Logger1 Hello"); Assert.Equal(0, mockTraceListener.Messages.Count); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void VerifyInternalLoggerLevelFilter(bool? internalLogToTrace, bool? logToTrace) { foreach (LogLevel logLevelConfig in LogLevel.AllLevels) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(logLevelConfig, internalLogToTrace, logToTrace); List<string> expected = new List<string>(); string input = "Logger1 Hello"; expected.Add(input); InternalLogger.Trace(input); InternalLogger.Debug(input); InternalLogger.Info(input); InternalLogger.Warn(input); InternalLogger.Error(input); InternalLogger.Fatal(input); input += "No.{0}"; expected.Add(string.Format(input, 1)); InternalLogger.Trace(input, 1); InternalLogger.Debug(input, 1); InternalLogger.Info(input, 1); InternalLogger.Warn(input, 1); InternalLogger.Error(input, 1); InternalLogger.Fatal(input, 1); input += ", We come in {1}"; expected.Add(string.Format(input, 1, "Peace")); InternalLogger.Trace(input, 1, "Peace"); InternalLogger.Debug(input, 1, "Peace"); InternalLogger.Info(input, 1, "Peace"); InternalLogger.Warn(input, 1, "Peace"); InternalLogger.Error(input, 1, "Peace"); InternalLogger.Fatal(input, 1, "Peace"); input += " and we are {2} to god"; expected.Add(string.Format(input, 1, "Peace", true)); InternalLogger.Trace(input, 1, "Peace", true); InternalLogger.Debug(input, 1, "Peace", true); InternalLogger.Info(input, 1, "Peace", true); InternalLogger.Warn(input, 1, "Peace", true); InternalLogger.Error(input, 1, "Peace", true); InternalLogger.Fatal(input, 1, "Peace", true); input += ", Please don't {3}"; expected.Add(string.Format(input, 1, "Peace", true, null)); InternalLogger.Trace(input, 1, "Peace", true, null); InternalLogger.Debug(input, 1, "Peace", true, null); InternalLogger.Info(input, 1, "Peace", true, null); InternalLogger.Warn(input, 1, "Peace", true, null); InternalLogger.Error(input, 1, "Peace", true, null); InternalLogger.Fatal(input, 1, "Peace", true, null); input += " the {4}"; expected.Add(string.Format(input, 1, "Peace", true, null, "Messenger")); InternalLogger.Trace(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Debug(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Info(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Warn(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Error(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Fatal(input, 1, "Peace", true, null, "Messenger"); Assert.Equal(expected.Count * (LogLevel.Fatal.Ordinal - logLevelConfig.Ordinal + 1), mockTraceListener.Messages.Count); for (int i = 0; i < expected.Count; ++i) { int msgCount = LogLevel.Fatal.Ordinal - logLevelConfig.Ordinal + 1; for (int j = 0; j < msgCount; ++j) { Assert.True(mockTraceListener.Messages.First().Contains(expected[i])); mockTraceListener.Messages.RemoveAt(0); } } Assert.Equal(0, mockTraceListener.Messages.Count); } } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsTrace(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Trace, internalLogToTrace, logToTrace); InternalLogger.Trace("Logger1 Hello"); Assert.Equal(1, mockTraceListener.Messages.Count); Assert.Equal("NLog: Trace Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsDebug(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Debug, internalLogToTrace, logToTrace); InternalLogger.Debug("Logger1 Hello"); Assert.Equal(1, mockTraceListener.Messages.Count); Assert.Equal("NLog: Debug Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsInfo(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Info, internalLogToTrace, logToTrace); InternalLogger.Info("Logger1 Hello"); Assert.Equal(1, mockTraceListener.Messages.Count); Assert.Equal("NLog: Info Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsWarn(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Warn, internalLogToTrace, logToTrace); InternalLogger.Warn("Logger1 Hello"); Assert.Equal(1, mockTraceListener.Messages.Count); Assert.Equal("NLog: Warn Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsError(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Error, internalLogToTrace, logToTrace); InternalLogger.Error("Logger1 Hello"); Assert.Equal(1, mockTraceListener.Messages.Count); Assert.Equal("NLog: Error Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsFatal(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Fatal, internalLogToTrace, logToTrace); InternalLogger.Fatal("Logger1 Hello"); Assert.Equal(1, mockTraceListener.Messages.Count); Assert.Equal("NLog: Fatal Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Fact(Skip = "This test's not working - explenation is in documentation: https://msdn.microsoft.com/pl-pl/library/system.stackoverflowexception(v=vs.110).aspx#Anchor_5. To clarify if StackOverflowException should be thrown.")] public void ShouldThrowStackOverFlowExceptionWhenUsingNLogTraceListener() { SetupTestConfiguration<NLogTraceListener>(LogLevel.Trace, true, null); Assert.Throws<StackOverflowException>(() => Trace.WriteLine("StackOverFlowException")); } /// <summary> /// Helper method to setup tests configuration /// </summary> /// <param name="logLevel">The <see cref="NLog.LogLevel"/> for the log event.</param> /// <param name="internalLogToTrace">internalLogToTrace XML attribute value. If <c>null</c> attribute is omitted.</param> /// <param name="logToTrace">Value of <see cref="InternalLogger.LogToTrace"/> property. If <c>null</c> property is not set.</param> /// <returns><see cref="TraceListener"/> instance.</returns> private T SetupTestConfiguration<T>(LogLevel logLevel, bool? internalLogToTrace, bool? logToTrace) where T : TraceListener { var internalLogToTraceAttribute = ""; if (internalLogToTrace.HasValue) { internalLogToTraceAttribute = string.Format(" internalLogToTrace='{0}'", internalLogToTrace.Value); } var xmlConfiguration = string.Format(XmlConfigurationFormat, logLevel, internalLogToTraceAttribute); LogManager.Configuration = CreateConfigurationFromString(xmlConfiguration); InternalLogger.IncludeTimestamp = false; if (logToTrace.HasValue) { InternalLogger.LogToTrace = logToTrace.Value; } T traceListener; if (typeof (T) == typeof (MockTraceListener)) { traceListener = CreateMockTraceListener() as T; } else { traceListener = CreateNLogTraceListener() as T; } Trace.Listeners.Clear(); if (traceListener == null) { return null; } Trace.Listeners.Add(traceListener); return traceListener; } private const string XmlConfigurationFormat = @"<nlog internalLogLevel='{0}'{1}> <targets> <target name='debug' type='Debug' layout='${{logger}} ${{level}} ${{message}}'/> </targets> <rules> <logger name='*' level='{0}' writeTo='debug'/> </rules> </nlog>"; /// <summary> /// Creates <see cref="MockTraceListener"/> instance. /// </summary> /// <returns><see cref="MockTraceListener"/> instance.</returns> private static MockTraceListener CreateMockTraceListener() { return new MockTraceListener(); } /// <summary> /// Creates <see cref="NLogTraceListener"/> instance. /// </summary> /// <returns><see cref="NLogTraceListener"/> instance.</returns> private static NLogTraceListener CreateNLogTraceListener() { return new NLogTraceListener {Name = "Logger1", ForceLogLevel = LogLevel.Trace}; } private class MockTraceListener : TraceListener { internal readonly List<string> Messages = new List<string>(); /// <summary> /// When overridden in a derived class, writes the specified message to the listener you create in the derived class. /// </summary> /// <param name="message">A message to write. </param> public override void Write(string message) { Messages.Add(message); } /// <summary> /// When overridden in a derived class, writes a message to the listener you create in the derived class, followed by a line terminator. /// </summary> /// <param name="message">A message to write. </param> public override void WriteLine(string message) { Messages.Add(message + Environment.NewLine); } } } } #endif
using System; using AutoMapper.UnitTests; using Should; using Xunit; namespace AutoMapper.Tests { public class EnumMappingFixture { public EnumMappingFixture() { Cleanup(); } public void Cleanup() { Mapper.Reset(); } [Fact] public void ShouldMapSharedEnum() { Mapper.CreateMap<Order, OrderDto>(); var order = new Order { Status = Status.InProgress }; var dto = Mapper.Map<Order, OrderDto>(order); dto.Status.ShouldEqual(Status.InProgress); } [Fact] public void ShouldMapToUnderlyingType() { Mapper.CreateMap<Order, OrderDtoInt>(); var order = new Order { Status = Status.InProgress }; var dto = Mapper.Map<Order, OrderDtoInt>(order); dto.Status.ShouldEqual(1); } [Fact] public void ShouldMapToStringType() { Mapper.CreateMap<Order, OrderDtoString>(); var order = new Order { Status = Status.InProgress }; var dto = Mapper.Map<Order, OrderDtoString>(order); dto.Status.ShouldEqual("InProgress"); } [Fact] public void ShouldMapFromUnderlyingType() { Mapper.CreateMap<OrderDtoInt, Order>(); var order = new OrderDtoInt { Status = 1 }; var dto = Mapper.Map<OrderDtoInt, Order>(order); dto.Status.ShouldEqual(Status.InProgress); } [Fact] public void ShouldMapFromStringType() { Mapper.CreateMap<OrderDtoString, Order>(); var order = new OrderDtoString { Status = "InProgress" }; var dto = Mapper.Map<OrderDtoString, Order>(order); dto.Status.ShouldEqual(Status.InProgress); } [Fact] public void ShouldMapEnumByMatchingNames() { Mapper.CreateMap<Order, OrderDtoWithOwnStatus>(); var order = new Order { Status = Status.InProgress }; var dto = Mapper.Map<Order, OrderDtoWithOwnStatus>(order); dto.Status.ShouldEqual(StatusForDto.InProgress); } [Fact] public void ShouldMapEnumByMatchingValues() { Mapper.CreateMap<Order, OrderDtoWithOwnStatus>(); var order = new Order { Status = Status.InProgress }; var dto = Mapper.Map<Order, OrderDtoWithOwnStatus>(order); dto.Status.ShouldEqual(StatusForDto.InProgress); } [Fact] public void ShouldMapSharedNullableEnum() { Mapper.CreateMap<OrderWithNullableStatus, OrderDtoWithNullableStatus>(); var order = new OrderWithNullableStatus { Status = Status.InProgress }; var dto = Mapper.Map<OrderWithNullableStatus, OrderDtoWithNullableStatus>(order); dto.Status.ShouldEqual(Status.InProgress); } [Fact] public void ShouldMapNullableEnumByMatchingValues() { Mapper.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>(); var order = new OrderWithNullableStatus { Status = Status.InProgress }; var dto = Mapper.Map<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>(order); dto.Status.ShouldEqual(StatusForDto.InProgress); } [Fact] public void ShouldMapNullableEnumToNullWhenSourceEnumIsNullAndDestinationWasNotNull() { Mapper.Initialize(cfg => { cfg.AllowNullDestinationValues = true; cfg.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>(); }); var dto = new OrderDtoWithOwnNullableStatus() { Status = StatusForDto.Complete }; var order = new OrderWithNullableStatus { Status = null }; Mapper.Map(order, dto); dto.Status.ShouldBeNull(); } [Fact] public void ShouldMapNullableEnumToNullWhenSourceEnumIsNull() { Mapper.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>(); var order = new OrderWithNullableStatus { Status = null }; var dto = Mapper.Map<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>(order); dto.Status.ShouldBeNull(); } [Fact] public void ShouldMapEnumUsingCustomResolver() { Mapper.CreateMap<Order, OrderDtoWithOwnStatus>() .ForMember(dto => dto.Status, options => options .ResolveUsing<DtoStatusValueResolver>()); var order = new Order { Status = Status.InProgress }; var mappedDto = Mapper.Map<Order, OrderDtoWithOwnStatus>(order); mappedDto.Status.ShouldEqual(StatusForDto.InProgress); } [Fact] public void ShouldMapEnumUsingGenericEnumResolver() { Mapper.CreateMap<Order, OrderDtoWithOwnStatus>() .ForMember(dto => dto.Status, options => options .ResolveUsing<EnumValueResolver<Status, StatusForDto>>() .FromMember(m => m.Status)); var order = new Order { Status = Status.InProgress }; var mappedDto = Mapper.Map<Order, OrderDtoWithOwnStatus>(order); mappedDto.Status.ShouldEqual(StatusForDto.InProgress); } [Fact] public void ShouldMapEnumWithInvalidValue() { Mapper.CreateMap<Order, OrderDtoWithOwnStatus>(); var order = new Order { Status = 0 }; var dto = Mapper.Map<Order, OrderDtoWithOwnStatus>(order); var expected = (StatusForDto)0; dto.Status.ShouldEqual(expected); } public enum Status { InProgress = 1, Complete = 2 } public enum StatusForDto { InProgress = 1, Complete = 2 } public class Order { public Status Status { get; set; } } public class OrderDto { public Status Status { get; set; } } public class OrderDtoInt { public int Status { get; set; } } public class OrderDtoString { public string Status { get; set; } } public class OrderDtoWithOwnStatus { public StatusForDto Status { get; set; } } public class OrderWithNullableStatus { public Status? Status { get; set; } } public class OrderDtoWithNullableStatus { public Status? Status { get; set; } } public class OrderDtoWithOwnNullableStatus { public StatusForDto? Status { get; set; } } public class DtoStatusValueResolver : IValueResolver { public ResolutionResult Resolve(ResolutionResult source) { return source.New(((Order)source.Value).Status); } } public class EnumValueResolver<TInputEnum, TOutputEnum> : IValueResolver { public ResolutionResult Resolve(ResolutionResult source) { return source.New(((TOutputEnum)Enum.Parse(typeof(TOutputEnum), Enum.GetName(typeof(TInputEnum), source.Value), false))); } } } public class When_mapping_from_a_null_object_with_an_enum { public When_mapping_from_a_null_object_with_an_enum() { SetUp(); } public void SetUp() { Mapper.AllowNullDestinationValues = false; Mapper.CreateMap<SourceClass, DestinationClass>(); } public enum EnumValues { One, Two, Three } public class DestinationClass { public EnumValues Values { get; set; } } public class SourceClass { public EnumValues Values { get; set; } } [Fact] public void Should_set_the_target_enum_to_the_default_value() { SourceClass sourceClass = null; var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass); dest.Values.ShouldEqual(default(EnumValues)); } } public class When_mapping_from_a_null_object_with_an_enum_on_a_nullable_enum { public When_mapping_from_a_null_object_with_an_enum_on_a_nullable_enum() { SetUp(); } public void SetUp() { Mapper.AllowNullDestinationValues = false; Mapper.CreateMap<SourceClass, DestinationClass>(); } public enum EnumValues { One, Two, Three } public class DestinationClass { public EnumValues? Values { get; set; } } public class SourceClass { public EnumValues Values { get; set; } } [Fact] public void Should_set_the_target_enum_to_null() { SourceClass sourceClass = null; var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass); dest.Values.ShouldEqual(null); } } public class When_mapping_from_a_null_object_with_a_nullable_enum { public When_mapping_from_a_null_object_with_a_nullable_enum() { SetUp(); } public void SetUp() { Mapper.AllowNullDestinationValues = false; Mapper.CreateMap<SourceClass, DestinationClass>(); } public enum EnumValues { One, Two, Three } public class DestinationClass { public EnumValues Values { get; set; } } public class SourceClass { public EnumValues? Values { get; set; } } [Fact] public void Should_set_the_target_enum_to_the_default_value() { SourceClass sourceClass = null; var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass); dest.Values.ShouldEqual(default(EnumValues)); } } public class When_mapping_from_a_null_object_with_a_nullable_enum_as_string : AutoMapperSpecBase { protected override void Establish_context() { Mapper.CreateMap<SourceClass, DestinationClass>(); } public enum EnumValues { One, Two, Three } public class DestinationClass { public EnumValues Values1 { get; set; } public EnumValues? Values2 { get; set; } public EnumValues Values3 { get; set; } } public class SourceClass { public string Values1 { get; set; } public string Values2 { get; set; } public string Values3 { get; set; } } [Fact] public void Should_set_the_target_enum_to_the_default_value() { var sourceClass = new SourceClass(); var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass); dest.Values1.ShouldEqual(default(EnumValues)); } [Fact] public void Should_set_the_target_nullable_to_null() { var sourceClass = new SourceClass(); var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass); dest.Values2.ShouldBeNull(); } [Fact] public void Should_set_the_target_empty_to_null() { var sourceClass = new SourceClass { Values3 = "" }; var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass); dest.Values3.ShouldEqual(default(EnumValues)); } } public class When_mapping_a_flags_enum : AutoMapperSpecBase { private DestinationFlags _result; [Flags] private enum SourceFlags { None = 0, One = 1, Two = 2, Four = 4, Eight = 8 } [Flags] private enum DestinationFlags { None = 0, One = 1, Two = 2, Four = 4, Eight = 8 } protected override void Establish_context() { // No type map needed } protected override void Because_of() { _result = Mapper.Map<SourceFlags, DestinationFlags>(SourceFlags.One | SourceFlags.Four | SourceFlags.Eight); } [Fact] public void Should_include_all_source_enum_values() { _result.ShouldEqual(DestinationFlags.One | DestinationFlags.Four | DestinationFlags.Eight); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using CoreFXTestLibrary; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace System.Threading.Tasks.Test { public static class ParallelLoopResultTests { [Fact] public static void ForPLRTests() { ParallelLoopResult plr = Parallel.For(1, 0, delegate (int i, ParallelLoopState ps) { if (i == 10) ps.Stop(); }); PLRcheck(plr, "For-Empty", true, null); plr = Parallel.For(0, 100, delegate (int i, ParallelLoopState ps) { //Thread.Sleep(20); if (i == 10) ps.Stop(); }); PLRcheck(plr, "For-Stop", false, null); plr = Parallel.For(0, 100, delegate (int i, ParallelLoopState ps) { //Thread.Sleep(20); if (i == 10) ps.Break(); }); PLRcheck(plr, "For-Break", false, 10); plr = Parallel.For(0, 100, delegate (int i, ParallelLoopState ps) { //Thread.Sleep(20); }); PLRcheck(plr, "For-Completion", true, null); } [Fact] public static void ForPLR64Tests() { ParallelLoopResult plr = Parallel.For(1L, 0L, delegate (long i, ParallelLoopState ps) { if (i == 10) ps.Stop(); }); PLRcheck(plr, "For64-Empty", true, null); plr = Parallel.For(0L, 100L, delegate (long i, ParallelLoopState ps) { //Thread.Sleep(20); if (i == 10) ps.Stop(); }); PLRcheck(plr, "For64-Stop", false, null); plr = Parallel.For(0L, 100L, delegate (long i, ParallelLoopState ps) { //Thread.Sleep(20); if (i == 10) ps.Break(); }); PLRcheck(plr, "For64-Break", false, 10); plr = Parallel.For(0L, 100L, delegate (long i, ParallelLoopState ps) { //Thread.Sleep(20); }); PLRcheck(plr, "For64-Completion", true, null); } [Fact] public static void ForEachPLRTests() { Dictionary<string, string> dict = new Dictionary<string, string>(); ParallelLoopResult plr = Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps) { if (kvp.Value.Equals("Purple")) ps.Stop(); }); PLRcheck(plr, "ForEach-Empty", true, null); dict.Add("Apple", "Red"); dict.Add("Banana", "Yellow"); dict.Add("Pear", "Green"); dict.Add("Plum", "Red"); dict.Add("Grape", "Green"); dict.Add("Cherry", "Red"); dict.Add("Carrot", "Orange"); dict.Add("Eggplant", "Purple"); plr = Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps) { if (kvp.Value.Equals("Purple")) ps.Stop(); }); PLRcheck(plr, "ForEach-Stop", false, null); plr = Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps) { if (kvp.Value.Equals("Purple")) ps.Break(); }); PLRcheck(plr, "ForEach-Break", false, 7); // right?? plr = Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps) { //if(kvp.Value.Equals("Purple")) ps.Stop(); }); PLRcheck(plr, "ForEach-Complete", true, null); } [Fact] public static void PartitionerForEachPLRTests() { // // Now try testing Partitionable, OrderablePartitionable // List<int> intlist = new List<int>(); for (int i = 0; i < 20; i++) intlist.Add(i * i); MyPartitioner<int> mp = new MyPartitioner<int>(intlist); ParallelLoopResult plr = Parallel.ForEach(mp, delegate (int item, ParallelLoopState ps) { if (item == 0) ps.Stop(); }); PLRcheck(plr, "Partitioner-ForEach-Stop", false, null); plr = Parallel.ForEach(mp, delegate (int item, ParallelLoopState ps) { }); PLRcheck(plr, "Partitioner-ForEach-Complete", true, null); } [Fact] public static void OrderablePartitionerForEachTests() { List<int> intlist = new List<int>(); for (int i = 0; i < 20; i++) intlist.Add(i * i); OrderablePartitioner<int> mop = Partitioner.Create(intlist, true); ParallelLoopResult plr = Parallel.ForEach(mop, delegate (int item, ParallelLoopState ps, long index) { if (index == 2) ps.Stop(); }); PLRcheck(plr, "OrderablePartitioner-ForEach-Stop", false, null); plr = Parallel.ForEach(mop, delegate (int item, ParallelLoopState ps, long index) { if (index == 2) ps.Break(); }); PLRcheck(plr, "OrderablePartitioner-ForEach-Break", false, 2); plr = Parallel.ForEach(mop, delegate (int item, ParallelLoopState ps, long index) { }); PLRcheck(plr, "OrderablePartitioner-ForEach-Complete", true, null); } private static void PLRcheck(ParallelLoopResult plr, string ttype, bool shouldComplete, Int32? expectedLBI) { if ((plr.IsCompleted == shouldComplete) && (plr.LowestBreakIteration == expectedLBI)) { } else { string biString = "(null)"; if (plr.LowestBreakIteration != null) biString = plr.LowestBreakIteration.ToString(); Assert.False(true, String.Format("PLRcheck {0} test: >> Failed. IsCompleted={1}, LowestBreakIteration={2}", ttype, plr.IsCompleted, biString)); } } // Generalized test for testing For-loop results private static void ForPLRTest( Action<int, ParallelLoopState> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { ForPLRTest(body, new ParallelOptions(), desc, excExpected, shouldComplete, shouldStop, shouldBreak, false); } private static void ForPLRTest( Action<int, ParallelLoopState> body, ParallelOptions parallelOptions, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak, bool shouldCancel) { try { ParallelLoopResult plr = Parallel.For(0, 1, parallelOptions, body); if (excExpected || shouldCancel) { Logger.LogInformation("For-PLRTest -- {0} > failed. Expected an exception.", desc); } else if ((plr.IsCompleted != shouldComplete) || (shouldStop && (plr.LowestBreakIteration != null)) || (shouldBreak && (plr.LowestBreakIteration == null))) { string LBIval = "null"; if (plr.LowestBreakIteration != null) LBIval = plr.LowestBreakIteration.Value.ToString(); Logger.LogInformation("For-PLRTest -- {0} > failed. Complete={1}, LBI={2}", desc, plr.IsCompleted, LBIval); } } catch (OperationCanceledException oce) { if (!shouldCancel) { Logger.LogInformation("For-PLRTest -- {0}: > FAILED -- got unexpected OCE: {1}.", desc, oce.Message); } } catch (AggregateException e) { if (!excExpected) { Logger.LogInformation("For-PLRTest -- {0}: > failed -- unexpected exception from loop. Error: {1}", desc, e.ToString()); } } } // ... and a 64-bit version private static void For64PLRTest( Action<long, ParallelLoopState> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { For64PLRTest(body, new ParallelOptions(), desc, excExpected, shouldComplete, shouldStop, shouldBreak, false); } private static void For64PLRTest( Action<long, ParallelLoopState> body, ParallelOptions parallelOptions, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak, bool shouldCancel) { try { ParallelLoopResult plr = Parallel.For(0L, 1L, parallelOptions, body); if (excExpected || shouldCancel) { Logger.LogInformation("For64-PLRTest -- {0} > failed. Expected an exception.", desc); } else if ((plr.IsCompleted != shouldComplete) || (shouldStop && (plr.LowestBreakIteration != null)) || (shouldBreak && (plr.LowestBreakIteration == null))) { string LBIval = "null"; if (plr.LowestBreakIteration != null) LBIval = plr.LowestBreakIteration.Value.ToString(); Logger.LogInformation("For64-PLRTest -- {0} > failed. Complete={1}, LBI={2}", desc, plr.IsCompleted, LBIval); } } catch (OperationCanceledException) { if (!shouldCancel) { Logger.LogInformation("For64-PLRTest -- {0} > FAILED -- got unexpected OCE.", desc); } } catch (AggregateException e) { if (!excExpected) { Logger.LogInformation("For64-PLRTest -- {0}: > failed -- unexpected exception from loop. Error: {1} ", desc, e.ToString()); } } } // Generalized test for testing ForEach-loop results private static void ForEachPLRTest( Action<KeyValuePair<int, string>, ParallelLoopState> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { ForEachPLRTest(body, new ParallelOptions(), desc, excExpected, shouldComplete, shouldStop, shouldBreak, false); } private static void ForEachPLRTest( Action<KeyValuePair<int, string>, ParallelLoopState> body, ParallelOptions parallelOptions, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak, bool shouldCancel) { Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(1, "one"); try { ParallelLoopResult plr = Parallel.ForEach(dict, parallelOptions, body); if (excExpected || shouldCancel) { Logger.LogInformation("ForEach-PLRTest -- {0} > failed. Expected an exception.", desc); } else if ((plr.IsCompleted != shouldComplete) || (shouldStop && (plr.LowestBreakIteration != null)) || (shouldBreak && (plr.LowestBreakIteration == null))) { Logger.LogInformation("ForEach-PLRTest -- {0} > failed. Complete={1}, LBI={2}", desc, plr.IsCompleted, plr.LowestBreakIteration); } } catch (OperationCanceledException oce) { if (!shouldCancel) { Logger.LogInformation("ForEach-PLRTest -- {0} > FAILED -- got unexpected OCE. Exception: {1}", desc, oce); } } catch (AggregateException e) { if (!excExpected) { Logger.LogInformation("ForEach-PLRTest -- {0} > failed -- unexpected exception from loop. Exception: {1}", desc, e); } } } // Generalized test for testing Partitioner ForEach-loop results private static void PartitionerForEachPLRTest( Action<int, ParallelLoopState> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { List<int> list = new List<int>(); for (int i = 0; i < 20; i++) list.Add(i); MyPartitioner<int> mp = new MyPartitioner<int>(list); try { ParallelLoopResult plr = Parallel.ForEach(mp, body); if (excExpected) { Logger.LogInformation("PartitionerForEach-PLRTest -- {0}: > failed. Expected an exception.", desc); } else if ((plr.IsCompleted != shouldComplete) || (shouldStop && (plr.LowestBreakIteration != null)) || (shouldBreak && (plr.LowestBreakIteration == null))) { Logger.LogInformation("PartitionerForEach-PLRTest -- {0} > failed. Complete={1}, LBI={2}", desc, plr.IsCompleted, plr.LowestBreakIteration); } } catch (AggregateException e) { if (!excExpected) { Logger.LogInformation("PartitionerForEach-PLRTest -- {0} > failed -- unexpected exception from loop. Exception: {1}", desc, e); } } } // Generalized test for testing OrderablePartitioner ForEach-loop results private static void OrderablePartitionerForEachPLRTest( Action<int, ParallelLoopState, long> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { List<int> list = new List<int>(); for (int i = 0; i < 20; i++) list.Add(i); OrderablePartitioner<int> mop = Partitioner.Create(list, true); try { ParallelLoopResult plr = Parallel.ForEach(mop, body); if (excExpected) { Logger.LogInformation("OrderablePartitionerForEach-PLRTest -- {0}: > failed. Expected an exception.", desc); } else if ((plr.IsCompleted != shouldComplete) || (shouldStop && (plr.LowestBreakIteration != null)) || (shouldBreak && (plr.LowestBreakIteration == null))) { Logger.LogInformation("OrderablePartitionerForEach-PLRTest -- {0}: > failed. Complete={1}, LBI={2}", desc, plr.IsCompleted, plr.LowestBreakIteration); } } catch (AggregateException e) { if (!excExpected) { Logger.LogInformation("OrderablePartitionerForEach-PLRTest -- {0}: > failed -- unexpected exception from loop. Exception: {1}", desc, e); } } } // Perform tests on various combinations of Stop()/Break() [Fact] public static void SimultaneousStopBreakTests() { // // Test 32-bit Parallel.For() // ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); ps.Break(); }, "Break After Stop", true, false, false, false); ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); ps.Stop(); }, "Stop After Break", true, false, false, false); CancellationTokenSource cts = new CancellationTokenSource(); ParallelOptions options = new ParallelOptions(); options.CancellationToken = cts.Token; ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); cts.Cancel(); }, options, "Cancel After Break", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); cts.Cancel(); }, options, "Cancel After Stop", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForPLRTest(delegate (int i, ParallelLoopState ps) { cts.Cancel(); ps.Stop(); }, options, "Stop After Cancel", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForPLRTest(delegate (int i, ParallelLoopState ps) { cts.Cancel(); ps.Break(); }, options, "Break After Cancel", false, false, false, false, true); ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught) after Break", false, false, false, true); ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught) after Stop", false, false, true, false); // // Test "vanilla" Parallel.ForEach // ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Break(); ps.Stop(); }, "Stop-After-Break", true, false, false, false); ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Stop(); ps.Break(); }, "Break-after-Stop", true, false, false, false); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Break(); cts.Cancel(); }, options, "Cancel After Break", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Stop(); cts.Cancel(); }, options, "Cancel After Stop", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { cts.Cancel(); ps.Stop(); }, options, "Stop After Cancel", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { cts.Cancel(); ps.Break(); }, options, "Break After Cancel", false, false, false, false, true); ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught)-after-Break", false, false, false, true); ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught)-after-Stop", false, false, true, false); // // Test Parallel.ForEach w/ Partitioner // PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); ps.Stop(); }, "Stop-After-Break", true, false, false, false); PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); ps.Break(); }, "Break-after-Stop", true, false, false, false); PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught)-after-Break", false, false, false, true); PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught)-after-Stop", false, false, true, false); // // Test Parallel.ForEach w/ OrderablePartitioner // OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index) { ps.Break(); ps.Stop(); }, "Stop-After-Break", true, false, false, false); OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index) { ps.Stop(); ps.Break(); }, "Break-after-Stop", true, false, false, false); OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught)-after-Break", false, false, false, true); OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught)-after-Stop", false, false, true, false); // // Test 64-bit Parallel.For // For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Stop(); ps.Break(); }, "Break After Stop", true, false, false, false); For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Break(); ps.Stop(); }, "Stop After Break", true, false, false, false); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Break(); cts.Cancel(); }, options, "Cancel After Break", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Stop(); cts.Cancel(); }, options, "Cancel After Stop", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; For64PLRTest(delegate (long i, ParallelLoopState ps) { cts.Cancel(); ps.Stop(); }, options, "Stop after Cancel", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; For64PLRTest(delegate (long i, ParallelLoopState ps) { cts.Cancel(); ps.Break(); }, options, "Break after Cancel", false, false, false, false, true); For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught) after Break", false, false, false, true); For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught) after Stop", false, false, true, false); } #region Helper Classes and Methods // // Utility class for use w/ Partitioner-style ForEach testing. // Created by Cindy Song. // public class MyPartitioner<TSource> : Partitioner<TSource> { private IList<TSource> _data; public MyPartitioner(IList<TSource> data) { _data = data; } override public IList<IEnumerator<TSource>> GetPartitions(int partitionCount) { if (partitionCount <= 0) { throw new ArgumentOutOfRangeException("partitionCount"); } IEnumerator<TSource>[] partitions = new IEnumerator<TSource>[partitionCount]; IEnumerable<KeyValuePair<long, TSource>> partitionEnumerable = Partitioner.Create(_data, true).GetOrderableDynamicPartitions(); for (int i = 0; i < partitionCount; i++) { partitions[i] = DropIndices(partitionEnumerable.GetEnumerator()); } return partitions; } override public IEnumerable<TSource> GetDynamicPartitions() { return DropIndices(Partitioner.Create(_data, true).GetOrderableDynamicPartitions()); } private static IEnumerable<TSource> DropIndices(IEnumerable<KeyValuePair<long, TSource>> source) { foreach (KeyValuePair<long, TSource> pair in source) { yield return pair.Value; } } private static IEnumerator<TSource> DropIndices(IEnumerator<KeyValuePair<long, TSource>> source) { while (source.MoveNext()) { yield return source.Current.Value; } } public override bool SupportsDynamicPartitions { get { return true; } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.DirectoryServices.ActiveDirectory { public class ConfigurationSet { // Private Variables private readonly DirectoryContext _context = null; private readonly DirectoryEntryManager _directoryEntryMgr = null; private bool _disposed = false; // variables corresponding to public properties private readonly string _configSetName = null; private ReadOnlySiteCollection _cachedSites = null; private AdamInstanceCollection _cachedADAMInstances = null; private ApplicationPartitionCollection _cachedApplicationPartitions = null; private ActiveDirectorySchema _cachedSchema = null; private AdamInstance _cachedSchemaRoleOwner = null; private AdamInstance _cachedNamingRoleOwner = null; private ReplicationSecurityLevel _cachedSecurityLevel = (ReplicationSecurityLevel)(-1); // 4 minutes timeout for locating an ADAM instance in the configset private static TimeSpan s_locationTimeout = new TimeSpan(0, 4, 0); #region constructors internal ConfigurationSet(DirectoryContext context, string configSetName, DirectoryEntryManager directoryEntryMgr) { _context = context; _configSetName = configSetName; _directoryEntryMgr = directoryEntryMgr; } internal ConfigurationSet(DirectoryContext context, string configSetName) : this(context, configSetName, new DirectoryEntryManager(context)) { } #endregion constructors #region IDisposable public void Dispose() => Dispose(true); // private Dispose method protected virtual void Dispose(bool disposing) { if (!_disposed) { // check if this is an explicit Dispose // only then clean up the directory entries if (disposing) { // dispose all directory entries foreach (DirectoryEntry entry in _directoryEntryMgr.GetCachedDirectoryEntries()) { entry.Dispose(); } } _disposed = true; } } #endregion IDisposable #region public methods public static ConfigurationSet GetConfigurationSet(DirectoryContext context) { // check that the argument is not null if (context == null) throw new ArgumentNullException("context"); // target should ConfigurationSet or DirectoryServer if ((context.ContextType != DirectoryContextType.ConfigurationSet) && (context.ContextType != DirectoryContextType.DirectoryServer)) { throw new ArgumentException(SR.TargetShouldBeServerORConfigSet, "context"); } // target should be an adam config set or server if (((!context.isServer()) && (!context.isADAMConfigSet()))) { // the target should be a server or an ADAM Config Set if (context.ContextType == DirectoryContextType.ConfigurationSet) { throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ConfigurationSet), context.Name); } else { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound , context.Name), typeof(ConfigurationSet), null); } } // work with copy of the context context = new DirectoryContext(context); // // bind to rootdse of an adam instance (if target is already a server, verify that it is an adam instance) // DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context); DirectoryEntry rootDSE = null; string configSetName = null; try { rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); if ((context.isServer()) && (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectoryApplicationMode))) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound , context.Name), typeof(ConfigurationSet), null); } configSetName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.ConfigurationNamingContext); } catch (COMException e) { int errorCode = e.ErrorCode; if (errorCode == unchecked((int)0x8007203a)) { if (context.ContextType == DirectoryContextType.ConfigurationSet) { throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ConfigurationSet), context.Name); } else { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound , context.Name), typeof(ConfigurationSet), null); } } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } catch (ActiveDirectoryObjectNotFoundException) { if (context.ContextType == DirectoryContextType.ConfigurationSet) { // this is the case when we could not find an ADAM instance in that config set throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ConfigurationSet), context.Name); } else throw; } // return config set object return new ConfigurationSet(context, configSetName, directoryEntryMgr); } public AdamInstance FindAdamInstance() { CheckIfDisposed(); return FindOneAdamInstance(Name, _context, null, null); } public AdamInstance FindAdamInstance(string partitionName) { CheckIfDisposed(); if (partitionName == null) { throw new ArgumentNullException("partitionName"); } return FindOneAdamInstance(Name, _context, partitionName, null); } public AdamInstance FindAdamInstance(string partitionName, string siteName) { CheckIfDisposed(); // // null partitionName would signify that we don't care about the partition // if (siteName == null) { throw new ArgumentNullException("siteName"); } return FindOneAdamInstance(Name, _context, partitionName, siteName); } public AdamInstanceCollection FindAllAdamInstances() { CheckIfDisposed(); return FindAdamInstances(_context, null, null); } public AdamInstanceCollection FindAllAdamInstances(string partitionName) { CheckIfDisposed(); if (partitionName == null) { throw new ArgumentNullException("partitionName"); } return FindAdamInstances(_context, partitionName, null); } public AdamInstanceCollection FindAllAdamInstances(string partitionName, string siteName) { CheckIfDisposed(); // // null partitionName would signify that we don't care about the partition // if (siteName == null) { throw new ArgumentNullException("siteName"); } return FindAdamInstances(_context, partitionName, siteName); } public DirectoryEntry GetDirectoryEntry() { CheckIfDisposed(); return DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.ConfigurationNamingContext); } public ReplicationSecurityLevel GetSecurityLevel() { CheckIfDisposed(); if (_cachedSecurityLevel == (ReplicationSecurityLevel)(-1)) { DirectoryEntry configEntry = _directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.ConfigurationNamingContext); _cachedSecurityLevel = (ReplicationSecurityLevel)((int)PropertyManager.GetPropertyValue(_context, configEntry, PropertyManager.MsDSReplAuthenticationMode)); } return _cachedSecurityLevel; } public void SetSecurityLevel(ReplicationSecurityLevel securityLevel) { CheckIfDisposed(); if (securityLevel < ReplicationSecurityLevel.NegotiatePassThrough || securityLevel > ReplicationSecurityLevel.MutualAuthentication) { throw new InvalidEnumArgumentException("securityLevel", (int)securityLevel, typeof(ReplicationSecurityLevel)); } try { DirectoryEntry configEntry = _directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.ConfigurationNamingContext); configEntry.Properties[PropertyManager.MsDSReplAuthenticationMode].Value = (int)securityLevel; configEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(_context, e); } // invalidate the cached entry _cachedSecurityLevel = (ReplicationSecurityLevel)(-1); } public override string ToString() => Name; #endregion public methods #region public properties public string Name { get { CheckIfDisposed(); return _configSetName; } } public ReadOnlySiteCollection Sites { get { CheckIfDisposed(); if (_cachedSites == null) { _cachedSites = new ReadOnlySiteCollection(GetSites()); } return _cachedSites; } } public AdamInstanceCollection AdamInstances { get { CheckIfDisposed(); if (_cachedADAMInstances == null) { _cachedADAMInstances = FindAllAdamInstances(); } return _cachedADAMInstances; } } public ApplicationPartitionCollection ApplicationPartitions { get { CheckIfDisposed(); if (_cachedApplicationPartitions == null) { _cachedApplicationPartitions = new ApplicationPartitionCollection(GetApplicationPartitions()); } return _cachedApplicationPartitions; } } public ActiveDirectorySchema Schema { get { CheckIfDisposed(); if (_cachedSchema == null) { try { _cachedSchema = new ActiveDirectorySchema(_context, _directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext)); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(_context, e); } } return _cachedSchema; } } public AdamInstance SchemaRoleOwner { get { CheckIfDisposed(); if (_cachedSchemaRoleOwner == null) { _cachedSchemaRoleOwner = GetRoleOwner(AdamRole.SchemaRole); } return _cachedSchemaRoleOwner; } } public AdamInstance NamingRoleOwner { get { CheckIfDisposed(); if (_cachedNamingRoleOwner == null) { _cachedNamingRoleOwner = GetRoleOwner(AdamRole.NamingRole); } return _cachedNamingRoleOwner; } } #endregion public properties #region private methods private static DirectoryEntry GetSearchRootEntry(Forest forest) { DirectoryEntry rootEntry; DirectoryContext forestContext = forest.GetDirectoryContext(); bool isServer = false; bool isGC = false; AuthenticationTypes authType = Utils.DefaultAuthType; if (forestContext.ContextType == DirectoryContextType.DirectoryServer) { // // the forest object was created by specifying a server name // so we will stick to that server for the search. We need to determine // whether or not the server is a DC or GC // isServer = true; DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(forestContext, WellKnownDN.RootDSE); string isGCReady = (string)PropertyManager.GetPropertyValue(forestContext, rootDSE, PropertyManager.IsGlobalCatalogReady); isGC = (Utils.Compare(isGCReady, "TRUE") == 0); } if (isServer) { authType |= AuthenticationTypes.ServerBind; if (isGC) { rootEntry = new DirectoryEntry("GC://" + forestContext.GetServerName(), forestContext.UserName, forestContext.Password, authType); } else { rootEntry = new DirectoryEntry("LDAP://" + forestContext.GetServerName(), forestContext.UserName, forestContext.Password, authType); } } else { // need to find any GC in the forest rootEntry = new DirectoryEntry("GC://" + forest.Name, forestContext.UserName, forestContext.Password, authType); } return rootEntry; } internal static AdamInstance FindAnyAdamInstance(DirectoryContext context) { if (context.ContextType != DirectoryContextType.ConfigurationSet) { // assuming it's an ADAM Instance // check that it is an ADAM server only (not AD) DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context); DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectoryApplicationMode)) { directoryEntryMgr.RemoveIfExists(directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.RootDSE)); throw new ArgumentException(SR.TargetShouldBeServerORConfigSet, "context"); } string dnsHostName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName); return new AdamInstance(context, dnsHostName, directoryEntryMgr); } // Now this is the case where context is a Config Set // Here we need to search for the service connection points in the forest // (if the forest object was created by specifying the server, we stick to that, else search in a GC) DirectoryEntry rootEntry = GetSearchRootEntry(Forest.GetCurrentForest()); ArrayList adamInstanceNames = new ArrayList(); try { string entryName = (string)rootEntry.Properties["distinguishedName"].Value; // Search for computer "serviceConnectionObjects" where the keywords attribute // contains the specified keyword // set up the searcher object // build the filter StringBuilder str = new StringBuilder(15); str.Append("(&("); str.Append(PropertyManager.ObjectCategory); str.Append("=serviceConnectionPoint)"); str.Append("("); str.Append(PropertyManager.Keywords); str.Append("=1.2.840.113556.1.4.1851)("); str.Append(PropertyManager.Keywords); str.Append("="); str.Append(Utils.GetEscapedFilterValue(context.Name)); // target = config set name str.Append("))"); string filter = str.ToString(); string[] propertiesToLoad = new string[1]; propertiesToLoad[0] = PropertyManager.ServiceBindingInformation; ADSearcher searcher = new ADSearcher(rootEntry, filter, propertiesToLoad, SearchScope.Subtree, false /*not paged search*/, false /*no cached results*/); SearchResultCollection resCol = searcher.FindAll(); try { foreach (SearchResult res in resCol) { // the binding info contains two values // "ldap://hostname:ldapport" // and "ldaps://hostname:sslport" // we need the "hostname:ldapport" value string prefix = "ldap://"; foreach (string bindingInfo in res.Properties[PropertyManager.ServiceBindingInformation]) { if ((bindingInfo.Length > prefix.Length) && (String.Compare(bindingInfo.Substring(0, prefix.Length), prefix, StringComparison.OrdinalIgnoreCase) == 0)) { adamInstanceNames.Add(bindingInfo.Substring(prefix.Length)); } } } } finally { resCol.Dispose(); } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { rootEntry.Dispose(); } // // we have all the adam instance names in teh form of server:port from the scp // now we need to find one that is alive // return FindAliveAdamInstance(null, context, adamInstanceNames); } internal static AdamInstance FindOneAdamInstance(DirectoryContext context, string partitionName, string siteName) { return FindOneAdamInstance(null, context, partitionName, siteName); } internal static AdamInstance FindOneAdamInstance(string configSetName, DirectoryContext context, string partitionName, string siteName) { // can expect valid context (non-null) if (partitionName != null && partitionName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "partitionName"); } if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "siteName"); } ArrayList ntdsaNames = Utils.GetReplicaList(context, partitionName, siteName, false /* isDefaultNC */, true /* isADAM */, false /* mustBeGC */); if (ntdsaNames.Count < 1) { throw new ActiveDirectoryObjectNotFoundException(SR.ADAMInstanceNotFound, typeof(AdamInstance), null); } return FindAliveAdamInstance(configSetName, context, ntdsaNames); } internal static AdamInstanceCollection FindAdamInstances(DirectoryContext context, string partitionName, string siteName) { // can expect valid context (non-null) if (partitionName != null && partitionName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "partitionName"); } if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "siteName"); } ArrayList adamInstanceList = new ArrayList(); foreach (string adamInstanceName in Utils.GetReplicaList(context, partitionName, siteName, false /* isDefaultNC */, true /* isADAM */, false /* mustBeGC */)) { DirectoryContext adamInstContext = Utils.GetNewDirectoryContext(adamInstanceName, DirectoryContextType.DirectoryServer, context); adamInstanceList.Add(new AdamInstance(adamInstContext, adamInstanceName)); } return new AdamInstanceCollection(adamInstanceList); } // // The input to this function is a list of adam instance names in the form server:port // This function tries to bind to each of the instances in this list sequentially until one of the following occurs: // 1. An ADAM instance responds to an ldap_bind - we return an ADAMInstance object for that adam instance // 2. We exceed the timeout duration - we return an ActiveDirectoryObjectNotFoundException // internal static AdamInstance FindAliveAdamInstance(string configSetName, DirectoryContext context, ArrayList adamInstanceNames) { bool foundAliveADAMInstance = false; AdamInstance adamInstance = null; // record the start time so that we can determine if the timeout duration has been exceeded or not DateTime startTime = DateTime.UtcNow; // loop through each adam instance and try to bind to the rootdse foreach (string adamInstanceName in adamInstanceNames) { DirectoryContext adamInstContext = Utils.GetNewDirectoryContext(adamInstanceName, DirectoryContextType.DirectoryServer, context); DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(adamInstContext); DirectoryEntry tempRootEntry = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); try { tempRootEntry.Bind(true); adamInstance = new AdamInstance(adamInstContext, adamInstanceName, directoryEntryMgr, true /* nameIncludesPort */); foundAliveADAMInstance = true; } catch (COMException e) { // if this is server down /server busy / server unavailable / timeout exception we should just eat this up and try the next one if ((e.ErrorCode == unchecked((int)0x8007203a)) || (e.ErrorCode == unchecked((int)0x8007200e)) || (e.ErrorCode == unchecked((int)0x8007200f)) || (e.ErrorCode == unchecked((int)0x800705b4))) { // if we are passed the timeout period, we should throw, else do nothing if (DateTime.UtcNow.Subtract(startTime) > s_locationTimeout) throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , (configSetName != null) ? configSetName : context.Name), typeof(AdamInstance), null); } else throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (foundAliveADAMInstance) { return adamInstance; } } // if we reach here, we haven't found an adam instance throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , (configSetName != null) ? configSetName : context.Name), typeof(AdamInstance), null); } /// <returns>Returns a DomainController object for the DC that holds the specified FSMO role</returns> private AdamInstance GetRoleOwner(AdamRole role) { DirectoryEntry entry = null; string adamInstName = null; try { switch (role) { case AdamRole.SchemaRole: { entry = _directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.SchemaNamingContext); break; } case AdamRole.NamingRole: { entry = _directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.PartitionsContainer); break; } default: // should not happen since we are calling this only internally Debug.Assert(false, "ConfigurationSet.GetRoleOwner: Invalid role type."); break; } entry.RefreshCache(); adamInstName = Utils.GetAdamDnsHostNameFromNTDSA(_context, (string)PropertyManager.GetPropertyValue(_context, entry, PropertyManager.FsmoRoleOwner)); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(_context, e); } finally { if (entry != null) { entry.Dispose(); } } // create a new context object for the adam instance passing on the // credentials from the context DirectoryContext adamInstContext = Utils.GetNewDirectoryContext(adamInstName, DirectoryContextType.DirectoryServer, _context); return new AdamInstance(adamInstContext, adamInstName); } private ArrayList GetSites() { ArrayList sites = new ArrayList(); DirectoryEntry sitesEntry = _directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.SitesContainer); // search for all the "site" objects // (one-level search is good enough) // setup the directory searcher object string filter = "(" + PropertyManager.ObjectCategory + "=site)"; string[] propertiesToLoad = new string[1]; propertiesToLoad[0] = PropertyManager.Cn; ADSearcher searcher = new ADSearcher(sitesEntry, filter, propertiesToLoad, SearchScope.OneLevel); SearchResultCollection resCol = null; try { resCol = searcher.FindAll(); foreach (SearchResult res in resCol) { // an existing site sites.Add(new ActiveDirectorySite(_context, (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.Cn), true)); } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(_context, e); } finally { if (resCol != null) { // call dispose on search result collection resCol.Dispose(); } } return sites; } private ArrayList GetApplicationPartitions() { ArrayList appNCs = new ArrayList(); DirectoryEntry rootDSE = _directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); DirectoryEntry partitionsEntry = _directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.PartitionsContainer); // search for all the "crossRef" objects that have the // ADS_SYSTEMFLAG_CR_NTDS_NC set and the SYSTEMFLAG_CR_NTDS_DOMAIN flag not set // (one-level search is good enough) // setup the directory searcher object // build the filter StringBuilder str = new StringBuilder(100); str.Append("(&("); str.Append(PropertyManager.ObjectCategory); str.Append("=crossRef)("); str.Append(PropertyManager.SystemFlags); str.Append(":1.2.840.113556.1.4.804:="); str.Append((int)SystemFlag.SystemFlagNtdsNC); str.Append(")(!("); str.Append(PropertyManager.SystemFlags); str.Append(":1.2.840.113556.1.4.803:="); str.Append((int)SystemFlag.SystemFlagNtdsDomain); str.Append(")))"); string filter = str.ToString(); string[] propertiesToLoad = new string[2]; propertiesToLoad[0] = PropertyManager.NCName; propertiesToLoad[1] = PropertyManager.MsDSNCReplicaLocations; ADSearcher searcher = new ADSearcher(partitionsEntry, filter, propertiesToLoad, SearchScope.OneLevel); SearchResultCollection resCol = null; try { resCol = searcher.FindAll(); string schemaNamingContext = (string)PropertyManager.GetPropertyValue(_context, rootDSE, PropertyManager.SchemaNamingContext); string configurationNamingContext = (string)PropertyManager.GetPropertyValue(_context, rootDSE, PropertyManager.ConfigurationNamingContext); foreach (SearchResult res in resCol) { // add the name of the appNC only if it is not // the Schema or Configuration partition string nCName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.NCName); if ((!(nCName.Equals(schemaNamingContext))) && (!(nCName.Equals(configurationNamingContext)))) { ResultPropertyValueCollection replicaLocations = res.Properties[PropertyManager.MsDSNCReplicaLocations]; if (replicaLocations.Count > 0) { string replicaName = Utils.GetAdamDnsHostNameFromNTDSA(_context, (string)replicaLocations[Utils.GetRandomIndex(replicaLocations.Count)]); DirectoryContext appNCContext = Utils.GetNewDirectoryContext(replicaName, DirectoryContextType.DirectoryServer, _context); appNCs.Add(new ApplicationPartition(appNCContext, nCName, null, ApplicationPartitionType.ADAMApplicationPartition, new DirectoryEntryManager(appNCContext))); } } } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(_context, e); } finally { if (resCol != null) { // call dispose on search result collection resCol.Dispose(); } } return appNCs; } private void CheckIfDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } } #endregion private methods } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. extern alias WORKSPACES; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.FileSystem; using Microsoft.CodeAnalysis.Editor.Implementation.Interactive; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Interactive; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Roslyn.Utilities; using RuntimeMetadataReferenceResolver = WORKSPACES::Microsoft.CodeAnalysis.Scripting.Hosting.RuntimeMetadataReferenceResolver; using GacFileResolver = WORKSPACES::Microsoft.CodeAnalysis.Scripting.Hosting.GacFileResolver; namespace Microsoft.CodeAnalysis.Editor.Interactive { public abstract class InteractiveEvaluator : IInteractiveEvaluator, ICurrentWorkingDirectoryDiscoveryService { // full path or null private readonly string _responseFilePath; private readonly InteractiveHost _interactiveHost; private string _initialWorkingDirectory; private ImmutableArray<CommandLineSourceFile> _rspSourceFiles; private readonly IContentType _contentType; private readonly InteractiveWorkspace _workspace; private IInteractiveWindow _currentWindow; private ImmutableHashSet<MetadataReference> _references; private MetadataReferenceResolver _metadataReferenceResolver; private SourceReferenceResolver _sourceReferenceResolver; private ProjectId _previousSubmissionProjectId; private ProjectId _currentSubmissionProjectId; private readonly IViewClassifierAggregatorService _classifierAggregator; private readonly IInteractiveWindowCommandsFactory _commandsFactory; private readonly ImmutableArray<IInteractiveWindowCommand> _commands; private IInteractiveWindowCommands _interactiveCommands; private ITextView _currentTextView; private ITextBuffer _currentSubmissionBuffer; private readonly ISet<ValueTuple<ITextView, ITextBuffer>> _submissionBuffers = new HashSet<ValueTuple<ITextView, ITextBuffer>>(); private int _submissionCount = 0; private readonly EventHandler<ContentTypeChangedEventArgs> _contentTypeChangedHandler; public ImmutableArray<string> ReferenceSearchPaths { get; private set; } public ImmutableArray<string> SourceSearchPaths { get; private set; } public string WorkingDirectory { get; private set; } internal InteractiveEvaluator( IContentType contentType, HostServices hostServices, IViewClassifierAggregatorService classifierAggregator, IInteractiveWindowCommandsFactory commandsFactory, ImmutableArray<IInteractiveWindowCommand> commands, string responseFilePath, string initialWorkingDirectory, string interactiveHostPath, Type replType) { Debug.Assert(responseFilePath == null || PathUtilities.IsAbsolute(responseFilePath)); _contentType = contentType; _responseFilePath = responseFilePath; _workspace = new InteractiveWorkspace(this, hostServices); _contentTypeChangedHandler = new EventHandler<ContentTypeChangedEventArgs>(LanguageBufferContentTypeChanged); _classifierAggregator = classifierAggregator; _initialWorkingDirectory = initialWorkingDirectory; _commandsFactory = commandsFactory; _commands = commands; var hostPath = interactiveHostPath; _interactiveHost = new InteractiveHost(replType, hostPath, initialWorkingDirectory); _interactiveHost.ProcessStarting += ProcessStarting; WorkingDirectory = initialWorkingDirectory; } public IContentType ContentType { get { return _contentType; } } public IInteractiveWindow CurrentWindow { get { return _currentWindow; } set { if (_currentWindow != value) { _interactiveHost.Output = value.OutputWriter; _interactiveHost.ErrorOutput = value.ErrorOutputWriter; if (_currentWindow != null) { _currentWindow.SubmissionBufferAdded -= SubmissionBufferAdded; } _currentWindow = value; } _currentWindow.SubmissionBufferAdded += SubmissionBufferAdded; _interactiveCommands = _commandsFactory.CreateInteractiveCommands(_currentWindow, "#", _commands); } } protected IInteractiveWindowCommands InteractiveCommands { get { return _interactiveCommands; } } protected abstract string LanguageName { get; } protected abstract CompilationOptions GetSubmissionCompilationOptions(string name, MetadataReferenceResolver metadataReferenceResolver, SourceReferenceResolver sourceReferenceResolver); protected abstract ParseOptions ParseOptions { get; } protected abstract CommandLineParser CommandLineParser { get; } #region Initialization public string GetConfiguration() { return null; } private IInteractiveWindow GetInteractiveWindow() { var window = CurrentWindow; if (window == null) { throw new InvalidOperationException(EditorFeaturesResources.EngineMustBeAttachedToAnInteractiveWindow); } return window; } public Task<ExecutionResult> InitializeAsync() { var window = GetInteractiveWindow(); _interactiveHost.Output = window.OutputWriter; _interactiveHost.ErrorOutput = window.ErrorOutputWriter; return ResetAsyncWorker(); } public void Dispose() { _workspace.Dispose(); _interactiveHost.Dispose(); } /// <summary> /// Invoked by <see cref="InteractiveHost"/> when a new process is being started. /// </summary> private void ProcessStarting(bool initialize) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => ProcessStarting(initialize))); return; } // Freeze all existing classifications and then clear the list of // submission buffers we have. FreezeClassifications(); _submissionBuffers.Clear(); // We always start out empty _workspace.ClearSolution(); _currentSubmissionProjectId = null; _previousSubmissionProjectId = null; var metadataService = _workspace.CurrentSolution.Services.MetadataService; ReferenceSearchPaths = ImmutableArray.Create(FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory())); SourceSearchPaths = ImmutableArray.Create(FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile))); if (initialize && File.Exists(_responseFilePath)) { // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var rspArguments = this.CommandLineParser.Parse(new[] { "@" + _responseFilePath }, Path.GetDirectoryName(_responseFilePath), RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/); ReferenceSearchPaths = ReferenceSearchPaths.AddRange(rspArguments.ReferencePaths); // the base directory for references specified in the .rsp file is the .rsp file directory: var rspMetadataReferenceResolver = CreateMetadataReferenceResolver(metadataService, ReferenceSearchPaths, rspArguments.BaseDirectory); // ignore unresolved references, they will be reported in the interactive window: var rspReferences = rspArguments.ResolveMetadataReferences(rspMetadataReferenceResolver) .Where(r => !(r is UnresolvedMetadataReference)); var interactiveHelpersRef = metadataService.GetReference(typeof(Script).Assembly.Location, MetadataReferenceProperties.Assembly); var interactiveHostObjectRef = metadataService.GetReference(typeof(InteractiveHostObject).Assembly.Location, MetadataReferenceProperties.Assembly); _references = ImmutableHashSet.Create<MetadataReference>( interactiveHelpersRef, interactiveHostObjectRef) .Union(rspReferences); // we need to create projects for these: _rspSourceFiles = rspArguments.SourceFiles; } else { var mscorlibRef = metadataService.GetReference(typeof(object).Assembly.Location, MetadataReferenceProperties.Assembly); _references = ImmutableHashSet.Create<MetadataReference>(mscorlibRef); _rspSourceFiles = ImmutableArray.Create<CommandLineSourceFile>(); } _metadataReferenceResolver = CreateMetadataReferenceResolver(metadataService, ReferenceSearchPaths, _initialWorkingDirectory); _sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, _initialWorkingDirectory); // create the first submission project in the workspace after reset: if (_currentSubmissionBuffer != null) { AddSubmission(_currentTextView, _currentSubmissionBuffer, this.LanguageName); } } private Dispatcher Dispatcher { get { return ((FrameworkElement)GetInteractiveWindow().TextView).Dispatcher; } } private static MetadataReferenceResolver CreateMetadataReferenceResolver(IMetadataService metadataService, ImmutableArray<string> searchPaths, string baseDirectory) { var userProfilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); var packagesDirectory = (userProfilePath == null) ? null : PathUtilities.CombineAbsoluteAndRelativePaths(userProfilePath, PathUtilities.CombinePossiblyRelativeAndRelativePaths(".nuget", "packages")); return new RuntimeMetadataReferenceResolver( new RelativePathResolver(searchPaths, baseDirectory), string.IsNullOrEmpty(packagesDirectory) ? null : new NuGetPackageResolverImpl(packagesDirectory), GacFileResolver.IsAvailable ? new GacFileResolver(preferredCulture: CultureInfo.CurrentCulture) : null, (path, properties) => metadataService.GetReference(path, properties)); } private static SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory) { return new SourceFileResolver(searchPaths, baseDirectory); } #endregion #region Workspace private void SubmissionBufferAdded(object sender, SubmissionBufferAddedEventArgs args) { AddSubmission(_currentWindow.TextView, args.NewBuffer, this.LanguageName); } // The REPL window might change content type to host command content type (when a host command is typed at the beginning of the buffer). private void LanguageBufferContentTypeChanged(object sender, ContentTypeChangedEventArgs e) { // It's not clear whether this situation will ever happen, but just in case. if (e.BeforeContentType == e.AfterContentType) { return; } var buffer = e.Before.TextBuffer; var contentTypeName = this.ContentType.TypeName; var afterIsLanguage = e.AfterContentType.IsOfType(contentTypeName); var afterIsInteractiveCommand = e.AfterContentType.IsOfType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName); var beforeIsLanguage = e.BeforeContentType.IsOfType(contentTypeName); var beforeIsInteractiveCommand = e.BeforeContentType.IsOfType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName); Debug.Assert((afterIsLanguage && beforeIsInteractiveCommand) || (beforeIsLanguage && afterIsInteractiveCommand)); // We're switching between the target language and the Interactive Command "language". // First, remove the current submission from the solution. var oldSolution = _workspace.CurrentSolution; var newSolution = oldSolution; foreach (var documentId in _workspace.GetRelatedDocumentIds(buffer.AsTextContainer())) { Debug.Assert(documentId != null); newSolution = newSolution.RemoveDocument(documentId); // TODO (tomat): Is there a better way to remove mapping between buffer and document in REPL? // Perhaps TrackingWorkspace should implement RemoveDocumentAsync? _workspace.ClearOpenDocument(documentId); } // Next, remove the previous submission project and update the workspace. newSolution = newSolution.RemoveProject(_currentSubmissionProjectId); _workspace.SetCurrentSolution(newSolution); // Add a new submission with the correct language for the current buffer. var languageName = afterIsLanguage ? this.LanguageName : InteractiveLanguageNames.InteractiveCommand; AddSubmission(_currentTextView, buffer, languageName); } private void AddSubmission(ITextView textView, ITextBuffer subjectBuffer, string languageName) { var solution = _workspace.CurrentSolution; Project project; if (_previousSubmissionProjectId == null) { // insert projects for initialization files listed in .rsp: // If we have separate files, then those are implicitly #loaded. For this, we'll // create a submission chain foreach (var file in _rspSourceFiles) { project = CreateSubmissionProject(solution, languageName); var documentId = DocumentId.CreateNewId(project.Id, debugName: file.Path); solution = project.Solution.AddDocument(documentId, Path.GetFileName(file.Path), new FileTextLoader(file.Path, defaultEncoding: null)); _previousSubmissionProjectId = project.Id; } } // project for the new submission: project = CreateSubmissionProject(solution, languageName); // Keep track of this buffer so we can freeze the classifications for it in the future. var viewAndBuffer = ValueTuple.Create(textView, subjectBuffer); if (!_submissionBuffers.Contains(viewAndBuffer)) { _submissionBuffers.Add(ValueTuple.Create(textView, subjectBuffer)); } SetSubmissionDocument(subjectBuffer, project); _currentSubmissionProjectId = project.Id; if (_currentSubmissionBuffer != null) { _currentSubmissionBuffer.ContentTypeChanged -= _contentTypeChangedHandler; } subjectBuffer.ContentTypeChanged += _contentTypeChangedHandler; subjectBuffer.Properties[typeof(ICurrentWorkingDirectoryDiscoveryService)] = this; _currentSubmissionBuffer = subjectBuffer; _currentTextView = textView; } private Project CreateSubmissionProject(Solution solution, string languageName) { var name = "Submission#" + (_submissionCount++); // Grab a local copy so we aren't closing over the field that might change. The // collection itself is an immutable collection. var localReferences = _references; // TODO (tomat): needs implementation in InteractiveHostService as well // var localCompilationOptions = (rspArguments != null) ? rspArguments.CompilationOptions : CompilationOptions.Default; var localCompilationOptions = GetSubmissionCompilationOptions(name, _metadataReferenceResolver, _sourceReferenceResolver); var localParseOptions = ParseOptions; var projectId = ProjectId.CreateNewId(debugName: name); solution = solution.AddProject( ProjectInfo.Create( projectId, VersionStamp.Create(), name: name, assemblyName: name, language: languageName, compilationOptions: localCompilationOptions, parseOptions: localParseOptions, documents: null, projectReferences: null, metadataReferences: localReferences, hostObjectType: typeof(InteractiveHostObject), isSubmission: true)); if (_previousSubmissionProjectId != null) { solution = solution.AddProjectReference(projectId, new ProjectReference(_previousSubmissionProjectId)); } return solution.GetProject(projectId); } private void SetSubmissionDocument(ITextBuffer buffer, Project project) { var documentId = DocumentId.CreateNewId(project.Id, debugName: project.Name); var solution = project.Solution .AddDocument(documentId, project.Name, buffer.CurrentSnapshot.AsText()); _workspace.SetCurrentSolution(solution); // opening document will start workspace listening to changes in this text container _workspace.OpenDocument(documentId, buffer.AsTextContainer()); } private void FreezeClassifications() { foreach (var textViewAndBuffer in _submissionBuffers) { var textView = textViewAndBuffer.Item1; var textBuffer = textViewAndBuffer.Item2; if (textBuffer != _currentSubmissionBuffer) { InertClassifierProvider.CaptureExistingClassificationSpans(_classifierAggregator, textView, textBuffer); } } } #endregion #region IInteractiveEngine public virtual bool CanExecuteCode(string text) { if (_interactiveCommands != null && _interactiveCommands.InCommand) { return true; } return false; } public Task<ExecutionResult> ResetAsync(bool initialize = true) { GetInteractiveWindow().AddInput(_interactiveCommands.CommandPrefix + "reset"); GetInteractiveWindow().WriteLine("Resetting execution engine."); GetInteractiveWindow().FlushOutput(); return ResetAsyncWorker(initialize); } private async Task<ExecutionResult> ResetAsyncWorker(bool initialize = true) { try { var options = InteractiveHostOptions.Default.WithInitializationFile(initialize ? _responseFilePath : null); var result = await _interactiveHost.ResetAsync(options).ConfigureAwait(false); if (result.Success) { UpdateResolvers(result); } return new ExecutionResult(result.Success); } catch (Exception e) when (FatalError.Report(e)) { throw ExceptionUtilities.Unreachable; } } public async Task<ExecutionResult> ExecuteCodeAsync(string text) { try { if (InteractiveCommands.InCommand) { var cmdResult = InteractiveCommands.TryExecuteCommand(); if (cmdResult != null) { return await cmdResult.ConfigureAwait(false); } } var result = await _interactiveHost.ExecuteAsync(text).ConfigureAwait(false); if (result.Success) { // We are not executing a command (the current content type is not "Interactive Command"), // so the source document should not have been removed. Debug.Assert(_workspace.CurrentSolution.GetProject(_currentSubmissionProjectId).HasDocuments); // only remember the submission if we compiled successfully, otherwise we // ignore it's id so we don't reference it in the next submission. _previousSubmissionProjectId = _currentSubmissionProjectId; // Grab any directive references from it var compilation = await _workspace.CurrentSolution.GetProject(_previousSubmissionProjectId).GetCompilationAsync().ConfigureAwait(false); _references = _references.Union(compilation.DirectiveReferences); // update local search paths - remote paths has already been updated UpdateResolvers(result); } return new ExecutionResult(result.Success); } catch (Exception e) when (FatalError.Report(e)) { throw ExceptionUtilities.Unreachable; } } public void AbortExecution() { // TODO: abort execution } public string FormatClipboard() { // keep the clipboard content as is return null; } #endregion #region Paths, Resolvers private void UpdateResolvers(RemoteExecutionResult result) { UpdateResolvers(result.ChangedReferencePaths.AsImmutableOrNull(), result.ChangedSourcePaths.AsImmutableOrNull(), result.ChangedWorkingDirectory); } private void UpdateResolvers(ImmutableArray<string> changedReferenceSearchPaths, ImmutableArray<string> changedSourceSearchPaths, string changedWorkingDirectory) { if (changedReferenceSearchPaths.IsDefault && changedSourceSearchPaths.IsDefault && changedWorkingDirectory == null) { return; } var solution = _workspace.CurrentSolution; // Maybe called after reset, when no submissions are available. var optionsOpt = (_currentSubmissionProjectId != null) ? solution.GetProjectState(_currentSubmissionProjectId).CompilationOptions : null; if (changedWorkingDirectory != null) { WorkingDirectory = changedWorkingDirectory; } if (!changedReferenceSearchPaths.IsDefault || changedWorkingDirectory != null) { ReferenceSearchPaths = changedReferenceSearchPaths; _metadataReferenceResolver = CreateMetadataReferenceResolver(_workspace.CurrentSolution.Services.MetadataService, ReferenceSearchPaths, WorkingDirectory); if (optionsOpt != null) { optionsOpt = optionsOpt.WithMetadataReferenceResolver(_metadataReferenceResolver); } } if (!changedSourceSearchPaths.IsDefault || changedWorkingDirectory != null) { SourceSearchPaths = changedSourceSearchPaths; _sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, WorkingDirectory); if (optionsOpt != null) { optionsOpt = optionsOpt.WithSourceReferenceResolver(_sourceReferenceResolver); } } if (optionsOpt != null) { _workspace.SetCurrentSolution(solution.WithProjectCompilationOptions(_currentSubmissionProjectId, optionsOpt)); } } public async Task SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string workingDirectory) { try { var result = await _interactiveHost.SetPathsAsync(referenceSearchPaths.ToArray(), sourceSearchPaths.ToArray(), workingDirectory).ConfigureAwait(false); UpdateResolvers(result); } catch (Exception e) when (FatalError.Report(e)) { throw ExceptionUtilities.Unreachable; } } public string GetPrompt() { if (CurrentWindow.CurrentLanguageBuffer != null && CurrentWindow.CurrentLanguageBuffer.CurrentSnapshot.LineCount > 1) { return ". "; } return "> "; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; namespace System.Linq.Expressions.Tests { public static class NonLiftedComparisonGreaterThanNullableTests { #region Test methods [Fact] public static void CheckNonLiftedComparisonGreaterThanNullableByteTest() { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableByte(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonGreaterThanNullableCharTest() { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableChar(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonGreaterThanNullableDecimalTest() { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableDecimal(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonGreaterThanNullableDoubleTest() { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableDouble(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonGreaterThanNullableFloatTest() { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableFloat(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonGreaterThanNullableIntTest() { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableInt(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonGreaterThanNullableLongTest() { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableLong(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonGreaterThanNullableSByteTest() { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableSByte(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonGreaterThanNullableShortTest() { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableShort(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonGreaterThanNullableUIntTest() { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableUInt(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonGreaterThanNullableULongTest() { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableULong(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonGreaterThanNullableUShortTest() { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableUShort(values[i], values[j]); } } } #endregion #region Test verifiers private static void VerifyComparisonGreaterThanNullableByte(byte? a, byte? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), false, null)); Func<bool> f = e.Compile(); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableChar(char? a, char? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), false, null)); Func<bool> f = e.Compile(); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableDecimal(decimal? a, decimal? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), false, null)); Func<bool> f = e.Compile(); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableDouble(double? a, double? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), false, null)); Func<bool> f = e.Compile(); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableFloat(float? a, float? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), false, null)); Func<bool> f = e.Compile(); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableInt(int? a, int? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), false, null)); Func<bool> f = e.Compile(); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableLong(long? a, long? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), false, null)); Func<bool> f = e.Compile(); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableSByte(sbyte? a, sbyte? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), false, null)); Func<bool> f = e.Compile(); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableShort(short? a, short? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), false, null)); Func<bool> f = e.Compile(); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableUInt(uint? a, uint? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), false, null)); Func<bool> f = e.Compile(); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableULong(ulong? a, ulong? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), false, null)); Func<bool> f = e.Compile(); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableUShort(ushort? a, ushort? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), false, null)); Func<bool> f = e.Compile(); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } #endregion } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace SPO_WebPartUploader { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using dnlib.DotNet.MD; using dnlib.DotNet.Pdb; namespace dnlib.DotNet { /// <summary> /// A high-level representation of a row in the MemberRef table /// </summary> public abstract class MemberRef : IHasCustomAttribute, IMethodDefOrRef, ICustomAttributeType, IField, IContainsGenericParameter, IHasCustomDebugInformation { /// <summary> /// The row id in its table /// </summary> protected uint rid; /// <summary> /// The owner module /// </summary> protected ModuleDef module; /// <inheritdoc/> public MDToken MDToken => new MDToken(Table.MemberRef, rid); /// <inheritdoc/> public uint Rid { get => rid; set => rid = value; } /// <inheritdoc/> public int HasCustomAttributeTag => 6; /// <inheritdoc/> public int MethodDefOrRefTag => 1; /// <inheritdoc/> public int CustomAttributeTypeTag => 3; /// <summary> /// From column MemberRef.Class /// </summary> public IMemberRefParent Class { get => @class; set => @class = value; } /// <summary/> protected IMemberRefParent @class; /// <summary> /// From column MemberRef.Name /// </summary> public UTF8String Name { get => name; set => name = value; } /// <summary>Name</summary> protected UTF8String name; /// <summary> /// From column MemberRef.Signature /// </summary> public CallingConventionSig Signature { get => signature; set => signature = value; } /// <summary/> protected CallingConventionSig signature; /// <summary> /// Gets all custom attributes /// </summary> public CustomAttributeCollection CustomAttributes { get { if (customAttributes is null) InitializeCustomAttributes(); return customAttributes; } } /// <summary/> protected CustomAttributeCollection customAttributes; /// <summary>Initializes <see cref="customAttributes"/></summary> protected virtual void InitializeCustomAttributes() => Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null); /// <inheritdoc/> public bool HasCustomAttributes => CustomAttributes.Count > 0; /// <inheritdoc/> public int HasCustomDebugInformationTag => 6; /// <inheritdoc/> public bool HasCustomDebugInfos => CustomDebugInfos.Count > 0; /// <summary> /// Gets all custom debug infos /// </summary> public IList<PdbCustomDebugInfo> CustomDebugInfos { get { if (customDebugInfos is null) InitializeCustomDebugInfos(); return customDebugInfos; } } /// <summary/> protected IList<PdbCustomDebugInfo> customDebugInfos; /// <summary>Initializes <see cref="customDebugInfos"/></summary> protected virtual void InitializeCustomDebugInfos() => Interlocked.CompareExchange(ref customDebugInfos, new List<PdbCustomDebugInfo>(), null); /// <inheritdoc/> public ITypeDefOrRef DeclaringType { get { var owner = @class; if (owner is ITypeDefOrRef tdr) return tdr; if (owner is MethodDef method) return method.DeclaringType; if (owner is ModuleRef mr) { var tr = GetGlobalTypeRef(mr); if (module is not null) return module.UpdateRowId(tr); return tr; } return null; } } TypeRefUser GetGlobalTypeRef(ModuleRef mr) { if (module is null) return CreateDefaultGlobalTypeRef(mr); var globalType = module.GlobalType; if (globalType is not null && new SigComparer().Equals(module, mr)) return new TypeRefUser(module, globalType.Namespace, globalType.Name, mr); var asm = module.Assembly; if (asm is null) return CreateDefaultGlobalTypeRef(mr); var mod = asm.FindModule(mr.Name); if (mod is null) return CreateDefaultGlobalTypeRef(mr); globalType = mod.GlobalType; if (globalType is null) return CreateDefaultGlobalTypeRef(mr); return new TypeRefUser(module, globalType.Namespace, globalType.Name, mr); } TypeRefUser CreateDefaultGlobalTypeRef(ModuleRef mr) { var tr = new TypeRefUser(module, string.Empty, "<Module>", mr); if (module is not null) module.UpdateRowId(tr); return tr; } bool IIsTypeOrMethod.IsType => false; bool IIsTypeOrMethod.IsMethod => IsMethodRef; bool IMemberRef.IsField => IsFieldRef; bool IMemberRef.IsTypeSpec => false; bool IMemberRef.IsTypeRef => false; bool IMemberRef.IsTypeDef => false; bool IMemberRef.IsMethodSpec => false; bool IMemberRef.IsMethodDef => false; bool IMemberRef.IsMemberRef => true; bool IMemberRef.IsFieldDef => false; bool IMemberRef.IsPropertyDef => false; bool IMemberRef.IsEventDef => false; bool IMemberRef.IsGenericParam => false; /// <summary> /// <c>true</c> if this is a method reference (<see cref="MethodSig"/> != <c>null</c>) /// </summary> public bool IsMethodRef => MethodSig is not null; /// <summary> /// <c>true</c> if this is a field reference (<see cref="FieldSig"/> != <c>null</c>) /// </summary> public bool IsFieldRef => FieldSig is not null; /// <summary> /// Gets/sets the method sig /// </summary> public MethodSig MethodSig { get => signature as MethodSig; set => signature = value; } /// <summary> /// Gets/sets the field sig /// </summary> public FieldSig FieldSig { get => signature as FieldSig; set => signature = value; } /// <inheritdoc/> public ModuleDef Module => module; /// <summary> /// <c>true</c> if the method has a hidden 'this' parameter /// </summary> public bool HasThis { get { var ms = MethodSig; return ms is null ? false : ms.HasThis; } } /// <summary> /// <c>true</c> if the method has an explicit 'this' parameter /// </summary> public bool ExplicitThis { get { var ms = MethodSig; return ms is null ? false : ms.ExplicitThis; } } /// <summary> /// Gets the calling convention /// </summary> public CallingConvention CallingConvention { get { var ms = MethodSig; return ms is null ? 0 : ms.CallingConvention & CallingConvention.Mask; } } /// <summary> /// Gets/sets the method return type /// </summary> public TypeSig ReturnType { get => MethodSig?.RetType; set { var ms = MethodSig; if (ms is not null) ms.RetType = value; } } /// <inheritdoc/> int IGenericParameterProvider.NumberOfGenericParameters => (int)(MethodSig?.GenParamCount ?? 0); /// <summary> /// Gets the full name /// </summary> public string FullName { get { var parent = @class; IList<TypeSig> typeGenArgs = null; if (parent is TypeSpec) { if (((TypeSpec)parent).TypeSig is GenericInstSig sig) typeGenArgs = sig.GenericArguments; } var methodSig = MethodSig; if (methodSig is not null) return FullNameFactory.MethodFullName(GetDeclaringTypeFullName(parent), name, methodSig, typeGenArgs, null, null, null); var fieldSig = FieldSig; if (fieldSig is not null) return FullNameFactory.FieldFullName(GetDeclaringTypeFullName(parent), name, fieldSig, typeGenArgs, null); return string.Empty; } } /// <summary> /// Get the declaring type's full name /// </summary> /// <returns>Full name or <c>null</c> if there's no declaring type</returns> public string GetDeclaringTypeFullName() => GetDeclaringTypeFullName(@class); string GetDeclaringTypeFullName(IMemberRefParent parent) { if (parent is null) return null; if (parent is ITypeDefOrRef) return ((ITypeDefOrRef)parent).FullName; if (parent is ModuleRef) return $"[module:{((ModuleRef)parent).ToString()}]<Module>"; if (parent is MethodDef) { var declaringType = ((MethodDef)parent).DeclaringType; return declaringType?.FullName; } return null; // Should never be reached } /// <summary> /// Resolves the method/field /// </summary> /// <returns>A <see cref="MethodDef"/> or a <see cref="FieldDef"/> instance or <c>null</c> /// if it couldn't be resolved.</returns> public IMemberForwarded Resolve() { if (module is null) return null; return module.Context.Resolver.Resolve(this); } /// <summary> /// Resolves the method/field /// </summary> /// <returns>A <see cref="MethodDef"/> or a <see cref="FieldDef"/> instance</returns> /// <exception cref="MemberRefResolveException">If the method/field couldn't be resolved</exception> public IMemberForwarded ResolveThrow() { var memberDef = Resolve(); if (memberDef is not null) return memberDef; throw new MemberRefResolveException($"Could not resolve method/field: {this} ({this.GetDefinitionAssembly()})"); } /// <summary> /// Resolves the field /// </summary> /// <returns>A <see cref="FieldDef"/> instance or <c>null</c> if it couldn't be resolved.</returns> public FieldDef ResolveField() => Resolve() as FieldDef; /// <summary> /// Resolves the field /// </summary> /// <returns>A <see cref="FieldDef"/> instance</returns> /// <exception cref="MemberRefResolveException">If the field couldn't be resolved</exception> public FieldDef ResolveFieldThrow() { var field = ResolveField(); if (field is not null) return field; throw new MemberRefResolveException($"Could not resolve field: {this} ({this.GetDefinitionAssembly()})"); } /// <summary> /// Resolves the method /// </summary> /// <returns>A <see cref="MethodDef"/> instance or <c>null</c> if it couldn't be resolved.</returns> public MethodDef ResolveMethod() => Resolve() as MethodDef; /// <summary> /// Resolves the method /// </summary> /// <returns>A <see cref="MethodDef"/> instance</returns> /// <exception cref="MemberRefResolveException">If the method couldn't be resolved</exception> public MethodDef ResolveMethodThrow() { var method = ResolveMethod(); if (method is not null) return method; throw new MemberRefResolveException($"Could not resolve method: {this} ({this.GetDefinitionAssembly()})"); } bool IContainsGenericParameter.ContainsGenericParameter => TypeHelper.ContainsGenericParameter(this); /// <summary> /// Gets a <see cref="GenericParamContext"/> that can be used as signature context /// </summary> /// <param name="gpContext">Context passed to the constructor</param> /// <param name="class">Field/method class owner</param> /// <returns></returns> protected static GenericParamContext GetSignatureGenericParamContext(GenericParamContext gpContext, IMemberRefParent @class) { TypeDef type = null; var method = gpContext.Method; if (@class is TypeSpec ts && ts.TypeSig is GenericInstSig gis) type = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef(); return new GenericParamContext(type, method); } /// <inheritdoc/> public override string ToString() => FullName; } /// <summary> /// A MemberRef row created by the user and not present in the original .NET file /// </summary> public class MemberRefUser : MemberRef { /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> public MemberRefUser(ModuleDef module) => this.module = module; /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of ref</param> public MemberRefUser(ModuleDef module, UTF8String name) { this.module = module; this.name = name; } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of field ref</param> /// <param name="sig">Field sig</param> public MemberRefUser(ModuleDef module, UTF8String name, FieldSig sig) : this(module, name, sig, null) { } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of field ref</param> /// <param name="sig">Field sig</param> /// <param name="class">Owner of field</param> public MemberRefUser(ModuleDef module, UTF8String name, FieldSig sig, IMemberRefParent @class) { this.module = module; this.name = name; this.@class = @class; signature = sig; } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of method ref</param> /// <param name="sig">Method sig</param> public MemberRefUser(ModuleDef module, UTF8String name, MethodSig sig) : this(module, name, sig, null) { } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of method ref</param> /// <param name="sig">Method sig</param> /// <param name="class">Owner of method</param> public MemberRefUser(ModuleDef module, UTF8String name, MethodSig sig, IMemberRefParent @class) { this.module = module; this.name = name; this.@class = @class; signature = sig; } } /// <summary> /// Created from a row in the MemberRef table /// </summary> sealed class MemberRefMD : MemberRef, IMDTokenProviderMD, IContainsGenericParameter2 { /// <summary>The module where this instance is located</summary> readonly ModuleDefMD readerModule; readonly uint origRid; readonly GenericParamContext gpContext; /// <inheritdoc/> public uint OrigRid => origRid; bool IContainsGenericParameter2.ContainsGenericParameter => TypeHelper.ContainsGenericParameter(this); /// <inheritdoc/> protected override void InitializeCustomAttributes() { var list = readerModule.Metadata.GetCustomAttributeRidList(Table.MemberRef, origRid); var tmp = new CustomAttributeCollection(list.Count, list, (list2, index) => readerModule.ReadCustomAttribute(list[index])); Interlocked.CompareExchange(ref customAttributes, tmp, null); } /// <inheritdoc/> protected override void InitializeCustomDebugInfos() { var list = new List<PdbCustomDebugInfo>(); readerModule.InitializeCustomDebugInfos(new MDToken(MDToken.Table, origRid), gpContext, list); Interlocked.CompareExchange(ref customDebugInfos, list, null); } /// <summary> /// Constructor /// </summary> /// <param name="readerModule">The module which contains this <c>MemberRef</c> row</param> /// <param name="rid">Row ID</param> /// <param name="gpContext">Generic parameter context</param> /// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception> /// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception> public MemberRefMD(ModuleDefMD readerModule, uint rid, GenericParamContext gpContext) { #if DEBUG if (readerModule is null) throw new ArgumentNullException("readerModule"); if (readerModule.TablesStream.MemberRefTable.IsInvalidRID(rid)) throw new BadImageFormatException($"MemberRef rid {rid} does not exist"); #endif origRid = rid; this.rid = rid; this.readerModule = readerModule; this.gpContext = gpContext; module = readerModule; bool b = readerModule.TablesStream.TryReadMemberRefRow(origRid, out var row); Debug.Assert(b); name = readerModule.StringsStream.ReadNoNull(row.Name); @class = readerModule.ResolveMemberRefParent(row.Class, gpContext); signature = readerModule.ReadSignature(row.Signature, GetSignatureGenericParamContext(gpContext, @class)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using BTCPayServer.Client.Models; using BTCPayServer.Data; using BTCPayServer.Logging; using BTCPayServer.Payments; using BTCPayServer.Services; using BTCPayServer.Services.Notifications; using BTCPayServer.Services.Notifications.Blobs; using BTCPayServer.Services.Rates; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using NBitcoin; using NBitcoin.DataEncoders; using NBXplorer; using PayoutData = BTCPayServer.Data.PayoutData; namespace BTCPayServer.HostedServices { public class CreatePullPayment { public DateTimeOffset? ExpiresAt { get; set; } public DateTimeOffset? StartsAt { get; set; } public string StoreId { get; set; } public string Name { get; set; } public string Description { get; set; } public decimal Amount { get; set; } public string Currency { get; set; } public string CustomCSSLink { get; set; } public string EmbeddedCSS { get; set; } public PaymentMethodId[] PaymentMethodIds { get; set; } public TimeSpan? Period { get; set; } public TimeSpan? BOLT11Expiration { get; set; } } public class PullPaymentHostedService : BaseAsyncService { public class CancelRequest { public CancelRequest(string pullPaymentId) { ArgumentNullException.ThrowIfNull(pullPaymentId); PullPaymentId = pullPaymentId; } public CancelRequest(string[] payoutIds) { ArgumentNullException.ThrowIfNull(payoutIds); PayoutIds = payoutIds; } public string PullPaymentId { get; set; } public string[] PayoutIds { get; set; } internal TaskCompletionSource<bool> Completion { get; set; } } public class PayoutApproval { public enum Result { Ok, NotFound, InvalidState, TooLowAmount, OldRevision } public string PayoutId { get; set; } public int Revision { get; set; } public decimal Rate { get; set; } internal TaskCompletionSource<Result> Completion { get; set; } public static string GetErrorMessage(Result result) { switch (result) { case PullPaymentHostedService.PayoutApproval.Result.Ok: return "Ok"; case PullPaymentHostedService.PayoutApproval.Result.InvalidState: return "The payout is not in a state that can be approved"; case PullPaymentHostedService.PayoutApproval.Result.TooLowAmount: return "The crypto amount is too small."; case PullPaymentHostedService.PayoutApproval.Result.OldRevision: return "The crypto amount is too small."; case PullPaymentHostedService.PayoutApproval.Result.NotFound: return "The payout is not found"; default: throw new NotSupportedException(); } } } public async Task<string> CreatePullPayment(CreatePullPayment create) { ArgumentNullException.ThrowIfNull(create); if (create.Amount <= 0.0m) throw new ArgumentException("Amount out of bound", nameof(create)); using var ctx = this._dbContextFactory.CreateContext(); var o = new Data.PullPaymentData(); o.StartDate = create.StartsAt is DateTimeOffset date ? date : DateTimeOffset.UtcNow - TimeSpan.FromSeconds(1.0); o.EndDate = create.ExpiresAt is DateTimeOffset date2 ? new DateTimeOffset?(date2) : null; o.Period = create.Period is TimeSpan period ? (long?)period.TotalSeconds : null; o.Id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(20)); o.StoreId = create.StoreId; o.SetBlob(new PullPaymentBlob() { Name = create.Name ?? string.Empty, Description = create.Description ?? string.Empty, Currency = create.Currency, Limit = create.Amount, Period = o.Period is long periodSeconds ? (TimeSpan?)TimeSpan.FromSeconds(periodSeconds) : null, SupportedPaymentMethods = create.PaymentMethodIds, View = new PullPaymentBlob.PullPaymentView() { Title = create.Name ?? string.Empty, Description = create.Description ?? string.Empty, CustomCSSLink = create.CustomCSSLink, Email = null, EmbeddedCSS = create.EmbeddedCSS, }, BOLT11Expiration = create.BOLT11Expiration ?? TimeSpan.FromDays(30.0) }); ctx.PullPayments.Add(o); await ctx.SaveChangesAsync(); return o.Id; } public async Task<Data.PullPaymentData> GetPullPayment(string pullPaymentId, bool includePayouts) { await using var ctx = _dbContextFactory.CreateContext(); IQueryable<Data.PullPaymentData> query = ctx.PullPayments; if (includePayouts) query = query.Include(data => data.Payouts); return await query.FirstOrDefaultAsync(data => data.Id == pullPaymentId); } class PayoutRequest { public PayoutRequest(TaskCompletionSource<ClaimRequest.ClaimResponse> completionSource, ClaimRequest request) { ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(completionSource); Completion = completionSource; ClaimRequest = request; } public TaskCompletionSource<ClaimRequest.ClaimResponse> Completion { get; set; } public ClaimRequest ClaimRequest { get; } } public PullPaymentHostedService(ApplicationDbContextFactory dbContextFactory, BTCPayNetworkJsonSerializerSettings jsonSerializerSettings, CurrencyNameTable currencyNameTable, EventAggregator eventAggregator, BTCPayNetworkProvider networkProvider, NotificationSender notificationSender, RateFetcher rateFetcher, IEnumerable<IPayoutHandler> payoutHandlers, ILogger<PullPaymentHostedService> logger, Logs logs) : base(logs) { _dbContextFactory = dbContextFactory; _jsonSerializerSettings = jsonSerializerSettings; _currencyNameTable = currencyNameTable; _eventAggregator = eventAggregator; _networkProvider = networkProvider; _notificationSender = notificationSender; _rateFetcher = rateFetcher; _payoutHandlers = payoutHandlers; _logger = logger; } Channel<object> _Channel; private readonly ApplicationDbContextFactory _dbContextFactory; private readonly BTCPayNetworkJsonSerializerSettings _jsonSerializerSettings; private readonly CurrencyNameTable _currencyNameTable; private readonly EventAggregator _eventAggregator; private readonly BTCPayNetworkProvider _networkProvider; private readonly NotificationSender _notificationSender; private readonly RateFetcher _rateFetcher; private readonly IEnumerable<IPayoutHandler> _payoutHandlers; private readonly ILogger<PullPaymentHostedService> _logger; private readonly CompositeDisposable _subscriptions = new CompositeDisposable(); internal override Task[] InitializeTasks() { _Channel = Channel.CreateUnbounded<object>(); foreach (IPayoutHandler payoutHandler in _payoutHandlers) { payoutHandler.StartBackgroundCheck(Subscribe); } return new[] { Loop() }; } private void Subscribe(params Type[] events) { foreach (Type @event in events) { _eventAggregator.Subscribe(@event, (subscription, o) => _Channel.Writer.TryWrite(o)); } } private async Task Loop() { await foreach (var o in _Channel.Reader.ReadAllAsync()) { if (o is PayoutRequest req) { await HandleCreatePayout(req); } if (o is PayoutApproval approv) { await HandleApproval(approv); } if (o is CancelRequest cancel) { await HandleCancel(cancel); } if (o is InternalPayoutPaidRequest paid) { await HandleMarkPaid(paid); } foreach (IPayoutHandler payoutHandler in _payoutHandlers) { try { await payoutHandler.BackgroundCheck(o); } catch (Exception e) { _logger.LogError(e, "PayoutHandler failed during BackgroundCheck"); } } } } public Task<RateResult> GetRate(PayoutData payout, string explicitRateRule, CancellationToken cancellationToken) { var ppBlob = payout.PullPaymentData.GetBlob(); var currencyPair = new Rating.CurrencyPair(payout.GetPaymentMethodId().CryptoCode, ppBlob.Currency); Rating.RateRule rule = null; try { if (explicitRateRule is null) { var storeBlob = payout.PullPaymentData.StoreData.GetStoreBlob(); var rules = storeBlob.GetRateRules(_networkProvider); rules.Spread = 0.0m; rule = rules.GetRuleFor(currencyPair); } else { rule = Rating.RateRule.CreateFromExpression(explicitRateRule, currencyPair); } } catch (Exception) { throw new FormatException("Invalid RateRule"); } return _rateFetcher.FetchRate(rule, cancellationToken); } public Task<PayoutApproval.Result> Approve(PayoutApproval approval) { approval.Completion = new TaskCompletionSource<PayoutApproval.Result>(TaskCreationOptions.RunContinuationsAsynchronously); if (!_Channel.Writer.TryWrite(approval)) throw new ObjectDisposedException(nameof(PullPaymentHostedService)); return approval.Completion.Task; } private async Task HandleApproval(PayoutApproval req) { try { using var ctx = _dbContextFactory.CreateContext(); var payout = await ctx.Payouts.Include(p => p.PullPaymentData).Where(p => p.Id == req.PayoutId).FirstOrDefaultAsync(); if (payout is null) { req.Completion.SetResult(PayoutApproval.Result.NotFound); return; } if (payout.State != PayoutState.AwaitingApproval) { req.Completion.SetResult(PayoutApproval.Result.InvalidState); return; } var payoutBlob = payout.GetBlob(this._jsonSerializerSettings); if (payoutBlob.Revision != req.Revision) { req.Completion.SetResult(PayoutApproval.Result.OldRevision); return; } if (!PaymentMethodId.TryParse(payout.PaymentMethodId, out var paymentMethod)) { req.Completion.SetResult(PayoutApproval.Result.NotFound); return; } payout.State = PayoutState.AwaitingPayment; if (paymentMethod.CryptoCode == payout.PullPaymentData.GetBlob().Currency) req.Rate = 1.0m; var cryptoAmount = payoutBlob.Amount / req.Rate; var payoutHandler = _payoutHandlers.FindPayoutHandler(paymentMethod); if (payoutHandler is null) throw new InvalidOperationException($"No payout handler for {paymentMethod}"); var dest = await payoutHandler.ParseClaimDestination(paymentMethod, payoutBlob.Destination); decimal minimumCryptoAmount = await payoutHandler.GetMinimumPayoutAmount(paymentMethod, dest.destination); if (cryptoAmount < minimumCryptoAmount) { req.Completion.TrySetResult(PayoutApproval.Result.TooLowAmount); return; } payoutBlob.CryptoAmount = BTCPayServer.Extensions.RoundUp(cryptoAmount, _networkProvider.GetNetwork(paymentMethod.CryptoCode).Divisibility); payout.SetBlob(payoutBlob, _jsonSerializerSettings); await ctx.SaveChangesAsync(); req.Completion.SetResult(PayoutApproval.Result.Ok); } catch (Exception ex) { req.Completion.TrySetException(ex); } } private async Task HandleMarkPaid(InternalPayoutPaidRequest req) { try { await using var ctx = _dbContextFactory.CreateContext(); var payout = await ctx.Payouts.Include(p => p.PullPaymentData).Where(p => p.Id == req.Request.PayoutId).FirstOrDefaultAsync(); if (payout is null) { req.Completion.SetResult(PayoutPaidRequest.PayoutPaidResult.NotFound); return; } if (payout.State != PayoutState.AwaitingPayment) { req.Completion.SetResult(PayoutPaidRequest.PayoutPaidResult.InvalidState); return; } if (req.Request.Proof != null) { payout.SetProofBlob(req.Request.Proof); } payout.State = PayoutState.Completed; await ctx.SaveChangesAsync(); req.Completion.SetResult(PayoutPaidRequest.PayoutPaidResult.Ok); } catch (Exception ex) { req.Completion.TrySetException(ex); } } private async Task HandleCreatePayout(PayoutRequest req) { try { DateTimeOffset now = DateTimeOffset.UtcNow; await using var ctx = _dbContextFactory.CreateContext(); var pp = await ctx.PullPayments.FindAsync(req.ClaimRequest.PullPaymentId); if (pp is null || pp.Archived) { req.Completion.TrySetResult(new ClaimRequest.ClaimResponse(ClaimRequest.ClaimResult.Archived)); return; } if (pp.IsExpired(now)) { req.Completion.TrySetResult(new ClaimRequest.ClaimResponse(ClaimRequest.ClaimResult.Expired)); return; } if (!pp.HasStarted(now)) { req.Completion.TrySetResult(new ClaimRequest.ClaimResponse(ClaimRequest.ClaimResult.NotStarted)); return; } var ppBlob = pp.GetBlob(); var payoutHandler = _payoutHandlers.FindPayoutHandler(req.ClaimRequest.PaymentMethodId); if (!ppBlob.SupportedPaymentMethods.Contains(req.ClaimRequest.PaymentMethodId) || payoutHandler is null) { req.Completion.TrySetResult(new ClaimRequest.ClaimResponse(ClaimRequest.ClaimResult.PaymentMethodNotSupported)); return; } if (req.ClaimRequest.Destination.Id != null) { if (await ctx.Payouts.AnyAsync(data => data.Destination.Equals(req.ClaimRequest.Destination.Id) && data.State != PayoutState.Completed && data.State != PayoutState.Cancelled )) { req.Completion.TrySetResult(new ClaimRequest.ClaimResponse(ClaimRequest.ClaimResult.Duplicate)); return; } } if (req.ClaimRequest.Value < await payoutHandler.GetMinimumPayoutAmount(req.ClaimRequest.PaymentMethodId, req.ClaimRequest.Destination)) { req.Completion.TrySetResult(new ClaimRequest.ClaimResponse(ClaimRequest.ClaimResult.AmountTooLow)); return; } var payouts = (await ctx.Payouts.GetPayoutInPeriod(pp, now) .Where(p => p.State != PayoutState.Cancelled) .ToListAsync()) .Select(o => new { Entity = o, Blob = o.GetBlob(_jsonSerializerSettings) }); var limit = ppBlob.Limit; var totalPayout = payouts.Select(p => p.Blob.Amount).Sum(); var claimed = req.ClaimRequest.Value is decimal v ? v : limit - totalPayout; if (totalPayout + claimed > limit) { req.Completion.TrySetResult(new ClaimRequest.ClaimResponse(ClaimRequest.ClaimResult.Overdraft)); return; } var payout = new PayoutData() { Id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(20)), Date = now, State = PayoutState.AwaitingApproval, PullPaymentDataId = req.ClaimRequest.PullPaymentId, PaymentMethodId = req.ClaimRequest.PaymentMethodId.ToString(), Destination = req.ClaimRequest.Destination.Id }; if (claimed < ppBlob.MinimumClaim || claimed == 0.0m) { req.Completion.TrySetResult(new ClaimRequest.ClaimResponse(ClaimRequest.ClaimResult.AmountTooLow)); return; } var payoutBlob = new PayoutBlob() { Amount = claimed, Destination = req.ClaimRequest.Destination.ToString() }; payout.SetBlob(payoutBlob, _jsonSerializerSettings); await ctx.Payouts.AddAsync(payout); try { await payoutHandler.TrackClaim(req.ClaimRequest.PaymentMethodId, req.ClaimRequest.Destination); await ctx.SaveChangesAsync(); req.Completion.TrySetResult(new ClaimRequest.ClaimResponse(ClaimRequest.ClaimResult.Ok, payout)); await _notificationSender.SendNotification(new StoreScope(pp.StoreId), new PayoutNotification() { StoreId = pp.StoreId, Currency = ppBlob.Currency, PaymentMethod = payout.PaymentMethodId, PayoutId = pp.Id }); } catch (DbUpdateException) { req.Completion.TrySetResult(new ClaimRequest.ClaimResponse(ClaimRequest.ClaimResult.Duplicate)); } } catch (Exception ex) { req.Completion.TrySetException(ex); } } private async Task HandleCancel(CancelRequest cancel) { try { using var ctx = this._dbContextFactory.CreateContext(); List<PayoutData> payouts = null; if (cancel.PullPaymentId != null) { ctx.PullPayments.Attach(new Data.PullPaymentData() { Id = cancel.PullPaymentId, Archived = true }) .Property(o => o.Archived).IsModified = true; payouts = await ctx.Payouts .Where(p => p.PullPaymentDataId == cancel.PullPaymentId) .ToListAsync(); } else { var payoutIds = cancel.PayoutIds.ToHashSet(); payouts = await ctx.Payouts .Where(p => payoutIds.Contains(p.Id)) .ToListAsync(); } foreach (var payout in payouts) { if (payout.State != PayoutState.Completed && payout.State != PayoutState.InProgress) payout.State = PayoutState.Cancelled; } await ctx.SaveChangesAsync(); cancel.Completion.TrySetResult(true); } catch (Exception ex) { cancel.Completion.TrySetException(ex); } } public Task Cancel(CancelRequest cancelRequest) { CancellationToken.ThrowIfCancellationRequested(); var cts = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); cancelRequest.Completion = cts; if (!_Channel.Writer.TryWrite(cancelRequest)) throw new ObjectDisposedException(nameof(PullPaymentHostedService)); return cts.Task; } public Task<ClaimRequest.ClaimResponse> Claim(ClaimRequest request) { CancellationToken.ThrowIfCancellationRequested(); var cts = new TaskCompletionSource<ClaimRequest.ClaimResponse>(TaskCreationOptions.RunContinuationsAsynchronously); if (!_Channel.Writer.TryWrite(new PayoutRequest(cts, request))) throw new ObjectDisposedException(nameof(PullPaymentHostedService)); return cts.Task; } public override Task StopAsync(CancellationToken cancellationToken) { _Channel?.Writer.Complete(); _subscriptions.Dispose(); return base.StopAsync(cancellationToken); } public Task<PayoutPaidRequest.PayoutPaidResult> MarkPaid(PayoutPaidRequest request) { CancellationToken.ThrowIfCancellationRequested(); var cts = new TaskCompletionSource<PayoutPaidRequest.PayoutPaidResult>(TaskCreationOptions.RunContinuationsAsynchronously); if (!_Channel.Writer.TryWrite(new InternalPayoutPaidRequest(cts, request))) throw new ObjectDisposedException(nameof(PullPaymentHostedService)); return cts.Task; } class InternalPayoutPaidRequest { public InternalPayoutPaidRequest(TaskCompletionSource<PayoutPaidRequest.PayoutPaidResult> completionSource, PayoutPaidRequest request) { ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(completionSource); Completion = completionSource; Request = request; } public TaskCompletionSource<PayoutPaidRequest.PayoutPaidResult> Completion { get; set; } public PayoutPaidRequest Request { get; } } } public class PayoutPaidRequest { public enum PayoutPaidResult { Ok, NotFound, InvalidState } public string PayoutId { get; set; } public ManualPayoutProof Proof { get; set; } public static string GetErrorMessage(PayoutPaidResult result) { switch (result) { case PayoutPaidResult.NotFound: return "The payout is not found"; case PayoutPaidResult.Ok: return "Ok"; case PayoutPaidResult.InvalidState: return "The payout is not in a state that can be marked as paid"; default: throw new NotSupportedException(); } } } public class ClaimRequest { public static string GetErrorMessage(ClaimResult result) { switch (result) { case ClaimResult.Ok: break; case ClaimResult.Duplicate: return "This address is already used for another payout"; case ClaimResult.Expired: return "This pull payment is expired"; case ClaimResult.NotStarted: return "This pull payment has yet started"; case ClaimResult.Archived: return "This pull payment has been archived"; case ClaimResult.Overdraft: return "The payout amount overdraft the pull payment's limit"; case ClaimResult.AmountTooLow: return "The requested payout amount is too low"; case ClaimResult.PaymentMethodNotSupported: return "This payment method is not supported by the pull payment"; default: throw new NotSupportedException("Unsupported ClaimResult"); } return null; } public class ClaimResponse { public ClaimResponse(ClaimResult result, PayoutData payoutData = null) { Result = result; PayoutData = payoutData; } public ClaimResult Result { get; set; } public PayoutData PayoutData { get; set; } } public enum ClaimResult { Ok, Duplicate, Expired, Archived, NotStarted, Overdraft, AmountTooLow, PaymentMethodNotSupported, } public PaymentMethodId PaymentMethodId { get; set; } public string PullPaymentId { get; set; } public decimal? Value { get; set; } public IClaimDestination Destination { get; set; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; namespace MS.Internal.Xml.XPath { // See comments to QueryBuilder.Props // Not all of them are used currently internal enum QueryProps { None = 0x00, Position = 0x01, Count = 0x02, Cached = 0x04, Reverse = 0x08, Merge = 0x10, }; // Turn off DebuggerDisplayAttribute. in subclasses of Query. // Calls to Current in the XPathNavigator.DebuggerDisplayProxy may change state or throw [DebuggerDisplay("{ToString()}")] internal abstract class Query : ResetableIterator { public Query() { } protected Query(Query other) : base(other) { } // -- XPathNodeIterator -- public override bool MoveNext() { return Advance() != null; } public override int Count { get { // Query can be ordered in reverse order. So we can't assume like base.Count that last node has greatest position. if (count == -1) { Query clone = (Query)this.Clone(); clone.Reset(); count = 0; while (clone.MoveNext()) count++; } return count; } } // -------------------- Query ------------------ public virtual void SetXsltContext(XsltContext context) { } public abstract object Evaluate(XPathNodeIterator nodeIterator); public abstract XPathNavigator Advance(); public virtual XPathNavigator MatchNode(XPathNavigator current) { throw XPathException.Create(SR.Xp_InvalidPattern); } public virtual double XsltDefaultPriority { get { return 0.5; } } public abstract XPathResultType StaticType { get; } public virtual QueryProps Properties { get { return QueryProps.Merge; } } // ----------------- Helper methods ------------- public static Query Clone(Query input) { if (input != null) { return (Query)input.Clone(); } return null; } protected static XPathNodeIterator Clone(XPathNodeIterator input) { if (input != null) { return input.Clone(); } return null; } protected static XPathNavigator Clone(XPathNavigator input) { if (input != null) { return input.Clone(); } return null; } // ----------------------------------------------------- // Set of methods to support insertion to sorted buffer. // buffer is always sorted here public static bool Insert(List<XPathNavigator> buffer, XPathNavigator nav) { int l = 0; int r = buffer.Count; // In most cases nodes are already sorted. // This means that nav often will be equal or after then last item in the buffer // So let's check this first. if (r != 0) { switch (CompareNodes(buffer[r - 1], nav)) { case XmlNodeOrder.Same: return false; case XmlNodeOrder.Before: buffer.Add(nav.Clone()); return true; default: r--; break; } } while (l < r) { int m = GetMedian(l, r); switch (CompareNodes(buffer[m], nav)) { case XmlNodeOrder.Same: return false; case XmlNodeOrder.Before: l = m + 1; break; default: r = m; break; } } AssertDOD(buffer, nav, l); buffer.Insert(l, nav.Clone()); return true; } private static int GetMedian(int l, int r) { Debug.Assert(0 <= l && l < r); return (int)(((uint)l + (uint)r) >> 1); } public static XmlNodeOrder CompareNodes(XPathNavigator l, XPathNavigator r) { XmlNodeOrder cmp = l.ComparePosition(r); if (cmp == XmlNodeOrder.Unknown) { XPathNavigator copy = l.Clone(); copy.MoveToRoot(); string baseUriL = copy.BaseURI; if (!copy.MoveTo(r)) { copy = r.Clone(); } copy.MoveToRoot(); string baseUriR = copy.BaseURI; int cmpBase = string.CompareOrdinal(baseUriL, baseUriR); cmp = ( cmpBase < 0 ? XmlNodeOrder.Before : cmpBase > 0 ? XmlNodeOrder.After : /*default*/ XmlNodeOrder.Unknown ); } return cmp; } [Conditional("DEBUG")] private static void AssertDOD(List<XPathNavigator> buffer, XPathNavigator nav, int pos) { if (nav.GetType().ToString() == "Microsoft.VisualStudio.Modeling.StoreNavigator") return; if (nav.GetType().ToString() == "System.Xml.DataDocumentXPathNavigator") return; Debug.Assert(0 <= pos && pos <= buffer.Count, "Algorithm error: Insert()"); XmlNodeOrder cmp; if (0 < pos) { cmp = CompareNodes(buffer[pos - 1], nav); Debug.Assert(cmp == XmlNodeOrder.Before, "Algorithm error: Insert()"); } if (pos < buffer.Count) { cmp = CompareNodes(nav, buffer[pos]); Debug.Assert(cmp == XmlNodeOrder.Before, "Algorithm error: Insert()"); } } [Conditional("DEBUG")] public static void AssertQuery(Query query) { Debug.Assert(query != null, "AssertQuery(): query == null"); if (query is FunctionQuery) return; // Temp Fix. Functions (as document()) return now unordered sequences query = Clone(query); XPathNavigator last = null; XPathNavigator curr; int querySize = query.Clone().Count; int actualSize = 0; while ((curr = query.Advance()) != null) { if (curr.GetType().ToString() == "Microsoft.VisualStudio.Modeling.StoreNavigator") return; if (curr.GetType().ToString() == "System.Xml.DataDocumentXPathNavigator") return; Debug.Assert(curr == query.Current, "AssertQuery(): query.Advance() != query.Current"); if (last != null) { if (last.NodeType == XPathNodeType.Namespace && curr.NodeType == XPathNodeType.Namespace) { // NamespaceQuery reports namsespaces in mixed order. // Ignore this for now. // It seams that this doesn't breake other queries becasue NS can't have children } else { XmlNodeOrder cmp = CompareNodes(last, curr); Debug.Assert(cmp == XmlNodeOrder.Before, "AssertQuery(): Wrong node order"); } } last = curr.Clone(); actualSize++; } Debug.Assert(actualSize == querySize, "AssertQuery(): actualSize != querySize"); } // =================== XPathResultType_Navigator ====================== // In v.1.0 and v.1.1 XPathResultType.Navigator is defined == to XPathResultType.String // This is source for multiple bugs or additional type casts. // To fix all of them in one change in v.2 we internaly use one more value: public const XPathResultType XPathResultType_Navigator = (XPathResultType)4; // The biggest challenge in this change is preserve backward compatibility with v.1.1 // To achive this in all places where we accept from or report to user XPathResultType. // On my best knowledge this happens only in XsltContext.ResolveFunction() / IXsltContextFunction.ReturnType protected XPathResultType GetXPathType(object value) { if (value is XPathNodeIterator) return XPathResultType.NodeSet; if (value is string) return XPathResultType.String; if (value is double) return XPathResultType.Number; if (value is bool) return XPathResultType.Boolean; Debug.Assert(value is XPathNavigator, "Unknown value type"); return XPathResultType_Navigator; } // =================== Serialization ====================== public virtual void PrintQuery(XmlWriter w) { w.WriteElementString(this.GetType().Name, string.Empty); } } }
namespace Checkers { partial class PreferencesDialog { /// <summary> /// Disposes of the resources (other than memory) used by the <see cref="T:System.Windows.Forms.Form"/>. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if(disposing) { if(components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PreferencesDialog)); this.imlTabs = new System.Windows.Forms.ImageList(this.components); this.tabPreferences = new System.Windows.Forms.TabControl(); this.tabGeneral = new System.Windows.Forms.TabPage(); this.grpGeneral = new System.Windows.Forms.GroupBox(); this.chkShowJumpMessage = new System.Windows.Forms.CheckBox(); this.chkHighlightSelection = new System.Windows.Forms.CheckBox(); this.chkHighlightPossibleMoves = new System.Windows.Forms.CheckBox(); this.chkShowTextFeedback = new System.Windows.Forms.CheckBox(); this.grpNet = new System.Windows.Forms.GroupBox(); this.chkFlashWindowOnTurn = new System.Windows.Forms.CheckBox(); this.chkFlashWindowOnMessage = new System.Windows.Forms.CheckBox(); this.chkShowNetPanelOnMessage = new System.Windows.Forms.CheckBox(); this.chkFlashWindowOnGameEvents = new System.Windows.Forms.CheckBox(); this.tabBoard = new System.Windows.Forms.TabPage(); this.lblColorCaption = new System.Windows.Forms.Label(); this.lblBoardBackColor = new System.Windows.Forms.Label(); this.picBoardBackColor = new System.Windows.Forms.PictureBox(); this.menuColor = new System.Windows.Forms.ContextMenu(); this.menuChangeColor = new System.Windows.Forms.MenuItem(); this.menuColorLine01 = new System.Windows.Forms.MenuItem(); this.menuSetDefault = new System.Windows.Forms.MenuItem(); this.lblBackColor = new System.Windows.Forms.Label(); this.picBackColor = new System.Windows.Forms.PictureBox(); this.lblBoardForeColor = new System.Windows.Forms.Label(); this.picBoardForeColor = new System.Windows.Forms.PictureBox(); this.picBoardGridColor = new System.Windows.Forms.PictureBox(); this.lblBoardGridColor = new System.Windows.Forms.Label(); this.tabSounds = new System.Windows.Forms.TabPage(); this.chkMuteSounds = new System.Windows.Forms.CheckBox(); this.lstSounds = new System.Windows.Forms.ListBox(); this.lblSounds = new System.Windows.Forms.Label(); this.txtSoundFile = new System.Windows.Forms.TextBox(); this.btnSoundFile = new System.Windows.Forms.Button(); this.btnSoundPreview = new System.Windows.Forms.Button(); this.lblSoundFile = new System.Windows.Forms.Label(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.dlgColorDialog = new System.Windows.Forms.ColorDialog(); this.dlgOpenSound = new System.Windows.Forms.OpenFileDialog(); this.btnDefault = new System.Windows.Forms.Button(); this.panTitle = new System.Windows.Forms.Panel(); this.lblTitle = new System.Windows.Forms.Label(); this.tabPreferences.SuspendLayout(); this.tabGeneral.SuspendLayout(); this.grpGeneral.SuspendLayout(); this.grpNet.SuspendLayout(); this.tabBoard.SuspendLayout(); this.tabSounds.SuspendLayout(); this.panTitle.SuspendLayout(); this.SuspendLayout(); // // imlTabs // this.imlTabs.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit; this.imlTabs.ImageSize = new System.Drawing.Size(32, 32); this.imlTabs.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imlTabs.ImageStream"))); this.imlTabs.TransparentColor = System.Drawing.Color.Transparent; // // tabPreferences // this.tabPreferences.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.tabPreferences.Appearance = System.Windows.Forms.TabAppearance.Buttons; this.tabPreferences.Controls.AddRange(new System.Windows.Forms.Control[] { this.tabGeneral, this.tabBoard, this.tabSounds}); this.tabPreferences.ImageList = this.imlTabs; this.tabPreferences.Location = new System.Drawing.Point(8, 8); this.tabPreferences.Multiline = true; this.tabPreferences.Name = "tabPreferences"; this.tabPreferences.SelectedIndex = 0; this.tabPreferences.Size = new System.Drawing.Size(396, 324); this.tabPreferences.TabIndex = 1; this.tabPreferences.SelectedIndexChanged += new System.EventHandler(this.tabPreferences_SelectedIndexChanged); // // tabGeneral // this.tabGeneral.Controls.AddRange(new System.Windows.Forms.Control[] { this.grpGeneral, this.grpNet}); this.tabGeneral.ImageIndex = 0; this.tabGeneral.Location = new System.Drawing.Point(4, 42); this.tabGeneral.Name = "tabGeneral"; this.tabGeneral.Size = new System.Drawing.Size(388, 278); this.tabGeneral.TabIndex = 0; this.tabGeneral.Text = "General"; // // grpGeneral // this.grpGeneral.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.grpGeneral.Controls.AddRange(new System.Windows.Forms.Control[] { this.chkShowJumpMessage, this.chkHighlightSelection, this.chkHighlightPossibleMoves, this.chkShowTextFeedback}); this.grpGeneral.Location = new System.Drawing.Point(0, 36); this.grpGeneral.Name = "grpGeneral"; this.grpGeneral.Size = new System.Drawing.Size(386, 112); this.grpGeneral.TabIndex = 0; this.grpGeneral.TabStop = false; this.grpGeneral.Text = "General"; // // chkShowJumpMessage // this.chkShowJumpMessage.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.chkShowJumpMessage.Location = new System.Drawing.Point(8, 84); this.chkShowJumpMessage.Name = "chkShowJumpMessage"; this.chkShowJumpMessage.Size = new System.Drawing.Size(370, 20); this.chkShowJumpMessage.TabIndex = 3; this.chkShowJumpMessage.Text = "Show detailed message when a jump must be completed"; // // chkHighlightSelection // this.chkHighlightSelection.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.chkHighlightSelection.Location = new System.Drawing.Point(8, 24); this.chkHighlightSelection.Name = "chkHighlightSelection"; this.chkHighlightSelection.Size = new System.Drawing.Size(370, 20); this.chkHighlightSelection.TabIndex = 0; this.chkHighlightSelection.Text = "Highlight selected squares"; // // chkHighlightPossibleMoves // this.chkHighlightPossibleMoves.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.chkHighlightPossibleMoves.Location = new System.Drawing.Point(8, 44); this.chkHighlightPossibleMoves.Name = "chkHighlightPossibleMoves"; this.chkHighlightPossibleMoves.Size = new System.Drawing.Size(370, 20); this.chkHighlightPossibleMoves.TabIndex = 1; this.chkHighlightPossibleMoves.Text = "Highlight possible moves"; // // chkShowTextFeedback // this.chkShowTextFeedback.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.chkShowTextFeedback.Location = new System.Drawing.Point(8, 64); this.chkShowTextFeedback.Name = "chkShowTextFeedback"; this.chkShowTextFeedback.Size = new System.Drawing.Size(370, 20); this.chkShowTextFeedback.TabIndex = 2; this.chkShowTextFeedback.Text = "Show text feedback"; // // grpNet // this.grpNet.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.grpNet.Controls.AddRange(new System.Windows.Forms.Control[] { this.chkFlashWindowOnTurn, this.chkFlashWindowOnMessage, this.chkShowNetPanelOnMessage, this.chkFlashWindowOnGameEvents}); this.grpNet.Location = new System.Drawing.Point(0, 160); this.grpNet.Name = "grpNet"; this.grpNet.Size = new System.Drawing.Size(386, 112); this.grpNet.TabIndex = 1; this.grpNet.TabStop = false; this.grpNet.Text = "Net Settings"; // // chkFlashWindowOnTurn // this.chkFlashWindowOnTurn.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.chkFlashWindowOnTurn.Location = new System.Drawing.Point(8, 44); this.chkFlashWindowOnTurn.Name = "chkFlashWindowOnTurn"; this.chkFlashWindowOnTurn.Size = new System.Drawing.Size(370, 20); this.chkFlashWindowOnTurn.TabIndex = 1; this.chkFlashWindowOnTurn.Text = "Flash window when your turn"; // // chkFlashWindowOnMessage // this.chkFlashWindowOnMessage.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.chkFlashWindowOnMessage.Location = new System.Drawing.Point(8, 64); this.chkFlashWindowOnMessage.Name = "chkFlashWindowOnMessage"; this.chkFlashWindowOnMessage.Size = new System.Drawing.Size(370, 20); this.chkFlashWindowOnMessage.TabIndex = 2; this.chkFlashWindowOnMessage.Text = "Flash window when a message is received"; // // chkShowNetPanelOnMessage // this.chkShowNetPanelOnMessage.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.chkShowNetPanelOnMessage.Location = new System.Drawing.Point(8, 84); this.chkShowNetPanelOnMessage.Name = "chkShowNetPanelOnMessage"; this.chkShowNetPanelOnMessage.Size = new System.Drawing.Size(370, 20); this.chkShowNetPanelOnMessage.TabIndex = 3; this.chkShowNetPanelOnMessage.Text = "Show Net Panel when message is received"; // // chkFlashWindowOnGameEvents // this.chkFlashWindowOnGameEvents.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.chkFlashWindowOnGameEvents.Location = new System.Drawing.Point(8, 24); this.chkFlashWindowOnGameEvents.Name = "chkFlashWindowOnGameEvents"; this.chkFlashWindowOnGameEvents.Size = new System.Drawing.Size(370, 20); this.chkFlashWindowOnGameEvents.TabIndex = 0; this.chkFlashWindowOnGameEvents.Text = "Flash window on game events"; // // tabBoard // this.tabBoard.Controls.AddRange(new System.Windows.Forms.Control[] { this.lblColorCaption, this.lblBoardBackColor, this.picBoardBackColor, this.lblBackColor, this.picBackColor, this.lblBoardForeColor, this.picBoardForeColor, this.picBoardGridColor, this.lblBoardGridColor}); this.tabBoard.ImageIndex = 1; this.tabBoard.Location = new System.Drawing.Point(4, 42); this.tabBoard.Name = "tabBoard"; this.tabBoard.Size = new System.Drawing.Size(388, 278); this.tabBoard.TabIndex = 1; this.tabBoard.Text = "Appearance"; // // lblColorCaption // this.lblColorCaption.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.lblColorCaption.Location = new System.Drawing.Point(12, 188); this.lblColorCaption.Name = "lblColorCaption"; this.lblColorCaption.Size = new System.Drawing.Size(370, 32); this.lblColorCaption.TabIndex = 4; this.lblColorCaption.Text = "Note: Right-click to reset to default"; // // lblBoardBackColor // this.lblBoardBackColor.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.lblBoardBackColor.Location = new System.Drawing.Point(45, 80); this.lblBoardBackColor.Name = "lblBoardBackColor"; this.lblBoardBackColor.Size = new System.Drawing.Size(334, 16); this.lblBoardBackColor.TabIndex = 1; this.lblBoardBackColor.Text = "Board Background Color"; // // picBoardBackColor // this.picBoardBackColor.BackColor = System.Drawing.Color.White; this.picBoardBackColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.picBoardBackColor.ContextMenu = this.menuColor; this.picBoardBackColor.Location = new System.Drawing.Point(9, 72); this.picBoardBackColor.Name = "picBoardBackColor"; this.picBoardBackColor.Size = new System.Drawing.Size(32, 32); this.picBoardBackColor.TabIndex = 7; this.picBoardBackColor.TabStop = false; this.picBoardBackColor.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picColor_MouseDown); // // menuColor // this.menuColor.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuChangeColor, this.menuColorLine01, this.menuSetDefault}); // // menuChangeColor // this.menuChangeColor.Index = 0; this.menuChangeColor.Text = "&Change Color..."; this.menuChangeColor.Click += new System.EventHandler(this.menuChangeColor_Click); // // menuColorLine01 // this.menuColorLine01.Index = 1; this.menuColorLine01.Text = "-"; // // menuSetDefault // this.menuSetDefault.Index = 2; this.menuSetDefault.Text = "Set to &Default"; this.menuSetDefault.Click += new System.EventHandler(this.menuSetDefault_Click); // // lblBackColor // this.lblBackColor.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.lblBackColor.Location = new System.Drawing.Point(45, 44); this.lblBackColor.Name = "lblBackColor"; this.lblBackColor.Size = new System.Drawing.Size(334, 16); this.lblBackColor.TabIndex = 0; this.lblBackColor.Text = "Background Color"; // // picBackColor // this.picBackColor.BackColor = System.Drawing.Color.White; this.picBackColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.picBackColor.ContextMenu = this.menuColor; this.picBackColor.Location = new System.Drawing.Point(9, 36); this.picBackColor.Name = "picBackColor"; this.picBackColor.Size = new System.Drawing.Size(32, 32); this.picBackColor.TabIndex = 4; this.picBackColor.TabStop = false; this.picBackColor.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picColor_MouseDown); // // lblBoardForeColor // this.lblBoardForeColor.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.lblBoardForeColor.Location = new System.Drawing.Point(45, 116); this.lblBoardForeColor.Name = "lblBoardForeColor"; this.lblBoardForeColor.Size = new System.Drawing.Size(334, 16); this.lblBoardForeColor.TabIndex = 2; this.lblBoardForeColor.Text = "Board Foreground Color"; // // picBoardForeColor // this.picBoardForeColor.BackColor = System.Drawing.Color.White; this.picBoardForeColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.picBoardForeColor.ContextMenu = this.menuColor; this.picBoardForeColor.Location = new System.Drawing.Point(9, 108); this.picBoardForeColor.Name = "picBoardForeColor"; this.picBoardForeColor.Size = new System.Drawing.Size(32, 32); this.picBoardForeColor.TabIndex = 5; this.picBoardForeColor.TabStop = false; this.picBoardForeColor.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picColor_MouseDown); // // picBoardGridColor // this.picBoardGridColor.BackColor = System.Drawing.Color.White; this.picBoardGridColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.picBoardGridColor.ContextMenu = this.menuColor; this.picBoardGridColor.Location = new System.Drawing.Point(9, 144); this.picBoardGridColor.Name = "picBoardGridColor"; this.picBoardGridColor.Size = new System.Drawing.Size(32, 32); this.picBoardGridColor.TabIndex = 6; this.picBoardGridColor.TabStop = false; this.picBoardGridColor.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picColor_MouseDown); // // lblBoardGridColor // this.lblBoardGridColor.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.lblBoardGridColor.Location = new System.Drawing.Point(45, 152); this.lblBoardGridColor.Name = "lblBoardGridColor"; this.lblBoardGridColor.Size = new System.Drawing.Size(334, 16); this.lblBoardGridColor.TabIndex = 3; this.lblBoardGridColor.Text = "Board Foreground Color"; // // tabSounds // this.tabSounds.Controls.AddRange(new System.Windows.Forms.Control[] { this.chkMuteSounds, this.lstSounds, this.lblSounds, this.txtSoundFile, this.btnSoundFile, this.btnSoundPreview, this.lblSoundFile}); this.tabSounds.ImageIndex = 2; this.tabSounds.Location = new System.Drawing.Point(4, 42); this.tabSounds.Name = "tabSounds"; this.tabSounds.Size = new System.Drawing.Size(388, 278); this.tabSounds.TabIndex = 2; this.tabSounds.Text = "Sounds"; // // chkMuteSounds // this.chkMuteSounds.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.chkMuteSounds.Location = new System.Drawing.Point(0, 256); this.chkMuteSounds.Name = "chkMuteSounds"; this.chkMuteSounds.Size = new System.Drawing.Size(386, 20); this.chkMuteSounds.TabIndex = 6; this.chkMuteSounds.Text = "Mute all Sounds"; // // lstSounds // this.lstSounds.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.lstSounds.IntegralHeight = false; this.lstSounds.Location = new System.Drawing.Point(0, 56); this.lstSounds.Name = "lstSounds"; this.lstSounds.Size = new System.Drawing.Size(386, 148); this.lstSounds.TabIndex = 1; this.lstSounds.SelectedIndexChanged += new System.EventHandler(this.lstSounds_SelectedIndexChanged); // // lblSounds // this.lblSounds.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.lblSounds.Location = new System.Drawing.Point(0, 36); this.lblSounds.Name = "lblSounds"; this.lblSounds.Size = new System.Drawing.Size(390, 20); this.lblSounds.TabIndex = 0; this.lblSounds.Text = "Game Sounds:"; this.lblSounds.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // txtSoundFile // this.txtSoundFile.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.txtSoundFile.Location = new System.Drawing.Point(0, 228); this.txtSoundFile.Name = "txtSoundFile"; this.txtSoundFile.Size = new System.Drawing.Size(338, 20); this.txtSoundFile.TabIndex = 3; this.txtSoundFile.Text = ""; this.txtSoundFile.TextChanged += new System.EventHandler(this.txtSoundFile_TextChanged); // // btnSoundFile // this.btnSoundFile.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right); this.btnSoundFile.Location = new System.Drawing.Point(366, 228); this.btnSoundFile.Name = "btnSoundFile"; this.btnSoundFile.Size = new System.Drawing.Size(20, 20); this.btnSoundFile.TabIndex = 5; this.btnSoundFile.Text = ".."; this.btnSoundFile.Click += new System.EventHandler(this.btnSoundFile_Click); // // btnSoundPreview // this.btnSoundPreview.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right); this.btnSoundPreview.Location = new System.Drawing.Point(342, 228); this.btnSoundPreview.Name = "btnSoundPreview"; this.btnSoundPreview.Size = new System.Drawing.Size(20, 20); this.btnSoundPreview.TabIndex = 4; this.btnSoundPreview.Text = "!!"; this.btnSoundPreview.Click += new System.EventHandler(this.btnSoundPreview_Click); // // lblSoundFile // this.lblSoundFile.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.lblSoundFile.Location = new System.Drawing.Point(0, 208); this.lblSoundFile.Name = "lblSoundFile"; this.lblSoundFile.Size = new System.Drawing.Size(390, 20); this.lblSoundFile.TabIndex = 2; this.lblSoundFile.Text = "Sound File:"; this.lblSoundFile.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // btnCancel // this.btnCancel.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(314, 337); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(88, 36); this.btnCancel.TabIndex = 4; this.btnCancel.Text = "&Cancel"; // // btnOK // this.btnOK.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right); this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOK.Location = new System.Drawing.Point(218, 337); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(88, 36); this.btnOK.TabIndex = 3; this.btnOK.Text = "&OK"; // // dlgColorDialog // this.dlgColorDialog.AnyColor = true; this.dlgColorDialog.FullOpen = true; // // dlgOpenSound // this.dlgOpenSound.DefaultExt = "wav"; this.dlgOpenSound.Filter = "Wave Files (*.wav)|*.wav|All Files (*.*)|*.*"; this.dlgOpenSound.ReadOnlyChecked = true; this.dlgOpenSound.Title = "Browse for Sound"; // // btnDefault // this.btnDefault.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right); this.btnDefault.Location = new System.Drawing.Point(112, 337); this.btnDefault.Name = "btnDefault"; this.btnDefault.Size = new System.Drawing.Size(88, 36); this.btnDefault.TabIndex = 2; this.btnDefault.Text = "&Default"; this.btnDefault.Click += new System.EventHandler(this.btnDefault_Click); // // panTitle // this.panTitle.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.panTitle.Controls.AddRange(new System.Windows.Forms.Control[] { this.lblTitle}); this.panTitle.Location = new System.Drawing.Point(7, 48); this.panTitle.Name = "panTitle"; this.panTitle.Size = new System.Drawing.Size(396, 28); this.panTitle.TabIndex = 5; // // lblTitle // this.lblTitle.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.lblTitle.BackColor = System.Drawing.SystemColors.Highlight; this.lblTitle.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblTitle.ForeColor = System.Drawing.SystemColors.HighlightText; this.lblTitle.Location = new System.Drawing.Point(0, 4); this.lblTitle.Name = "lblTitle"; this.lblTitle.Size = new System.Drawing.Size(394, 24); this.lblTitle.TabIndex = 0; this.lblTitle.Text = "General"; // // frmPreferences // this.AcceptButton = this.btnOK; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(410, 380); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.panTitle, this.btnDefault, this.btnCancel, this.btnOK, this.tabPreferences}); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Name = "frmPreferences"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Checkers Preferences"; this.tabPreferences.ResumeLayout(false); this.tabGeneral.ResumeLayout(false); this.grpGeneral.ResumeLayout(false); this.grpNet.ResumeLayout(false); this.tabBoard.ResumeLayout(false); this.tabSounds.ResumeLayout(false); this.panTitle.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components; private System.Windows.Forms.OpenFileDialog dlgOpenSound; private System.Windows.Forms.Label lblBoardBackColor; private System.Windows.Forms.PictureBox picBoardBackColor; private System.Windows.Forms.Label lblBackColor; private System.Windows.Forms.PictureBox picBackColor; private System.Windows.Forms.Label lblBoardForeColor; private System.Windows.Forms.PictureBox picBoardForeColor; private System.Windows.Forms.PictureBox picBoardGridColor; private System.Windows.Forms.Label lblBoardGridColor; private System.Windows.Forms.TabControl tabPreferences; private System.Windows.Forms.TabPage tabGeneral; private System.Windows.Forms.TabPage tabBoard; private System.Windows.Forms.TabPage tabSounds; private System.Windows.Forms.ImageList imlTabs; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.GroupBox grpNet; private System.Windows.Forms.CheckBox chkShowNetPanelOnMessage; private System.Windows.Forms.CheckBox chkFlashWindowOnTurn; private System.Windows.Forms.CheckBox chkFlashWindowOnMessage; private System.Windows.Forms.ColorDialog dlgColorDialog; private System.Windows.Forms.ListBox lstSounds; private System.Windows.Forms.Label lblSounds; private System.Windows.Forms.Button btnSoundFile; private System.Windows.Forms.TextBox txtSoundFile; private System.Windows.Forms.Button btnSoundPreview; private System.Windows.Forms.Label lblSoundFile; private System.Windows.Forms.CheckBox chkMuteSounds; private System.Windows.Forms.Button btnDefault; private System.Windows.Forms.GroupBox grpGeneral; private System.Windows.Forms.CheckBox chkShowJumpMessage; private System.Windows.Forms.CheckBox chkHighlightSelection; private System.Windows.Forms.CheckBox chkHighlightPossibleMoves; private System.Windows.Forms.CheckBox chkShowTextFeedback; private System.Windows.Forms.MenuItem menuSetDefault; private System.Windows.Forms.ContextMenu menuColor; private System.Windows.Forms.MenuItem menuChangeColor; private System.Windows.Forms.MenuItem menuColorLine01; private System.Windows.Forms.CheckBox chkFlashWindowOnGameEvents; private System.Windows.Forms.Label lblColorCaption; private System.Windows.Forms.Panel panTitle; private System.Windows.Forms.Label lblTitle; } }
// 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 Xunit; namespace System.Runtime.CompilerServices { public class UnsafeTests { [Fact] public static unsafe void ReadInt32() { int expected = 10; void* address = Unsafe.AsPointer(ref expected); int ret = Unsafe.Read<int>(address); Assert.Equal(expected, ret); } [Fact] public static unsafe void WriteInt32() { int value = 10; int* address = (int*)Unsafe.AsPointer(ref value); int expected = 20; Unsafe.Write(address, expected); Assert.Equal(expected, value); Assert.Equal(expected, *address); Assert.Equal(expected, Unsafe.Read<int>(address)); } [Fact] public static unsafe void WriteBytesIntoInt32() { int value = 20; int* intAddress = (int*)Unsafe.AsPointer(ref value); byte* byteAddress = (byte*)intAddress; for (int i = 0; i < 4; i++) { Unsafe.Write(byteAddress + i, (byte)i); } Assert.Equal(0, Unsafe.Read<byte>(byteAddress)); Assert.Equal(1, Unsafe.Read<byte>(byteAddress + 1)); Assert.Equal(2, Unsafe.Read<byte>(byteAddress + 2)); Assert.Equal(3, Unsafe.Read<byte>(byteAddress + 3)); Byte4 b4 = Unsafe.Read<Byte4>(byteAddress); Assert.Equal(0, b4.B0); Assert.Equal(1, b4.B1); Assert.Equal(2, b4.B2); Assert.Equal(3, b4.B3); int expected = (b4.B3 << 24) + (b4.B2 << 16) + (b4.B1 << 8) + (b4.B0); Assert.Equal(expected, value); } [Fact] public static unsafe void LongIntoCompoundStruct() { long value = 1234567891011121314L; long* longAddress = (long*)Unsafe.AsPointer(ref value); Byte4Short2 b4s2 = Unsafe.Read<Byte4Short2>(longAddress); Assert.Equal(162, b4s2.B0); Assert.Equal(48, b4s2.B1); Assert.Equal(210, b4s2.B2); Assert.Equal(178, b4s2.B3); Assert.Equal(4340, b4s2.S4); Assert.Equal(4386, b4s2.S6); b4s2.B0 = 1; b4s2.B1 = 1; b4s2.B2 = 1; b4s2.B3 = 1; b4s2.S4 = 1; b4s2.S6 = 1; Unsafe.Write(longAddress, b4s2); long expected = 281479288520961; Assert.Equal(expected, value); Assert.Equal(expected, Unsafe.Read<long>(longAddress)); } [Fact] public static unsafe void ReadWriteDoublePointer() { int value1 = 10; int value2 = 20; int* valueAddress = (int*)Unsafe.AsPointer(ref value1); int** valueAddressPtr = &valueAddress; Unsafe.Write(valueAddressPtr, new IntPtr(&value2)); Assert.Equal(20, *(*valueAddressPtr)); Assert.Equal(20, Unsafe.Read<int>(valueAddress)); Assert.Equal(new IntPtr(valueAddress), Unsafe.Read<IntPtr>(valueAddressPtr)); Assert.Equal(20, Unsafe.Read<int>(Unsafe.Read<IntPtr>(valueAddressPtr).ToPointer())); } [Fact] public static unsafe void CopyToRef() { int value = 10; int destination = -1; Unsafe.Copy(ref destination, Unsafe.AsPointer(ref value)); Assert.Equal(10, destination); Assert.Equal(10, value); int destination2 = -1; Unsafe.Copy(ref destination2, &value); Assert.Equal(10, destination2); Assert.Equal(10, value); } [Fact] public static unsafe void CopyToVoidPtr() { int value = 10; int destination = -1; Unsafe.Copy(Unsafe.AsPointer(ref destination), ref value); Assert.Equal(10, destination); Assert.Equal(10, value); int destination2 = -1; Unsafe.Copy(&destination2, ref value); Assert.Equal(10, destination2); Assert.Equal(10, value); } [Theory] [MemberData(nameof(SizeOfData))] public static unsafe void SizeOf<T>(int expected, T valueUnused) { // valueUnused is only present to enable Xunit to call the correct generic overload. Assert.Equal(expected, Unsafe.SizeOf<T>()); } public static IEnumerable<object[]> SizeOfData() { yield return new object[] { 1, new sbyte() }; yield return new object[] { 1, new byte() }; yield return new object[] { 2, new short() }; yield return new object[] { 2, new ushort() }; yield return new object[] { 4, new int() }; yield return new object[] { 4, new uint() }; yield return new object[] { 8, new long() }; yield return new object[] { 8, new ulong() }; yield return new object[] { 4, new float() }; yield return new object[] { 8, new double() }; yield return new object[] { 4, new Byte4() }; yield return new object[] { 8, new Byte4Short2() }; yield return new object[] { 512, new Byte512() }; } [Theory] [MemberData(nameof(InitBlockData))] public static unsafe void InitBlockStack(int numBytes, byte value) { byte* stackPtr = stackalloc byte[numBytes]; Unsafe.InitBlock(stackPtr, value, (uint)numBytes); for (int i = 0; i < numBytes; i++) { Assert.Equal(stackPtr[i], value); } } [Theory] [MemberData(nameof(InitBlockData))] public static unsafe void InitBlockUnmanaged(int numBytes, byte value) { IntPtr allocatedMemory = Marshal.AllocCoTaskMem(numBytes); byte* bytePtr = (byte*)allocatedMemory.ToPointer(); Unsafe.InitBlock(bytePtr, value, (uint)numBytes); for (int i = 0; i < numBytes; i++) { Assert.Equal(bytePtr[i], value); } } public static IEnumerable<object[]> InitBlockData() { yield return new object[] { 0, 1 }; yield return new object[] { 1, 1 }; yield return new object[] { 10, 0 }; yield return new object[] { 10, 2 }; yield return new object[] { 10, 255 }; yield return new object[] { 10000, 255 }; } [Theory] [MemberData(nameof(CopyBlockData))] public static unsafe void CopyBlock(int numBytes) { byte* source = stackalloc byte[numBytes]; byte* destination = stackalloc byte[numBytes]; for (int i = 0; i < numBytes; i++) { byte value = (byte)(i % 255); source[i] = value; } Unsafe.CopyBlock(destination, source, (uint)numBytes); for (int i = 0; i < numBytes; i++) { byte value = (byte)(i % 255); Assert.Equal(value, destination[i]); Assert.Equal(source[i], destination[i]); } } public static IEnumerable<object[]> CopyBlockData() { yield return new object[] { 0 }; yield return new object[] { 1 }; yield return new object[] { 10 }; yield return new object[] { 100 }; yield return new object[] { 100000 }; } [Fact] public static void As() { object o = "Hello"; Assert.Equal("Hello", Unsafe.As<string>(o)); } [Fact] public static void DangerousAs() { // Verify that As does not perform type checks object o = new Object(); Assert.IsType(typeof(Object), Unsafe.As<string>(o)); } } [StructLayout(LayoutKind.Explicit)] public struct Byte4 { [FieldOffset(0)] public byte B0; [FieldOffset(1)] public byte B1; [FieldOffset(2)] public byte B2; [FieldOffset(3)] public byte B3; } [StructLayout(LayoutKind.Explicit)] public struct Byte4Short2 { [FieldOffset(0)] public byte B0; [FieldOffset(1)] public byte B1; [FieldOffset(2)] public byte B2; [FieldOffset(3)] public byte B3; [FieldOffset(4)] public short S4; [FieldOffset(6)] public short S6; } public unsafe struct Byte512 { public fixed byte Bytes[512]; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================================= ** ** ** ** Purpose: UCOMITypeInfo interface definition. ** ** =============================================================================*/ namespace System.Runtime.InteropServices { using System; [Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [Serializable] public enum TYPEKIND { TKIND_ENUM = 0, TKIND_RECORD = TKIND_ENUM + 1, TKIND_MODULE = TKIND_RECORD + 1, TKIND_INTERFACE = TKIND_MODULE + 1, TKIND_DISPATCH = TKIND_INTERFACE + 1, TKIND_COCLASS = TKIND_DISPATCH + 1, TKIND_ALIAS = TKIND_COCLASS + 1, TKIND_UNION = TKIND_ALIAS + 1, TKIND_MAX = TKIND_UNION + 1 } [Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [Serializable] [Flags()] public enum TYPEFLAGS : short { TYPEFLAG_FAPPOBJECT = 0x1, TYPEFLAG_FCANCREATE = 0x2, TYPEFLAG_FLICENSED = 0x4, TYPEFLAG_FPREDECLID = 0x8, TYPEFLAG_FHIDDEN = 0x10, TYPEFLAG_FCONTROL = 0x20, TYPEFLAG_FDUAL = 0x40, TYPEFLAG_FNONEXTENSIBLE = 0x80, TYPEFLAG_FOLEAUTOMATION = 0x100, TYPEFLAG_FRESTRICTED = 0x200, TYPEFLAG_FAGGREGATABLE = 0x400, TYPEFLAG_FREPLACEABLE = 0x800, TYPEFLAG_FDISPATCHABLE = 0x1000, TYPEFLAG_FREVERSEBIND = 0x2000, TYPEFLAG_FPROXY = 0x4000 } [Obsolete("Use System.Runtime.InteropServices.ComTypes.IMPLTYPEFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [Serializable] [Flags()] public enum IMPLTYPEFLAGS { IMPLTYPEFLAG_FDEFAULT = 0x1, IMPLTYPEFLAG_FSOURCE = 0x2, IMPLTYPEFLAG_FRESTRICTED = 0x4, IMPLTYPEFLAG_FDEFAULTVTABLE = 0x8, } [Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEATTR instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct TYPEATTR { // Constant used with the memid fields. public const int MEMBER_ID_NIL = unchecked((int)0xFFFFFFFF); // Actual fields of the TypeAttr struct. public Guid guid; public Int32 lcid; public Int32 dwReserved; public Int32 memidConstructor; public Int32 memidDestructor; public IntPtr lpstrSchema; public Int32 cbSizeInstance; public TYPEKIND typekind; public Int16 cFuncs; public Int16 cVars; public Int16 cImplTypes; public Int16 cbSizeVft; public Int16 cbAlignment; public TYPEFLAGS wTypeFlags; public Int16 wMajorVerNum; public Int16 wMinorVerNum; public TYPEDESC tdescAlias; public IDLDESC idldescType; } [Obsolete("Use System.Runtime.InteropServices.ComTypes.FUNCDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [StructLayout(LayoutKind.Sequential)] public struct FUNCDESC { public int memid; //MEMBERID memid; public IntPtr lprgscode; // /* [size_is(cScodes)] */ SCODE RPC_FAR *lprgscode; public IntPtr lprgelemdescParam; // /* [size_is(cParams)] */ ELEMDESC __RPC_FAR *lprgelemdescParam; public FUNCKIND funckind; //FUNCKIND funckind; public INVOKEKIND invkind; //INVOKEKIND invkind; public CALLCONV callconv; //CALLCONV callconv; public Int16 cParams; //short cParams; public Int16 cParamsOpt; //short cParamsOpt; public Int16 oVft; //short oVft; public Int16 cScodes; //short cScodes; public ELEMDESC elemdescFunc; //ELEMDESC elemdescFunc; public Int16 wFuncFlags; //WORD wFuncFlags; } [Obsolete("Use System.Runtime.InteropServices.ComTypes.IDLFLAG instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [Serializable] [Flags()] public enum IDLFLAG : short { IDLFLAG_NONE = PARAMFLAG.PARAMFLAG_NONE, IDLFLAG_FIN = PARAMFLAG.PARAMFLAG_FIN, IDLFLAG_FOUT = PARAMFLAG.PARAMFLAG_FOUT, IDLFLAG_FLCID = PARAMFLAG.PARAMFLAG_FLCID, IDLFLAG_FRETVAL = PARAMFLAG.PARAMFLAG_FRETVAL } [Obsolete("Use System.Runtime.InteropServices.ComTypes.IDLDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct IDLDESC { public int dwReserved; public IDLFLAG wIDLFlags; } [Obsolete("Use System.Runtime.InteropServices.ComTypes.PARAMFLAG instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [Serializable] [Flags()] public enum PARAMFLAG :short { PARAMFLAG_NONE = 0, PARAMFLAG_FIN = 0x1, PARAMFLAG_FOUT = 0x2, PARAMFLAG_FLCID = 0x4, PARAMFLAG_FRETVAL = 0x8, PARAMFLAG_FOPT = 0x10, PARAMFLAG_FHASDEFAULT = 0x20, PARAMFLAG_FHASCUSTDATA = 0x40 } [Obsolete("Use System.Runtime.InteropServices.ComTypes.PARAMDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct PARAMDESC { public IntPtr lpVarValue; public PARAMFLAG wParamFlags; } [Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct TYPEDESC { public IntPtr lpValue; public Int16 vt; } [Obsolete("Use System.Runtime.InteropServices.ComTypes.ELEMDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct ELEMDESC { public TYPEDESC tdesc; [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)] [ComVisible(false)] public struct DESCUNION { [FieldOffset(0)] public IDLDESC idldesc; [FieldOffset(0)] public PARAMDESC paramdesc; }; public DESCUNION desc; } [Obsolete("Use System.Runtime.InteropServices.ComTypes.VARDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct VARDESC { public int memid; public String lpstrSchema; [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)] [ComVisible(false)] public struct DESCUNION { [FieldOffset(0)] public int oInst; [FieldOffset(0)] public IntPtr lpvarValue; }; public ELEMDESC elemdescVar; public short wVarFlags; public VarEnum varkind; } [Obsolete("Use System.Runtime.InteropServices.ComTypes.DISPPARAMS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct DISPPARAMS { public IntPtr rgvarg; public IntPtr rgdispidNamedArgs; public int cArgs; public int cNamedArgs; } [Obsolete("Use System.Runtime.InteropServices.ComTypes.EXCEPINFO instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct EXCEPINFO { public Int16 wCode; public Int16 wReserved; [MarshalAs(UnmanagedType.BStr)] public String bstrSource; [MarshalAs(UnmanagedType.BStr)] public String bstrDescription; [MarshalAs(UnmanagedType.BStr)] public String bstrHelpFile; public int dwHelpContext; public IntPtr pvReserved; public IntPtr pfnDeferredFillIn; } [Obsolete("Use System.Runtime.InteropServices.ComTypes.FUNCKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [Serializable] public enum FUNCKIND : int { FUNC_VIRTUAL = 0, FUNC_PUREVIRTUAL = 1, FUNC_NONVIRTUAL = 2, FUNC_STATIC = 3, FUNC_DISPATCH = 4 } [Obsolete("Use System.Runtime.InteropServices.ComTypes.INVOKEKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [Serializable] public enum INVOKEKIND : int { INVOKE_FUNC = 0x1, INVOKE_PROPERTYGET = 0x2, INVOKE_PROPERTYPUT = 0x4, INVOKE_PROPERTYPUTREF = 0x8 } [Obsolete("Use System.Runtime.InteropServices.ComTypes.CALLCONV instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [Serializable] public enum CALLCONV : int { CC_CDECL =1, CC_MSCPASCAL=2, CC_PASCAL =CC_MSCPASCAL, CC_MACPASCAL=3, CC_STDCALL =4, CC_RESERVED =5, CC_SYSCALL =6, CC_MPWCDECL =7, CC_MPWPASCAL=8, CC_MAX =9 } [Obsolete("Use System.Runtime.InteropServices.ComTypes.FUNCFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [Serializable] [Flags()] public enum FUNCFLAGS : short { FUNCFLAG_FRESTRICTED= 0x1, FUNCFLAG_FSOURCE = 0x2, FUNCFLAG_FBINDABLE = 0x4, FUNCFLAG_FREQUESTEDIT = 0x8, FUNCFLAG_FDISPLAYBIND = 0x10, FUNCFLAG_FDEFAULTBIND = 0x20, FUNCFLAG_FHIDDEN = 0x40, FUNCFLAG_FUSESGETLASTERROR= 0x80, FUNCFLAG_FDEFAULTCOLLELEM= 0x100, FUNCFLAG_FUIDEFAULT = 0x200, FUNCFLAG_FNONBROWSABLE = 0x400, FUNCFLAG_FREPLACEABLE = 0x800, FUNCFLAG_FIMMEDIATEBIND = 0x1000 } [Obsolete("Use System.Runtime.InteropServices.ComTypes.VARFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [Serializable] [Flags()] public enum VARFLAGS : short { VARFLAG_FREADONLY =0x1, VARFLAG_FSOURCE =0x2, VARFLAG_FBINDABLE =0x4, VARFLAG_FREQUESTEDIT =0x8, VARFLAG_FDISPLAYBIND =0x10, VARFLAG_FDEFAULTBIND =0x20, VARFLAG_FHIDDEN =0x40, VARFLAG_FRESTRICTED =0x80, VARFLAG_FDEFAULTCOLLELEM =0x100, VARFLAG_FUIDEFAULT =0x200, VARFLAG_FNONBROWSABLE =0x400, VARFLAG_FREPLACEABLE =0x800, VARFLAG_FIMMEDIATEBIND =0x1000 } [Obsolete("Use System.Runtime.InteropServices.ComTypes.ITypeInfo instead. http://go.microsoft.com/fwlink/?linkid=14202", false)] [Guid("00020401-0000-0000-C000-000000000046")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface UCOMITypeInfo { void GetTypeAttr(out IntPtr ppTypeAttr); void GetTypeComp(out UCOMITypeComp ppTComp); void GetFuncDesc(int index, out IntPtr ppFuncDesc); void GetVarDesc(int index, out IntPtr ppVarDesc); void GetNames(int memid, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2), Out] String[] rgBstrNames, int cMaxNames, out int pcNames); void GetRefTypeOfImplType(int index, out int href); void GetImplTypeFlags(int index, out int pImplTypeFlags); void GetIDsOfNames([MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1), In] String[] rgszNames, int cNames, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] int[] pMemId); void Invoke([MarshalAs(UnmanagedType.IUnknown)] Object pvInstance, int memid, Int16 wFlags, ref DISPPARAMS pDispParams, out Object pVarResult, out EXCEPINFO pExcepInfo, out int puArgErr); void GetDocumentation(int index, out String strName, out String strDocString, out int dwHelpContext, out String strHelpFile); void GetDllEntry(int memid, INVOKEKIND invKind, out String pBstrDllName, out String pBstrName, out Int16 pwOrdinal); void GetRefTypeInfo(int hRef, out UCOMITypeInfo ppTI); void AddressOfMember(int memid, INVOKEKIND invKind, out IntPtr ppv); void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] Object pUnkOuter, ref Guid riid, [MarshalAs(UnmanagedType.IUnknown), Out] out Object ppvObj); void GetMops(int memid, out String pBstrMops); void GetContainingTypeLib(out UCOMITypeLib ppTLB, out int pIndex); void ReleaseTypeAttr(IntPtr pTypeAttr); void ReleaseFuncDesc(IntPtr pFuncDesc); void ReleaseVarDesc(IntPtr pVarDesc); } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace Microsoft.Win32.SafeHandles { /// <summary> /// SafeHandle for buffers returned by the Axl APIs /// </summary> #pragma warning disable 618 // Have not migrated to v4 transparency yet [System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)] #pragma warning restore 618 internal sealed class SafeAxlBufferHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeAxlBufferHandle() : base(true) { return; } [DllImport("kernel32")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr GetProcessHeap(); [DllImport("kernel32")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool HeapFree(IntPtr hHeap, int dwFlags, IntPtr lpMem); protected override bool ReleaseHandle() { // _AxlFree is a wrapper around HeapFree on the process heap. Since it is not exported from mscorwks // we just call HeapFree directly. This needs to be updated if _AxlFree is ever changed. HeapFree(GetProcessHeap(), 0, handle); return true; } } /// <summary> /// SafeHandle base class for CAPI handles (such as HCRYPTKEY and HCRYPTHASH) which must keep their /// CSP alive as long as they stay alive as well. CAPI requires that all child handles belonging to a /// HCRYPTPROV must be destroyed up before the reference count to the HCRYPTPROV drops to zero. /// Since we cannot control the order of finalization between the two safe handles, SafeCapiHandleBase /// maintains a native refcount on its parent HCRYPTPROV to ensure that if the corresponding /// SafeCspKeyHandle is finalized first CAPI still keeps the provider alive. /// </summary> #pragma warning disable 618 // Have not migrated to v4 transparency yet [SecurityCritical(SecurityCriticalScope.Everything)] #pragma warning restore 618 internal abstract class SafeCapiHandleBase : SafeHandleZeroOrMinusOneIsInvalid { private IntPtr m_csp; [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] internal SafeCapiHandleBase() : base(true) { } [DllImport("advapi32", SetLastError = true)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CryptContextAddRef(IntPtr hProv, IntPtr pdwReserved, int dwFlags); [DllImport("advapi32")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CryptReleaseContext(IntPtr hProv, int dwFlags); protected IntPtr ParentCsp { get { return m_csp; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] set { // We should not be resetting the parent CSP if it's already been set once - that will // lead to leaking the original handle. Debug.Assert(m_csp == IntPtr.Zero); int error = (int)CapiNative.ErrorCode.Success; // A successful call to CryptContextAddRef and an assignment of the handle value to our field // SafeHandle need to happen atomically, so we contain them within a CER. RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (CryptContextAddRef(value, IntPtr.Zero, 0)) { m_csp = value; } else { error = Marshal.GetLastWin32Error(); } } if (error != (int)CapiNative.ErrorCode.Success) { throw new CryptographicException(error); } } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] internal void SetParentCsp(SafeCspHandle parentCsp) { bool addedRef = false; RuntimeHelpers.PrepareConstrainedRegions(); try { parentCsp.DangerousAddRef(ref addedRef); IntPtr rawParentHandle = parentCsp.DangerousGetHandle(); ParentCsp = rawParentHandle; } finally { if (addedRef) { parentCsp.DangerousRelease(); } } } protected abstract bool ReleaseCapiChildHandle(); protected override sealed bool ReleaseHandle() { // Order is important here - we must destroy the child handle before the parent CSP bool destroyedChild = ReleaseCapiChildHandle(); bool releasedCsp = true; if (m_csp != IntPtr.Zero) { releasedCsp = CryptReleaseContext(m_csp, 0); } return destroyedChild && releasedCsp; } } /// <summary> /// SafeHandle for CAPI hash algorithms (HCRYPTHASH) /// </summary> #pragma warning disable 618 // Have not migrated to v4 transparency yet [System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)] #pragma warning restore 618 internal sealed class SafeCapiHashHandle : SafeCapiHandleBase { private SafeCapiHashHandle() { } /// <summary> /// NULL hash handle /// </summary> public static SafeCapiHashHandle InvalidHandle { get { SafeCapiHashHandle handle = new SafeCapiHashHandle(); handle.SetHandle(IntPtr.Zero); return handle; } } [DllImport("advapi32")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CryptDestroyHash(IntPtr hHash); protected override bool ReleaseCapiChildHandle() { return CryptDestroyHash(handle); } } /// <summary> /// SafeHandle for CAPI keys (HCRYPTKEY) /// </summary> #pragma warning disable 618 // Have not migrated to v4 transparency yet [System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)] #pragma warning restore 618 internal sealed class SafeCapiKeyHandle : SafeCapiHandleBase { private SafeCapiKeyHandle() { } /// <summary> /// NULL key handle /// </summary> internal static SafeCapiKeyHandle InvalidHandle { [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] get { SafeCapiKeyHandle handle = new SafeCapiKeyHandle(); handle.SetHandle(IntPtr.Zero); return handle; } } [DllImport("advapi32")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CryptDestroyKey(IntPtr hKey); /// <summary> /// Make a copy of this key handle /// </summary> [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] internal SafeCapiKeyHandle Duplicate() { Contract.Requires(!IsInvalid && !IsClosed); Contract.Ensures(Contract.Result<SafeCapiKeyHandle>() != null && !Contract.Result<SafeCapiKeyHandle>().IsInvalid && !Contract.Result<SafeCapiKeyHandle>().IsClosed); SafeCapiKeyHandle duplicate = null; RuntimeHelpers.PrepareConstrainedRegions(); try { if (!CapiNative.UnsafeNativeMethods.CryptDuplicateKey(this, IntPtr.Zero, 0, out duplicate)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } } finally { if (duplicate != null && !duplicate.IsInvalid && ParentCsp != IntPtr.Zero) { duplicate.ParentCsp = ParentCsp; } } return duplicate; } protected override bool ReleaseCapiChildHandle() { return CryptDestroyKey(handle); } } /// <summary> /// SafeHandle for crypto service providers (HCRYPTPROV) /// </summary> #pragma warning disable 618 // Have not migrated to v4 transparency yet [System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)] #pragma warning restore 618 internal sealed class SafeCspHandle : SafeHandleZeroOrMinusOneIsInvalid { [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] private SafeCspHandle() : base(true) { return; } [DllImport("advapi32", SetLastError = true)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CryptContextAddRef(SafeCspHandle hProv, IntPtr pdwReserved, int dwFlags); [DllImport("advapi32")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CryptReleaseContext(IntPtr hProv, int dwFlags); /// <summary> /// Create a second SafeCspHandle which refers to the same HCRYPTPROV /// </summary> [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] public SafeCspHandle Duplicate() { Contract.Requires(!IsInvalid && !IsClosed); // In the window between the call to CryptContextAddRef and when the raw handle value is assigned // into this safe handle, there's a second reference to the original safe handle that the CLR does // not know about, so we need to bump the reference count around this entire operation to ensure // that we don't have the original handle closed underneath us. bool acquired = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref acquired); IntPtr originalHandle = DangerousGetHandle(); int error = (int)CapiNative.ErrorCode.Success; SafeCspHandle duplicate = new SafeCspHandle(); // A successful call to CryptContextAddRef and an assignment of the handle value to the duplicate // SafeHandle need to happen atomically, so we contain them within a CER. RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (!CryptContextAddRef(this, IntPtr.Zero, 0)) { error = Marshal.GetLastWin32Error(); } else { duplicate.SetHandle(originalHandle); } } // If we could not call CryptContextAddRef succesfully, then throw the error here otherwise // we should be in a valid state at this point. if (error != (int)CapiNative.ErrorCode.Success) { duplicate.Dispose(); throw new CryptographicException(error); } else { Debug.Assert(!duplicate.IsInvalid, "Failed to duplicate handle successfully"); } return duplicate; } finally { if (acquired) { DangerousRelease(); } } } protected override bool ReleaseHandle() { return CryptReleaseContext(handle, 0); } } }
// 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 Test.Utilities; using Xunit; namespace Microsoft.NetFramework.Analyzers.UnitTests { public partial class DoNotUseInsecureDtdProcessingAnalyzerTests : DiagnosticAnalyzerTestBase { private static readonly string s_CA3075XmlDocumentWithNoSecureResolverMessage = MicrosoftNetFrameworkAnalyzersResources.XmlDocumentWithNoSecureResolverMessage; private DiagnosticResult GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(int line, int column) { return GetCSharpResultAt(line, column, CA3075RuleId, s_CA3075XmlDocumentWithNoSecureResolverMessage); } private DiagnosticResult GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(int line, int column) { return GetBasicResultAt(line, column, CA3075RuleId, s_CA3075XmlDocumentWithNoSecureResolverMessage); } [Fact] public void XmlDocumentSetResolverToNullShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument(); doc.XmlResolver = null; } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() doc.XmlResolver = Nothing End Sub End Class End Namespace " ); } [Fact] public void XmlDocumentSetResolverToNullInInitializerShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument() { XmlResolver = null }; } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() With { _ .XmlResolver = Nothing _ } End Sub End Class End Namespace" ); } [Fact] public void XmlDocumentAsFieldSetResolverToNullInInitializerShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument() { XmlResolver = null }; } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() With { _ .XmlResolver = Nothing _ } End Class End Namespace" ); } [Fact] public void XmlDocumentAsFieldSetInsecureResolverInInitializerShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument() { XmlResolver = new XmlUrlResolver() }; } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 54) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() With { _ .XmlResolver = New XmlUrlResolver() _ } End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(7, 13) ); } [Fact] public void XmlDocumentAsFieldNoResolverShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument(); } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 34) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(6, 37) ); } [Fact] public void XmlDocumentUseSecureResolverShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlSecureResolver resolver) { XmlDocument doc = new XmlDocument(); doc.XmlResolver = resolver; } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(resolver As XmlSecureResolver) Dim doc As New XmlDocument() doc.XmlResolver = resolver End Sub End Class End Namespace" ); } [Fact] public void XmlDocumentSetSecureResolverInInitializerShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlSecureResolver resolver) { XmlDocument doc = new XmlDocument() { XmlResolver = resolver }; } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(resolver As XmlSecureResolver) Dim doc As New XmlDocument() With { _ .XmlResolver = resolver _ } End Sub End Class End Namespace" ); } [Fact] public void XmlDocumentUseSecureResolverWithPermissionsShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Net; using System.Security; using System.Security.Permissions; using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { PermissionSet myPermissions = new PermissionSet(PermissionState.None); WebPermission permission = new WebPermission(PermissionState.None); permission.AddPermission(NetworkAccess.Connect, ""http://www.contoso.com/""); permission.AddPermission(NetworkAccess.Connect, ""http://litwareinc.com/data/""); myPermissions.SetPermission(permission); XmlSecureResolver resolver = new XmlSecureResolver(new XmlUrlResolver(), myPermissions); XmlDocument doc = new XmlDocument(); doc.XmlResolver = resolver; } } }" ); VerifyBasic(@" Imports System.Net Imports System.Security Imports System.Security.Permissions Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim myPermissions As New PermissionSet(PermissionState.None) Dim permission As New WebPermission(PermissionState.None) permission.AddPermission(NetworkAccess.Connect, ""http://www.contoso.com/"") permission.AddPermission(NetworkAccess.Connect, ""http://litwareinc.com/data/"") myPermissions.SetPermission(permission) Dim resolver As New XmlSecureResolver(New XmlUrlResolver(), myPermissions) Dim doc As New XmlDocument() doc.XmlResolver = resolver End Sub End Class End Namespace" ); } [Fact] public void XmlDocumentSetResolverToNullInTryClauseShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument(); try { doc.XmlResolver = null; } catch { throw; } } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() Try doc.XmlResolver = Nothing Catch Throw End Try End Sub End Class End Namespace" ); } [Fact] public void XmlDocumentNoResolverShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument(); } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(10, 31) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(7, 24) ); } [Fact] public void XmlDocumentUseNonSecureResolverShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument(); doc.XmlResolver = new XmlUrlResolver(); // warn } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(11, 13) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() doc.XmlResolver = New XmlUrlResolver() ' warn End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(8, 13) ); } [Fact] public void XmlDocumentUseNonSecureResolverInTryClauseShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument(); try { doc.XmlResolver = new XmlUrlResolver(); // warn } catch { throw; } } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(13, 17) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() Try ' warn doc.XmlResolver = New XmlUrlResolver() Catch Throw End Try End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(10, 17) ); } [Fact] public void XmlDocumentReassignmentSetResolverToNullInInitializerShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument(); doc = new XmlDocument() { XmlResolver = null }; } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() doc = New XmlDocument() With { _ .XmlResolver = Nothing _ } End Sub End Class End Namespace" ); } [Fact] public void XmlDocumentReassignmentDefaultShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { XmlDocument doc = new XmlDocument() { XmlResolver = null }; doc = new XmlDocument(); // warn } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(14, 19) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() Dim doc As New XmlDocument() With { _ .XmlResolver = Nothing _ } doc = New XmlDocument() ' warn End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(10, 19) ); } [Fact] public void XmlDocumentSetResolversInDifferentBlock() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod() { { XmlDocument doc = new XmlDocument(); } { XmlDocument doc = new XmlDocument(); doc.XmlResolver = null; } } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(11, 35) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod() If True Then Dim doc As New XmlDocument() End If If True Then Dim doc As New XmlDocument() doc.XmlResolver = Nothing End If End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(8, 28) ); } [Fact] public void XmlDocumentAsFieldSetResolverToInsecureResolverInOnlyMethodShouldGenerateDiagnostics() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument(); public void Method1() { this.doc.XmlResolver = new XmlUrlResolver(); } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 34), GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(12, 13) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() ' warn Public Sub Method1() Me.doc.XmlResolver = New XmlUrlResolver() End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(6, 37), GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(9, 13) ); } [Fact] public void XmlDocumentAsFieldSetResolverToInsecureResolverInSomeMethodShouldGenerateDiagnostics() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument(); // warn public void Method1() { this.doc.XmlResolver = null; } public void Method2() { this.doc.XmlResolver = new XmlUrlResolver(); // warn } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 34), GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(17, 13) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() ' warn Public Sub Method1() Me.doc.XmlResolver = Nothing End Sub Public Sub Method2() Me.doc.XmlResolver = New XmlUrlResolver() ' warn End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(6, 37), GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(13, 13) ); } [Fact] public void XmlDocumentAsFieldSetResolverToNullInSomeMethodShouldGenerateDiagnostics() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlDocument doc = new XmlDocument(); public void Method1() { this.doc.XmlResolver = null; } public void Method2(XmlReader reader) { this.doc.Load(reader); } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 34) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public doc As XmlDocument = New XmlDocument() Public Sub Method1() Me.doc.XmlResolver = Nothing End Sub Public Sub Method2(reader As XmlReader) Me.doc.Load(reader) End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(6, 37) ); } [Fact] public void XmlDocumentCreatedAsTempNotSetResolverShouldGenerateDiagnostics() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public void Method1() { Method2(new XmlDocument()); } public void Method2(XmlDocument doc){} } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(11, 21) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public Sub Method1() Method2(New XmlDocument()) End Sub Public Sub Method2(doc As XmlDocument) End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(8, 21) ); } [Fact] public void XmlDocumentDerivedTypeNotSetResolverShouldNotGenerateDiagnostics() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass1 : XmlDocument { public TestClass1() { XmlResolver = null; } } class TestClass2 { void TestMethod() { var c = new TestClass1(); } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass1 Inherits XmlDocument Public Sub New() XmlResolver = Nothing End Sub End Class Class TestClass2 Private Sub TestMethod() Dim c = New TestClass1() End Sub End Class End Namespace " ); } [Fact] public void XmlDocumentDerivedTypeWithNoSecureResolverShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class DerivedType : XmlDocument {} class TestClass { void TestMethod() { var c = new DerivedType(); } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class DerivedType Inherits XmlDocument End Class Class TestClass Private Sub TestMethod() Dim c = New DerivedType() End Sub End Class End Namespace" ); } } }
/* Copyright (c) Citrix Systems 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: * * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using XenAdmin.Network; using XenAPI; using XenAdmin.Core; using System.Collections; namespace XenAdmin.Dialogs { public partial class VIFDialog : XenDialogBase { private VIF ExistingVif; private int Device; private readonly bool vSwitchController; public VIFDialog(IXenConnection Connection, VIF ExistingVif, int Device) : base(Connection) { InitializeComponent(); CueBannersManager.SetWatermark(promptTextBoxMac, "aa:bb:cc:dd:ee:ff"); this.ExistingVif = ExistingVif; this.Device = Device; if (ExistingVif != null) changeToPropertiesTitle(); // Check if vSwitch Controller is configured for the pool (CA-46299) Pool pool = Helpers.GetPoolOfOne(connection); vSwitchController = pool != null && pool.vSwitchController; label1.Text = vSwitchController ? Messages.VIF_VSWITCH_CONTROLLER : Messages.VIF_LICENSE_RESTRICTION; LoadNetworks(); LoadDetails(); updateEnablement(); SetupEventHandlers(); } private void SetupEventHandlers() { promptTextBoxMac.GotFocus += new EventHandler(promptTextBoxMac_ReceivedFocus); promptTextBoxQoS.GotFocus += new EventHandler(promptTextBoxQoS_ReceivedFocus); promptTextBoxQoS.TextChanged += new EventHandler(promptTextBoxQoS_TextChanged); comboBoxNetwork.SelectedIndexChanged += new EventHandler(NetworkComboBox_SelectedIndexChanged); promptTextBoxMac.TextChanged += new EventHandler(promptTextBoxMac_TextChanged); } void promptTextBoxQoS_TextChanged(object sender, EventArgs e) { updateEnablement(); } void promptTextBoxQoS_ReceivedFocus(object sender, EventArgs e) { checkboxQoS.Checked = true; updateEnablement(); } void promptTextBoxMac_ReceivedFocus(object sender, EventArgs e) { radioButtonMac.Checked = true; updateEnablement(); } private void changeToPropertiesTitle() { this.Text = Messages.VIRTUAL_INTERFACE_PROPERTIES; this.buttonOk.Text = Messages.OK; } private void LoadDetails() { if (vSwitchController) { flowLayoutPanelQoS.Enabled = checkboxQoS.Enabled = checkboxQoS.Checked = false; panelLicenseRestriction.Visible = true; } else { if (ExistingVif == null) { promptTextBoxQoS.Text = ""; checkboxQoS.Checked = false; } else { promptTextBoxQoS.Text = ExistingVif.LimitString; checkboxQoS.Checked = ExistingVif.RateLimited; } flowLayoutPanelQoS.Enabled = checkboxQoS.Enabled = true; panelLicenseRestriction.Visible = false; } if (ExistingVif == null) { radioButtonAutogenerate.Checked = true; return; } foreach (NetworkComboBoxItem item in comboBoxNetwork.Items) { if (item.Network != null && item.Network.opaque_ref == ExistingVif.network.opaque_ref) comboBoxNetwork.SelectedItem = item; } promptTextBoxMac.Text = ExistingVif.MAC; if (!string.IsNullOrEmpty(ExistingVif.MAC)) radioButtonMac.Checked = true; else radioButtonAutogenerate.Checked = true; } void promptTextBoxMac_TextChanged(object sender, EventArgs e) { ValidateMACAddress(); } private void ValidateMACAddress() { if (MACAddressHasChanged() && !MACAddressIsAcceptable()) { MarkMACAsInvalid(); if (ExistingVif != null) promptTextBoxMac.Text = ExistingVif.MAC; return; } updateEnablement(); } private bool MACAddressHasChanged() { if (ExistingVif == null) return true; return promptTextBoxMac.Text != ExistingVif.MAC; } private void MarkMACAsInvalid() { buttonOk.Enabled = false; toolTipContainerOkButton.SetToolTip(Messages.MAC_INVALID); } private void updateEnablement() { if (!Helpers.IsValidMAC(promptTextBoxMac.Text) && !AutogenerateMac) { MarkMACAsInvalid(); } else if (comboBoxNetwork.SelectedItem == null || ((NetworkComboBoxItem)comboBoxNetwork.SelectedItem).Network == null) { buttonOk.Enabled = false; toolTipContainerOkButton.SetToolTip(Messages.SELECT_NETWORK_TOOLTIP); } else if (checkboxQoS.Checked && !isValidQoSLimit()) { buttonOk.Enabled = false; toolTipContainerOkButton.SetToolTip(Messages.ENTER_VALID_QOS); } else { buttonOk.Enabled = true; toolTipContainerOkButton.RemoveAll(); } } private void LoadNetworks() { List<XenAPI.Network> networks = new List<XenAPI.Network>(connection.Cache.Networks); networks.Sort(); foreach (XenAPI.Network network in networks) { if (!network.Show(Properties.Settings.Default.ShowHiddenVMs) || network.IsSlave) continue; comboBoxNetwork.Items.Add(new NetworkComboBoxItem(network)); } if (comboBoxNetwork.Items.Count == 0) { comboBoxNetwork.Items.Add(new NetworkComboBoxItem(null)); } comboBoxNetwork.SelectedIndex = 0; } private void NetworkComboBox_SelectedIndexChanged(object sender, EventArgs e) { ValidateMACAddress(); updateEnablement(); } private XenAPI.Network SelectedNetwork { get { return ((NetworkComboBoxItem)comboBoxNetwork.SelectedItem).Network; } } private string SelectedMac { get { return AutogenerateMac ? "" : promptTextBoxMac.Text; } } private bool AutogenerateMac { get { return radioButtonAutogenerate.Checked; } } public VIF NewVif() { VIF vif = new VIF(); vif.Connection = connection; vif.network = new XenRef<XenAPI.Network>(SelectedNetwork.opaque_ref); vif.MAC = SelectedMac; vif.device = Device.ToString(); if (checkboxQoS.Checked) vif.RateLimited = true; // preserve this param even if we have decided not to turn on qos if (!string.IsNullOrEmpty(promptTextBoxQoS.Text)) { Dictionary<String, String> qos_algorithm_params = new Dictionary<String, String>(); qos_algorithm_params.Add(VIF.KBPS_QOS_PARAMS_KEY, promptTextBoxQoS.Text); vif.qos_algorithm_params = qos_algorithm_params; } return vif; } /// <summary> /// Retrieves the new settings as a proxy vif object. You will need to set the VM field to use these settings in a vif action /// </summary> /// <returns></returns> public Proxy_VIF GetNewSettings() { Proxy_VIF proxyVIF = ExistingVif != null ? ExistingVif.ToProxy() : new Proxy_VIF(); proxyVIF.network = new XenRef<XenAPI.Network>(SelectedNetwork.opaque_ref); proxyVIF.MAC = SelectedMac; proxyVIF.device = Device.ToString(); if (checkboxQoS.Checked) { proxyVIF.qos_algorithm_type = VIF.RATE_LIMIT_QOS_VALUE; } else if (ExistingVif != null && ExistingVif.RateLimited) { proxyVIF.qos_algorithm_type = ""; } // else ... we leave it alone. Currently we only deal with "ratelimit" and "", don't overwrite the field if it's something else // preserve this param even if we turn off qos if (!string.IsNullOrEmpty(promptTextBoxQoS.Text)) { Hashtable qos_algorithm_params = new Hashtable(); qos_algorithm_params.Add(VIF.KBPS_QOS_PARAMS_KEY, promptTextBoxQoS.Text); proxyVIF.qos_algorithm_params = qos_algorithm_params; } return proxyVIF; } private bool ChangesHaveBeenMade { get { if (ExistingVif == null) return true; if (ExistingVif.network.opaque_ref != SelectedNetwork.opaque_ref) return true; if (ExistingVif.MAC != SelectedMac) return true; if (ExistingVif.device != Device.ToString()) return true; if (ExistingVif.RateLimited) { if (!checkboxQoS.Checked) return true; if (ExistingVif.qos_algorithm_params[VIF.KBPS_QOS_PARAMS_KEY] != promptTextBoxQoS.Text) return true; } else if (string.IsNullOrEmpty(ExistingVif.qos_algorithm_type)) { if (checkboxQoS.Checked) return true; } return false; } } private void AutogenerateRadioButton_CheckedChanged(object sender, EventArgs e) { updateEnablement(); } private void MacRadioButton_CheckedChanged(object sender, EventArgs e) { updateEnablement(); } private ThreeButtonDialog MacAddressDuplicationWarningDialog(string macAddress, string vmName) { return new ThreeButtonDialog( new ThreeButtonDialog.Details(SystemIcons.Warning, String.Format(Messages.PROBLEM_MAC_ADDRESS_IS_DUPLICATE, macAddress, vmName).Replace("\\n", "\n"), Messages.PROBLEM_MAC_ADDRESS_IS_DUPLICATE_TITLE), new[] { new ThreeButtonDialog.TBDButton( Messages.YES_BUTTON_CAPTION, DialogResult.Yes), new ThreeButtonDialog.TBDButton( Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true) } ); } /// <summary> /// Determine if the MAC is accetable. It may not be if /// other VIFs on the same Network have the same MAC address as entered /// </summary> /// <returns>If the MAC address entered is acceptable</returns> private bool MACAddressIsAcceptable() { foreach (VIF vif in connection.ResolveAll( SelectedNetwork.VIFs ) ) { if ( vif != ExistingVif && vif.MAC == SelectedMac ) { DialogResult result = MacAddressDuplicationWarningDialog( SelectedMac, connection.Resolve(vif.VM).Name ).ShowDialog(Program.MainWindow); return (result == DialogResult.Yes); } } return true; } private void Okbutton_Click(object sender, EventArgs e) { DialogResult = !ChangesHaveBeenMade ? DialogResult.Cancel : DialogResult.OK; Close(); } private void Cancelbutton_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private bool isValidQoSLimit() { if (!checkboxQoS.Checked) { return true; } string value = promptTextBoxQoS.Text; if (value == null || value.Trim().Length == 0) return false; Int32 result; if (Int32.TryParse(value, out result)) { return result > 0; } else { return false; } } private void checkboxQoS_CheckedChanged(object sender, EventArgs e) { updateEnablement(); } internal override string HelpName { get { if (ExistingVif != null) return "EditVmNetworkSettingsDialog"; else return "VIFDialog"; } } } public class NetworkComboBoxItem : IEquatable<NetworkComboBoxItem> { public XenAPI.Network Network; public NetworkComboBoxItem(XenAPI.Network network) { Network = network; } public override string ToString() { return Network == null ? Messages.NONE : Helpers.GetName(Network); } public bool Equals(NetworkComboBoxItem other) { if (Network == null) return other.Network == null; return Network.Equals(other.Network); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using YesSql.Sql.Schema; namespace YesSql.Sql { public abstract class BaseCommandInterpreter : ICommandInterpreter { protected readonly ISqlDialect _dialect; private const char Space = ' '; public BaseCommandInterpreter(ISqlDialect dialect) { _dialect = dialect; } public IEnumerable<string> CreateSql(IEnumerable<ISchemaCommand> commands) { var sqlCommands = new List<string>(); foreach (var command in commands) { var schemaCommand = command as SchemaCommand; if (schemaCommand == null) { continue; } switch (schemaCommand.Type) { case SchemaCommandType.CreateTable: sqlCommands.AddRange(Run((ICreateTableCommand)schemaCommand)); break; case SchemaCommandType.AlterTable: sqlCommands.AddRange(Run((IAlterTableCommand)schemaCommand)); break; case SchemaCommandType.DropTable: sqlCommands.AddRange(Run((IDropTableCommand)schemaCommand)); break; case SchemaCommandType.SqlStatement: sqlCommands.AddRange(Run((ISqlStatementCommand)schemaCommand)); break; case SchemaCommandType.CreateForeignKey: sqlCommands.AddRange(Run((ICreateForeignKeyCommand)schemaCommand)); break; case SchemaCommandType.DropForeignKey: sqlCommands.AddRange(Run((IDropForeignKeyCommand)schemaCommand)); break; } } return sqlCommands; } public virtual IEnumerable<string> Run(ICreateTableCommand command) { // TODO: Support CreateForeignKeyCommand in a CREATE TABLE (in sqlite they can only be created with the table) var builder = new StringBuilder(); builder.Append(_dialect.CreateTableString) .Append(' ') .Append(_dialect.QuoteForTableName(command.Name)) .Append(" ("); var appendComma = false; foreach (var createColumn in command.TableCommands.OfType<CreateColumnCommand>()) { if (appendComma) { builder.Append(", "); } appendComma = true; Run(builder, createColumn); } // We only create PK statements on columns that don't have IsIdentity since IsIdentity statements also contains the notion of primary key. var primaryKeys = command.TableCommands.OfType<CreateColumnCommand>().Where(ccc => ccc.IsPrimaryKey && !ccc.IsIdentity).Select(ccc => _dialect.QuoteForColumnName(ccc.ColumnName)).ToArray(); if (primaryKeys.Any()) { if (appendComma) { builder.Append(", "); } builder.Append(_dialect.PrimaryKeyString) .Append(" ( ") .Append(String.Join(", ", primaryKeys.ToArray())) .Append(" )"); } builder.Append(" )"); yield return builder.ToString(); } public virtual IEnumerable<string> Run(IDropTableCommand command) { var builder = new StringBuilder(); builder.Append(_dialect.GetDropTableString(command.Name)); yield return builder.ToString(); } public virtual IEnumerable<string> Run(IAlterTableCommand command) { if (command.TableCommands.Count == 0) { yield break; } // drop columns foreach (var dropColumn in command.TableCommands.OfType<DropColumnCommand>()) { var builder = new StringBuilder(); Run(builder, dropColumn); yield return builder.ToString(); } // add columns foreach (var addColumn in command.TableCommands.OfType<AddColumnCommand>()) { var builder = new StringBuilder(); Run(builder, addColumn); yield return builder.ToString(); } // alter columns foreach (var alterColumn in command.TableCommands.OfType<AlterColumnCommand>()) { var builder = new StringBuilder(); Run(builder, alterColumn); yield return builder.ToString(); } // rename columns foreach (var renameColumn in command.TableCommands.OfType<RenameColumnCommand>()) { var builder = new StringBuilder(); Run(builder, renameColumn); yield return builder.ToString(); } // add index foreach (var addIndex in command.TableCommands.OfType<AddIndexCommand>()) { var builder = new StringBuilder(); Run(builder, addIndex); yield return builder.ToString(); } // drop index foreach (var dropIndex in command.TableCommands.OfType<DropIndexCommand>()) { var builder = new StringBuilder(); Run(builder, dropIndex); yield return builder.ToString(); } } public virtual void Run(StringBuilder builder, IAddColumnCommand command) { builder.AppendFormat("alter table {0} add ", _dialect.QuoteForTableName(command.Name)); Run(builder, (CreateColumnCommand)command); } public virtual void Run(StringBuilder builder, IDropColumnCommand command) { builder.AppendFormat("alter table {0} drop column {1}", _dialect.QuoteForTableName(command.Name), _dialect.QuoteForColumnName(command.ColumnName)); } public virtual void Run(StringBuilder builder, IAlterColumnCommand command) { builder.AppendFormat("alter table {0} alter column {1} ", _dialect.QuoteForTableName(command.Name), _dialect.QuoteForColumnName(command.ColumnName)); var dbType = _dialect.ToDbType(command.DbType); // type if (dbType != DbType.Object) { builder.Append(_dialect.GetTypeName(dbType, command.Length, command.Precision, command.Scale)); } else { if (command.Length > 0 || command.Precision > 0 || command.Scale > 0) { throw new Exception("Error while executing data migration: you need to specify the field's type in order to change its properties"); } } // [default value] if (command.Default != null) { builder.Append(" set default ").Append(_dialect.GetSqlValue(command.Default)).Append(Space); } } public virtual void Run(StringBuilder builder, IRenameColumnCommand command) { builder.AppendFormat("alter table {0} rename column {1} to {2}", _dialect.QuoteForTableName(command.Name), _dialect.QuoteForColumnName(command.ColumnName), _dialect.QuoteForColumnName(command.NewColumnName) ); } public virtual void Run(StringBuilder builder, IAddIndexCommand command) { builder.AppendFormat("create index {1} on {0} ({2}) ", _dialect.QuoteForTableName(command.Name), _dialect.QuoteForColumnName(command.IndexName), String.Join(", ", command.ColumnNames.Select(x => _dialect.QuoteForColumnName(x)).ToArray())); } public virtual void Run(StringBuilder builder, IDropIndexCommand command) { builder.Append(_dialect.GetDropIndexString(command.IndexName, command.Name)); } public virtual IEnumerable<string> Run(ISqlStatementCommand command) { if (command.Providers.Count != 0) { yield break; } yield return command.Sql; } public virtual IEnumerable<string> Run(ICreateForeignKeyCommand command) { var builder = new StringBuilder(); builder.Append("alter table ") .Append(_dialect.QuoteForTableName(command.SrcTable)); builder.Append(_dialect.GetAddForeignKeyConstraintString(command.Name, command.SrcColumns.Select(x => _dialect.QuoteForColumnName(x)).ToArray(), _dialect.QuoteForTableName(command.DestTable), command.DestColumns.Select(x => _dialect.QuoteForColumnName(x)).ToArray(), false)); yield return builder.ToString(); } public virtual IEnumerable<string> Run(IDropForeignKeyCommand command) { var builder = new StringBuilder(); builder.Append("alter table ") .Append(_dialect.QuoteForTableName(command.SrcTable)) .Append(_dialect.GetDropForeignKeyConstraintString(command.Name)); yield return builder.ToString(); } private void Run(StringBuilder builder, ICreateColumnCommand command) { // name builder.Append(_dialect.QuoteForColumnName(command.ColumnName)).Append(Space); if (!command.IsIdentity || _dialect.HasDataTypeInIdentityColumn) { var dbType = _dialect.ToDbType(command.DbType); builder.Append(_dialect.GetTypeName(dbType, command.Length, command.Precision, command.Scale)); } // append identity if handled if (command.IsIdentity && _dialect.SupportsIdentityColumns) { builder.Append(Space).Append(_dialect.IdentityColumnString); } // [default value] if (command.Default != null) { builder.Append(" default ").Append(_dialect.GetSqlValue(command.Default)).Append(Space); } // nullable builder.Append(command.IsNotNull ? " not null" : !command.IsPrimaryKey && !command.IsUnique ? _dialect.NullColumnString : string.Empty); // append unique if handled, otherwise at the end of the satement if (command.IsUnique && _dialect.SupportsUnique) { builder.Append(" unique"); } } } }
using System; using System.Collections; using System.Collections.Generic; /// <summary> /// System.Array.Sort<T>(T[],System.Int32,System.Int32) /// </summary> public class ArraySort9 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; retVal = NegTest6() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1:Sort a string array using generics "); try { string[] s1 = new string[6]{"Jack", "Mary", "Mike", "Peter", "Tom", "Allin"}; string[] s2 = new string[6]{"Jack", "Mary", "Mike", "Allin", "Peter", "Tom"}; Array.Sort<string>(s1, 3, 3); for (int i = 0; i < 6; i++) { if (s1[i] != s2[i]) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Sort an int32 array using generics"); try { int length = TestLibrary.Generator.GetByte(-55) + 1; int[] i1 = new int[length]; int[] i2 = new int[length]; for (int i = 0; i < length; i++) { int value = TestLibrary.Generator.GetByte(-55); i1[i] = value; i2[i] = value; } int startIdx = GetInt(0, length - 2); int endIdx = GetInt(startIdx, length - 1); int count = endIdx - startIdx + 1; Array.Sort<int>(i1, startIdx, count); for (int i = startIdx; i < endIdx; i++) //manually quich sort { for (int j = i + 1; j <= endIdx; j++) { if (i2[i] > i2[j]) { int temp = i2[i]; i2[i] = i2[j]; i2[j] = temp; } } } for (int i = 0; i < length; i++) { if (i1[i] != i2[i]) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,the start index is:" + startIdx.ToString() + "the end index is:" + endIdx.ToString()); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Sort a char array from the minimal index to the maximal index of the array "); try { char[] c1 = new char[10] { 'j', 'h', 'g', 'i', 'f', 'e', 'c', 'd', 'a', 'b' }; char[] d1 = new char[10] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' }; Array.Sort<char>(c1, 0, c1.Length); for (int i = 0; i < 10; i++) { if (c1[i] != d1[i]) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Sort customized type array using default customized comparer"); try { int length = TestLibrary.Generator.GetByte(-55); C[] c_array = new C[length]; C[] c_result = new C[length]; for (int i = 0; i < length; i++) { int value = TestLibrary.Generator.GetInt32(-55); C c1 = new C(value); c_array.SetValue(c1, i); c_result.SetValue(c1, i); } //sort manually C temp; for (int j = 0; j < length - 1; j++) { for (int i = 0; i < length - 1; i++) { if (c_result[i].value < c_result[i + 1].value) { temp = c_result[i]; c_result[i] = c_result[i + 1]; c_result[i + 1] = temp; } } } Array.Sort<C>(c_array, 0, length); for (int i = 0; i < length; i++) { if (c_result[i].value != c_array[i].value) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The array is null "); try { string[] s1 = null; Array.Sort<string>(s1, 0, 5); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected "); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: The start index is less than the minimal bound of the array"); try { string[] s1 = new string[6]{"Jack", "Mary", "Peter", "Mike", "Tom", "Allin"}; Array.Sort<string>(s1, -1, 4); TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException is not throw as expected "); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: The length is less than zero"); try { string[] s1 = new string[6]{"Jack", "Mary", "Peter", "Mike", "Tom", "Allin"}; Array.Sort<string>(s1, 1, -4); TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException is not throw as expected "); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: The start index is greater than the maximal range of the array"); try { int length = TestLibrary.Generator.GetByte(-55); string[] s1 = new string[length]; for (int i = 0; i < length; i++) { string value = TestLibrary.Generator.GetString(-55, false, 0, 10); s1[i] = value; } int startIdx = GetInt(0, Byte.MaxValue); int increment = length; Array.Sort<string>(s1, startIdx + increment, 3); TestLibrary.TestFramework.LogError("107", "The ArgumentException is not throw as expected "); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest5: Elements in array do not implement the IComparable interface "); try { E[] a1 = new E[4] { new E(), new E(), new E(), new E() }; Array.Sort<E>(a1, 0, 4); TestLibrary.TestFramework.LogError("109", "The InvalidOperationException is not throw as expected "); retVal = false; } catch (InvalidOperationException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest6: The index argument is valid, but the length argument is too large for that index. "); try { int length = TestLibrary.Generator.GetByte(-55); string[] s1 = new string[length]; for (int i = 0; i < length; i++) { string value = TestLibrary.Generator.GetString(-55, false, 0, 10); s1[i] = value; } int startIdx = GetInt(0, length - 1); int count = GetInt(length + 1, TestLibrary.Generator.GetByte(-55)); Array.Sort<string>(s1, startIdx, count); TestLibrary.TestFramework.LogError("11", "The ArgumentException is not throw as expected "); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("112", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ArraySort9 test = new ArraySort9(); TestLibrary.TestFramework.BeginTestCase("ArraySort9"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } class C : IComparable { private int c_value; public C(int a) { this.c_value = a; } public int value { get { return c_value; } } #region IComparable Members public int CompareTo(object obj) { if (this.c_value <= ((C)obj).c_value) { return 1; } else { return -1; } } #endregion } class E { public E() { } } #region Help method for geting test data private Int32 GetInt(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void HorizontalSubtractSingle() { var test = new HorizontalBinaryOpTest__HorizontalSubtractSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class HorizontalBinaryOpTest__HorizontalSubtractSingle { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int Op2ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private HorizontalBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static HorizontalBinaryOpTest__HorizontalSubtractSingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); } public HorizontalBinaryOpTest__HorizontalSubtractSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } _dataTable = new HorizontalBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize); } public bool IsSupported => Sse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse3.HorizontalSubtract( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse3.HorizontalSubtract( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse3.HorizontalSubtract( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalSubtract), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalSubtract), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalSubtract), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse3.HorizontalSubtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse3.HorizontalSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse3.HorizontalSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse3.HorizontalSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new HorizontalBinaryOpTest__HorizontalSubtractSingle(); var result = Sse3.HorizontalSubtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse3.HorizontalSubtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { for (var outer = 0; outer < (VectorSize / 16); outer++) { for (var inner = 0; inner < (8 / sizeof(Single)); inner++) { var i1 = (outer * (16 / sizeof(Single))) + inner; var i2 = i1 + (8 / sizeof(Single)); var i3 = (outer * (16 / sizeof(Single))) + (inner * 2); if (BitConverter.SingleToInt32Bits(result[i1]) != BitConverter.SingleToInt32Bits(left[i3] - left[i3 + 1])) { Succeeded = false; break; } if (BitConverter.SingleToInt32Bits(result[i2]) != BitConverter.SingleToInt32Bits(right[i3] - right[i3 + 1])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse3)}.{nameof(Sse3.HorizontalSubtract)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Runtime.ExceptionServices; namespace System.Linq.Expressions.Interpreter { #if FEATURE_MAKE_RUN_METHODS internal static partial class DelegateHelpers { private const int MaximumArity = 17; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] internal static Type MakeDelegate(Type[] types) { Debug.Assert(types != null && types.Length > 0); // Can only used predefined delegates if we have no byref types and // the arity is small enough to fit in Func<...> or Action<...> if (types.Length > MaximumArity || types.Any(t => t.IsByRef)) { throw ContractUtils.Unreachable; } Type returnType = types[types.Length - 1]; if (returnType == typeof(void)) { Array.Resize(ref types, types.Length - 1); switch (types.Length) { case 0: return typeof(Action); case 1: return typeof(Action<>).MakeGenericType(types); case 2: return typeof(Action<,>).MakeGenericType(types); case 3: return typeof(Action<,,>).MakeGenericType(types); case 4: return typeof(Action<,,,>).MakeGenericType(types); case 5: return typeof(Action<,,,,>).MakeGenericType(types); case 6: return typeof(Action<,,,,,>).MakeGenericType(types); case 7: return typeof(Action<,,,,,,>).MakeGenericType(types); case 8: return typeof(Action<,,,,,,,>).MakeGenericType(types); case 9: return typeof(Action<,,,,,,,,>).MakeGenericType(types); case 10: return typeof(Action<,,,,,,,,,>).MakeGenericType(types); case 11: return typeof(Action<,,,,,,,,,,>).MakeGenericType(types); case 12: return typeof(Action<,,,,,,,,,,,>).MakeGenericType(types); case 13: return typeof(Action<,,,,,,,,,,,,>).MakeGenericType(types); case 14: return typeof(Action<,,,,,,,,,,,,,>).MakeGenericType(types); case 15: return typeof(Action<,,,,,,,,,,,,,,>).MakeGenericType(types); case 16: return typeof(Action<,,,,,,,,,,,,,,,>).MakeGenericType(types); } } else { switch (types.Length) { case 1: return typeof(Func<>).MakeGenericType(types); case 2: return typeof(Func<,>).MakeGenericType(types); case 3: return typeof(Func<,,>).MakeGenericType(types); case 4: return typeof(Func<,,,>).MakeGenericType(types); case 5: return typeof(Func<,,,,>).MakeGenericType(types); case 6: return typeof(Func<,,,,,>).MakeGenericType(types); case 7: return typeof(Func<,,,,,,>).MakeGenericType(types); case 8: return typeof(Func<,,,,,,,>).MakeGenericType(types); case 9: return typeof(Func<,,,,,,,,>).MakeGenericType(types); case 10: return typeof(Func<,,,,,,,,,>).MakeGenericType(types); case 11: return typeof(Func<,,,,,,,,,,>).MakeGenericType(types); case 12: return typeof(Func<,,,,,,,,,,,>).MakeGenericType(types); case 13: return typeof(Func<,,,,,,,,,,,,>).MakeGenericType(types); case 14: return typeof(Func<,,,,,,,,,,,,,>).MakeGenericType(types); case 15: return typeof(Func<,,,,,,,,,,,,,,>).MakeGenericType(types); case 16: return typeof(Func<,,,,,,,,,,,,,,,>).MakeGenericType(types); case 17: return typeof(Func<,,,,,,,,,,,,,,,,>).MakeGenericType(types); } } throw ContractUtils.Unreachable; } } #endif internal static class ScriptingRuntimeHelpers { public static object Int32ToObject(int i) { switch (i) { case -1: return Utils.BoxedIntM1; case 0: return Utils.BoxedInt0; case 1: return Utils.BoxedInt1; case 2: return Utils.BoxedInt2; case 3: return Utils.BoxedInt3; } return i; } internal static object GetPrimitiveDefaultValue(Type type) { object result; switch (type.GetTypeCode()) { case TypeCode.Boolean: result = Utils.BoxedFalse; break; case TypeCode.SByte: result = Utils.BoxedDefaultSByte; break; case TypeCode.Byte: result = Utils.BoxedDefaultByte; break; case TypeCode.Char: result = Utils.BoxedDefaultChar; break; case TypeCode.Int16: result = Utils.BoxedDefaultInt16; break; case TypeCode.Int32: result = Utils.BoxedInt0; break; case TypeCode.Int64: result = Utils.BoxedDefaultInt64; break; case TypeCode.UInt16: result = Utils.BoxedDefaultUInt16; break; case TypeCode.UInt32: result = Utils.BoxedDefaultUInt32; break; case TypeCode.UInt64: result = Utils.BoxedDefaultUInt64; break; case TypeCode.Single: return Utils.BoxedDefaultSingle; case TypeCode.Double: return Utils.BoxedDefaultDouble; case TypeCode.DateTime: return Utils.BoxedDefaultDateTime; case TypeCode.Decimal: return Utils.BoxedDefaultDecimal; default: // Also covers DBNull which is a class. return null; } if (type.IsEnum) { result = Enum.ToObject(type, result); } return result; } } internal static class ExceptionHelpers { /// <summary> /// Updates an exception before it's getting re-thrown so /// we can present a reasonable stack trace to the user. /// </summary> public static void UnwrapAndRethrow(TargetInvocationException exception) { ExceptionDispatchInfo.Throw(exception.InnerException); } } /// <summary> /// A hybrid dictionary which compares based upon object identity. /// </summary> internal class HybridReferenceDictionary<TKey, TValue> where TKey : class { private KeyValuePair<TKey, TValue>[] _keysAndValues; private Dictionary<TKey, TValue> _dict; private const int ArraySize = 10; public bool TryGetValue(TKey key, out TValue value) { Debug.Assert(key != null); if (_dict != null) { return _dict.TryGetValue(key, out value); } else if (_keysAndValues != null) { for (int i = 0; i < _keysAndValues.Length; i++) { if (_keysAndValues[i].Key == key) { value = _keysAndValues[i].Value; return true; } } } value = default(TValue); return false; } public void Remove(TKey key) { Debug.Assert(key != null); if (_dict != null) { _dict.Remove(key); } else if (_keysAndValues != null) { for (int i = 0; i < _keysAndValues.Length; i++) { if (_keysAndValues[i].Key == key) { _keysAndValues[i] = new KeyValuePair<TKey, TValue>(); return; } } } } public bool ContainsKey(TKey key) { Debug.Assert(key != null); if (_dict != null) { return _dict.ContainsKey(key); } KeyValuePair<TKey, TValue>[] keysAndValues = _keysAndValues; if (keysAndValues != null) { for (int i = 0; i < keysAndValues.Length; i++) { if (keysAndValues[i].Key == key) { return true; } } } return false; } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { if (_dict != null) { return _dict.GetEnumerator(); } return GetEnumeratorWorker(); } private IEnumerator<KeyValuePair<TKey, TValue>> GetEnumeratorWorker() { if (_keysAndValues != null) { for (int i = 0; i < _keysAndValues.Length; i++) { if (_keysAndValues[i].Key != null) { yield return _keysAndValues[i]; } } } } public TValue this[TKey key] { get { Debug.Assert(key != null); TValue res; if (TryGetValue(key, out res)) { return res; } throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); } set { Debug.Assert(key != null); if (_dict != null) { _dict[key] = value; } else { int index; if (_keysAndValues != null) { index = -1; for (int i = 0; i < _keysAndValues.Length; i++) { if (_keysAndValues[i].Key == key) { _keysAndValues[i] = new KeyValuePair<TKey, TValue>(key, value); return; } else if (_keysAndValues[i].Key == null) { index = i; } } } else { _keysAndValues = new KeyValuePair<TKey, TValue>[ArraySize]; index = 0; } if (index != -1) { _keysAndValues[index] = new KeyValuePair<TKey, TValue>(key, value); } else { _dict = new Dictionary<TKey, TValue>(); for (int i = 0; i < _keysAndValues.Length; i++) { _dict[_keysAndValues[i].Key] = _keysAndValues[i].Value; } _keysAndValues = null; _dict[key] = value; } } } } } internal static class Assert { [Conditional("DEBUG")] public static void NotNull(object var) { Debug.Assert(var != null); } } }
// 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. // // ResourcesEtwProvider.cs // // // Managed event source for things that can version with MSCORLIB. // using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Text; using System.Runtime.CompilerServices; namespace System.Diagnostics.Tracing { // To use the framework provider // // \\clrmain\tools\Perfmonitor /nokernel /noclr /provider:8E9F5090-2D75-4d03-8A81-E5AFBF85DAF1 start // Run run your app // \\clrmain\tools\Perfmonitor stop // \\clrmain\tools\Perfmonitor print // // This will produce an XML file, where each event is pretty-printed with all its arguments nicely parsed. // [FriendAccessAllowed] [EventSource(Guid = "8E9F5090-2D75-4d03-8A81-E5AFBF85DAF1", Name = "System.Diagnostics.Eventing.FrameworkEventSource")] sealed internal class FrameworkEventSource : EventSource { // Defines the singleton instance for the Resources ETW provider public static readonly FrameworkEventSource Log = new FrameworkEventSource(); // Keyword definitions. These represent logical groups of events that can be turned on and off independently // Often each task has a keyword, but where tasks are determined by subsystem, keywords are determined by // usefulness to end users to filter. Generally users don't mind extra events if they are not high volume // so grouping low volume events together in a single keywords is OK (users can post-filter by task if desired) public static class Keywords { public const EventKeywords Loader = (EventKeywords)0x0001; // This is bit 0 public const EventKeywords ThreadPool = (EventKeywords)0x0002; public const EventKeywords NetClient = (EventKeywords)0x0004; // // This is a private event we do not want to expose to customers. It is to be used for profiling // uses of dynamic type loading by ProjectN applications running on the desktop CLR // public const EventKeywords DynamicTypeUsage = (EventKeywords)0x0008; public const EventKeywords ThreadTransfer = (EventKeywords)0x0010; } /// <summary>ETW tasks that have start/stop events.</summary> [FriendAccessAllowed] public static class Tasks // this name is important for EventSource { /// <summary>Begin / End - GetResponse.</summary> public const EventTask GetResponse = (EventTask)1; /// <summary>Begin / End - GetRequestStream</summary> public const EventTask GetRequestStream = (EventTask)2; /// <summary>Send / Receive - begin transfer/end transfer</summary> public const EventTask ThreadTransfer = (EventTask)3; } [FriendAccessAllowed] public static class Opcodes { public const EventOpcode ReceiveHandled = (EventOpcode)11; } // This predicate is used by consumers of this class to deteremine if the class has actually been initialized, // and therefore if the public statics are available for use. This is typically not a problem... if the static // class constructor fails, then attempts to access the statics (or even this property) will result in a // TypeInitializationException. However, that is not the case while the class loader is actually trying to construct // the TypeInitializationException instance to represent that failure, and some consumers of this class are on // that code path, specifically the resource manager. public static bool IsInitialized { get { return Log != null; } } // The FrameworkEventSource GUID is {8E9F5090-2D75-4d03-8A81-E5AFBF85DAF1} private FrameworkEventSource() : base(new Guid(0x8e9f5090, 0x2d75, 0x4d03, 0x8a, 0x81, 0xe5, 0xaf, 0xbf, 0x85, 0xda, 0xf1), "System.Diagnostics.Eventing.FrameworkEventSource") { } // WriteEvent overloads (to avoid the "params" EventSource.WriteEvent // optimized for common signatures (used by the ThreadTransferSend/Receive events) [NonEvent, System.Security.SecuritySafeCritical] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] private unsafe void WriteEvent(int eventId, long arg1, int arg2, string arg3, bool arg4) { if (IsEnabled()) { if (arg3 == null) arg3 = ""; fixed (char* string3Bytes = arg3) { EventSource.EventData* descrs = stackalloc EventSource.EventData[4]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[2].DataPointer = (IntPtr)string3Bytes; descrs[2].Size = ((arg3.Length + 1) * 2); descrs[3].DataPointer = (IntPtr)(&arg4); descrs[3].Size = 4; WriteEventCore(eventId, 4, descrs); } } } // optimized for common signatures (used by the ThreadTransferSend/Receive events) [NonEvent, System.Security.SecuritySafeCritical] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] private unsafe void WriteEvent(int eventId, long arg1, int arg2, string arg3) { if (IsEnabled()) { if (arg3 == null) arg3 = ""; fixed (char* string3Bytes = arg3) { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[2].DataPointer = (IntPtr)string3Bytes; descrs[2].Size = ((arg3.Length + 1) * 2); WriteEventCore(eventId, 3, descrs); } } } // optimized for common signatures (used by the BeginGetResponse/BeginGetRequestStream events) [NonEvent, System.Security.SecuritySafeCritical] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] private unsafe void WriteEvent(int eventId, long arg1, string arg2, bool arg3, bool arg4) { if (IsEnabled()) { if (arg2 == null) arg2 = ""; fixed (char* string2Bytes = arg2) { EventSource.EventData* descrs = stackalloc EventSource.EventData[4]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[1].DataPointer = (IntPtr)string2Bytes; descrs[1].Size = ((arg2.Length + 1) * 2); descrs[2].DataPointer = (IntPtr)(&arg3); descrs[2].Size = 4; descrs[3].DataPointer = (IntPtr)(&arg4); descrs[3].Size = 4; WriteEventCore(eventId, 4, descrs); } } } // optimized for common signatures (used by the EndGetRequestStream event) [NonEvent, System.Security.SecuritySafeCritical] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] private unsafe void WriteEvent(int eventId, long arg1, bool arg2, bool arg3) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[2].DataPointer = (IntPtr)(&arg3); descrs[2].Size = 4; WriteEventCore(eventId, 3, descrs); } } // optimized for common signatures (used by the EndGetResponse event) [NonEvent, System.Security.SecuritySafeCritical] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] private unsafe void WriteEvent(int eventId, long arg1, bool arg2, bool arg3, int arg4) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[4]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[2].DataPointer = (IntPtr)(&arg3); descrs[2].Size = 4; descrs[3].DataPointer = (IntPtr)(&arg4); descrs[3].Size = 4; WriteEventCore(eventId, 4, descrs); } } // ResourceManager Event Definitions [Event(1, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerLookupStarted(String baseName, String mainAssemblyName, String cultureName) { WriteEvent(1, baseName, mainAssemblyName, cultureName); } [Event(2, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerLookingForResourceSet(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(2, baseName, mainAssemblyName, cultureName); } [Event(3, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerFoundResourceSetInCache(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(3, baseName, mainAssemblyName, cultureName); } // After loading a satellite assembly, we already have the ResourceSet for this culture in // the cache. This can happen if you have an assembly load callback that called into this // instance of the ResourceManager. [Event(4, Level = EventLevel.Warning, Keywords = Keywords.Loader)] public void ResourceManagerFoundResourceSetInCacheUnexpected(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(4, baseName, mainAssemblyName, cultureName); } // manifest resource stream lookup succeeded [Event(5, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerStreamFound(String baseName, String mainAssemblyName, String cultureName, String loadedAssemblyName, String resourceFileName) { if (IsEnabled()) WriteEvent(5, baseName, mainAssemblyName, cultureName, loadedAssemblyName, resourceFileName); } // manifest resource stream lookup failed [Event(6, Level = EventLevel.Warning, Keywords = Keywords.Loader)] public void ResourceManagerStreamNotFound(String baseName, String mainAssemblyName, String cultureName, String loadedAssemblyName, String resourceFileName) { if (IsEnabled()) WriteEvent(6, baseName, mainAssemblyName, cultureName, loadedAssemblyName, resourceFileName); } [Event(7, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerGetSatelliteAssemblySucceeded(String baseName, String mainAssemblyName, String cultureName, String assemblyName) { if (IsEnabled()) WriteEvent(7, baseName, mainAssemblyName, cultureName, assemblyName); } [Event(8, Level = EventLevel.Warning, Keywords = Keywords.Loader)] public void ResourceManagerGetSatelliteAssemblyFailed(String baseName, String mainAssemblyName, String cultureName, String assemblyName) { if (IsEnabled()) WriteEvent(8, baseName, mainAssemblyName, cultureName, assemblyName); } [Event(9, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(String baseName, String mainAssemblyName, String assemblyName, String resourceFileName) { if (IsEnabled()) WriteEvent(9, baseName, mainAssemblyName, assemblyName, resourceFileName); } [Event(10, Level = EventLevel.Warning, Keywords = Keywords.Loader)] public void ResourceManagerCaseInsensitiveResourceStreamLookupFailed(String baseName, String mainAssemblyName, String assemblyName, String resourceFileName) { if (IsEnabled()) WriteEvent(10, baseName, mainAssemblyName, assemblyName, resourceFileName); } // Could not access the manifest resource the assembly [Event(11, Level = EventLevel.Error, Keywords = Keywords.Loader)] public void ResourceManagerManifestResourceAccessDenied(String baseName, String mainAssemblyName, String assemblyName, String canonicalName) { if (IsEnabled()) WriteEvent(11, baseName, mainAssemblyName, assemblyName, canonicalName); } // Neutral resources are sufficient for this culture. Skipping satellites [Event(12, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerNeutralResourcesSufficient(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(12, baseName, mainAssemblyName, cultureName); } [Event(13, Level = EventLevel.Warning, Keywords = Keywords.Loader)] public void ResourceManagerNeutralResourceAttributeMissing(String mainAssemblyName) { if (IsEnabled()) WriteEvent(13, mainAssemblyName); } [Event(14, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerCreatingResourceSet(String baseName, String mainAssemblyName, String cultureName, String fileName) { if (IsEnabled()) WriteEvent(14, baseName, mainAssemblyName, cultureName, fileName); } [Event(15, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerNotCreatingResourceSet(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(15, baseName, mainAssemblyName, cultureName); } [Event(16, Level = EventLevel.Warning, Keywords = Keywords.Loader)] public void ResourceManagerLookupFailed(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(16, baseName, mainAssemblyName, cultureName); } [Event(17, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerReleasingResources(String baseName, String mainAssemblyName) { if (IsEnabled()) WriteEvent(17, baseName, mainAssemblyName); } [Event(18, Level = EventLevel.Warning, Keywords = Keywords.Loader)] public void ResourceManagerNeutralResourcesNotFound(String baseName, String mainAssemblyName, String resName) { if (IsEnabled()) WriteEvent(18, baseName, mainAssemblyName, resName); } [Event(19, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerNeutralResourcesFound(String baseName, String mainAssemblyName, String resName) { if (IsEnabled()) WriteEvent(19, baseName, mainAssemblyName, resName); } [Event(20, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerAddingCultureFromConfigFile(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(20, baseName, mainAssemblyName, cultureName); } [Event(21, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerCultureNotFoundInConfigFile(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(21, baseName, mainAssemblyName, cultureName); } [Event(22, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerCultureFoundInConfigFile(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(22, baseName, mainAssemblyName, cultureName); } // ResourceManager Event Wrappers [NonEvent] public void ResourceManagerLookupStarted(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerLookupStarted(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerLookingForResourceSet(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerLookingForResourceSet(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerFoundResourceSetInCache(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerFoundResourceSetInCache(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerFoundResourceSetInCacheUnexpected(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerFoundResourceSetInCacheUnexpected(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerStreamFound(String baseName, Assembly mainAssembly, String cultureName, Assembly loadedAssembly, String resourceFileName) { if (IsEnabled()) ResourceManagerStreamFound(baseName, GetName(mainAssembly), cultureName, GetName(loadedAssembly), resourceFileName); } [NonEvent] public void ResourceManagerStreamNotFound(String baseName, Assembly mainAssembly, String cultureName, Assembly loadedAssembly, String resourceFileName) { if (IsEnabled()) ResourceManagerStreamNotFound(baseName, GetName(mainAssembly), cultureName, GetName(loadedAssembly), resourceFileName); } [NonEvent] public void ResourceManagerGetSatelliteAssemblySucceeded(String baseName, Assembly mainAssembly, String cultureName, String assemblyName) { if (IsEnabled()) ResourceManagerGetSatelliteAssemblySucceeded(baseName, GetName(mainAssembly), cultureName, assemblyName); } [NonEvent] public void ResourceManagerGetSatelliteAssemblyFailed(String baseName, Assembly mainAssembly, String cultureName, String assemblyName) { if (IsEnabled()) ResourceManagerGetSatelliteAssemblyFailed(baseName, GetName(mainAssembly), cultureName, assemblyName); } [NonEvent] public void ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(String baseName, Assembly mainAssembly, String assemblyName, String resourceFileName) { if (IsEnabled()) ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(baseName, GetName(mainAssembly), assemblyName, resourceFileName); } [NonEvent] public void ResourceManagerCaseInsensitiveResourceStreamLookupFailed(String baseName, Assembly mainAssembly, String assemblyName, String resourceFileName) { if (IsEnabled()) ResourceManagerCaseInsensitiveResourceStreamLookupFailed(baseName, GetName(mainAssembly), assemblyName, resourceFileName); } [NonEvent] public void ResourceManagerManifestResourceAccessDenied(String baseName, Assembly mainAssembly, String assemblyName, String canonicalName) { if (IsEnabled()) ResourceManagerManifestResourceAccessDenied(baseName, GetName(mainAssembly), assemblyName, canonicalName); } [NonEvent] public void ResourceManagerNeutralResourcesSufficient(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerNeutralResourcesSufficient(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerNeutralResourceAttributeMissing(Assembly mainAssembly) { if (IsEnabled()) ResourceManagerNeutralResourceAttributeMissing(GetName(mainAssembly)); } [NonEvent] public void ResourceManagerCreatingResourceSet(String baseName, Assembly mainAssembly, String cultureName, String fileName) { if (IsEnabled()) ResourceManagerCreatingResourceSet(baseName, GetName(mainAssembly), cultureName, fileName); } [NonEvent] public void ResourceManagerNotCreatingResourceSet(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerNotCreatingResourceSet(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerLookupFailed(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerLookupFailed(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerReleasingResources(String baseName, Assembly mainAssembly) { if (IsEnabled()) ResourceManagerReleasingResources(baseName, GetName(mainAssembly)); } [NonEvent] public void ResourceManagerNeutralResourcesNotFound(String baseName, Assembly mainAssembly, String resName) { if (IsEnabled()) ResourceManagerNeutralResourcesNotFound(baseName, GetName(mainAssembly), resName); } [NonEvent] public void ResourceManagerNeutralResourcesFound(String baseName, Assembly mainAssembly, String resName) { if (IsEnabled()) ResourceManagerNeutralResourcesFound(baseName, GetName(mainAssembly), resName); } [NonEvent] public void ResourceManagerAddingCultureFromConfigFile(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerAddingCultureFromConfigFile(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerCultureNotFoundInConfigFile(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerCultureNotFoundInConfigFile(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerCultureFoundInConfigFile(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerCultureFoundInConfigFile(baseName, GetName(mainAssembly), cultureName); } private static string GetName(Assembly assembly) { if (assembly == null) return "<<NULL>>"; else return assembly.FullName; } [Event(30, Level = EventLevel.Verbose, Keywords = Keywords.ThreadPool|Keywords.ThreadTransfer)] public void ThreadPoolEnqueueWork(long workID) { WriteEvent(30, workID); } [NonEvent, System.Security.SecuritySafeCritical] public unsafe void ThreadPoolEnqueueWorkObject(object workID) { // convert the Object Id to a long ThreadPoolEnqueueWork((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref workID))); } [Event(31, Level = EventLevel.Verbose, Keywords = Keywords.ThreadPool|Keywords.ThreadTransfer)] public void ThreadPoolDequeueWork(long workID) { WriteEvent(31, workID); } [NonEvent, System.Security.SecuritySafeCritical] public unsafe void ThreadPoolDequeueWorkObject(object workID) { // convert the Object Id to a long ThreadPoolDequeueWork((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref workID))); } // In the desktop runtime they don't use Tasks for the point at which the response happens, which means that the // Activity ID created by start using implicit activity IDs does not match. Thus disable implicit activities (until we fix that) [Event(140, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions=EventActivityOptions.Disable, Task = Tasks.GetResponse, Opcode = EventOpcode.Start, Version = 1)] private void GetResponseStart(long id, string uri, bool success, bool synchronous) { WriteEvent(140, id, uri, success, synchronous); } [Event(141, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions=EventActivityOptions.Disable, Task = Tasks.GetResponse, Opcode = EventOpcode.Stop, Version = 1)] private void GetResponseStop(long id, bool success, bool synchronous, int statusCode) { WriteEvent(141, id, success, synchronous, statusCode); } // In the desktop runtime they don't use Tasks for the point at which the response happens, which means that the // Activity ID created by start using implicit activity IDs does not match. Thus disable implicit activities (until we fix that) [Event(142, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions=EventActivityOptions.Disable, Task = Tasks.GetRequestStream, Opcode = EventOpcode.Start, Version = 1)] private void GetRequestStreamStart(long id, string uri, bool success, bool synchronous) { WriteEvent(142, id, uri, success, synchronous); } [Event(143, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions=EventActivityOptions.Disable, Task = Tasks.GetRequestStream, Opcode = EventOpcode.Stop, Version = 1)] private void GetRequestStreamStop(long id, bool success, bool synchronous) { WriteEvent(143, id, success, synchronous); } [NonEvent, System.Security.SecuritySafeCritical] public unsafe void BeginGetResponse(object id, string uri, bool success, bool synchronous) { if (IsEnabled()) GetResponseStart(IdForObject(id), uri, success, synchronous); } [NonEvent, System.Security.SecuritySafeCritical] public unsafe void EndGetResponse(object id, bool success, bool synchronous, int statusCode) { if (IsEnabled()) GetResponseStop(IdForObject(id), success, synchronous, statusCode); } [NonEvent, System.Security.SecuritySafeCritical] public unsafe void BeginGetRequestStream(object id, string uri, bool success, bool synchronous) { if (IsEnabled()) GetRequestStreamStart(IdForObject(id), uri, success, synchronous); } [NonEvent, System.Security.SecuritySafeCritical] public unsafe void EndGetRequestStream(object id, bool success, bool synchronous) { if (IsEnabled()) GetRequestStreamStop(IdForObject(id), success, synchronous); } // id - represents a correlation ID that allows correlation of two activities, one stamped by // ThreadTransferSend, the other by ThreadTransferReceive // kind - identifies the transfer: values below 64 are reserved for the runtime. Currently used values: // 1 - managed Timers ("roaming" ID) // 2 - managed async IO operations (FileStream, PipeStream, a.o.) // 3 - WinRT dispatch operations // info - any additional information user code might consider interesting [Event(150, Level = EventLevel.Informational, Keywords = Keywords.ThreadTransfer, Task = Tasks.ThreadTransfer, Opcode = EventOpcode.Send)] public void ThreadTransferSend(long id, int kind, string info, bool multiDequeues) { if (IsEnabled()) WriteEvent(150, id, kind, info, multiDequeues); } // id - is a managed object. it gets translated to the object's address. ETW listeners must // keep track of GC movements in order to correlate the value passed to XyzSend with the // (possibly changed) value passed to XyzReceive [NonEvent, System.Security.SecuritySafeCritical] public unsafe void ThreadTransferSendObj(object id, int kind, string info, bool multiDequeues) { ThreadTransferSend((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info, multiDequeues); } // id - represents a correlation ID that allows correlation of two activities, one stamped by // ThreadTransferSend, the other by ThreadTransferReceive // kind - identifies the transfer: values below 64 are reserved for the runtime. Currently used values: // 1 - managed Timers ("roaming" ID) // 2 - managed async IO operations (FileStream, PipeStream, a.o.) // 3 - WinRT dispatch operations // info - any additional information user code might consider interesting [Event(151, Level = EventLevel.Informational, Keywords = Keywords.ThreadTransfer, Task = Tasks.ThreadTransfer, Opcode = EventOpcode.Receive)] public void ThreadTransferReceive(long id, int kind, string info) { if (IsEnabled()) WriteEvent(151, id, kind, info); } // id - is a managed object. it gets translated to the object's address. ETW listeners must // keep track of GC movements in order to correlate the value passed to XyzSend with the // (possibly changed) value passed to XyzReceive [NonEvent, System.Security.SecuritySafeCritical] public unsafe void ThreadTransferReceiveObj(object id, int kind, string info) { ThreadTransferReceive((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info); } // id - represents a correlation ID that allows correlation of two activities, one stamped by // ThreadTransferSend, the other by ThreadTransferReceive // kind - identifies the transfer: values below 64 are reserved for the runtime. Currently used values: // 1 - managed Timers ("roaming" ID) // 2 - managed async IO operations (FileStream, PipeStream, a.o.) // 3 - WinRT dispatch operations // info - any additional information user code might consider interesting [Event(152, Level = EventLevel.Informational, Keywords = Keywords.ThreadTransfer, Task = Tasks.ThreadTransfer, Opcode = Opcodes.ReceiveHandled)] public void ThreadTransferReceiveHandled(long id, int kind, string info) { if (IsEnabled()) WriteEvent(152, id, kind, info); } // id - is a managed object. it gets translated to the object's address. ETW listeners must // keep track of GC movements in order to correlate the value passed to XyzSend with the // (possibly changed) value passed to XyzReceive [NonEvent, System.Security.SecuritySafeCritical] public unsafe void ThreadTransferReceiveHandledObj(object id, int kind, string info) { ThreadTransferReceive((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info); } // return a stable ID for a an object. We use the hash code which is not truely unique but is // close enough for now at least. we add to it 0x7FFFFFFF00000000 to make it distinguishable // from the style of ID that simply casts the object reference to a long (since old versions of the // runtime will emit IDs of that form). private static long IdForObject(object obj) { return obj.GetHashCode() + 0x7FFFFFFF00000000; } } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; namespace tk2dEditor.SpriteAnimationEditor { public class ClipEditor { // Accessors tk2dSpriteAnimationClip clip = null; public tk2dSpriteAnimationClip Clip { get { return clip; } set { SetClip(value); } } public EditorWindow hostEditorWindow = null; public void InitForNewClip() { selectClipNameField = true; timelineEditor.CurrentState.selectedFrame = 0; } bool selectClipNameField = false; // Locals int minInspectorWidth = 170; int inspectorWidth { get { return tk2dPreferences.inst.animInspectorWidth; } set { tk2dPreferences.inst.animInspectorWidth = Mathf.Max(value, minInspectorWidth); } } tk2dSpriteAnimationPreview preview = null; TimelineEditor timelineEditor = new TimelineEditor(); // Events public delegate void ClipEventDelegate(tk2dSpriteAnimationClip clip, int data); public event ClipEventDelegate clipNameChangedEvent; public event ClipEventDelegate clipDeletedEvent; public event ClipEventDelegate clipSelectionChangedEvent; void OnClipNameChanged() { if (clipNameChangedEvent != null) clipNameChangedEvent(clip, 0); } void OnClipDeleted() { if (clipDeletedEvent != null) clipDeletedEvent(clip, 0); } bool OnClipSelectionChanged(int direction) { if (clipSelectionChangedEvent != null) clipSelectionChangedEvent(clip, direction); return clipSelectionChangedEvent != null; } void Repaint() { if (hostEditorWindow != null) { hostEditorWindow.Repaint(); } else { HandleUtility.Repaint(); } } // Sprite changed callback // Create an instance - only ever use the instance through the property void SpriteChangedCallbackImpl(tk2dSpriteCollectionData spriteCollection, int spriteId, object data) { FrameGroup fg = data as FrameGroup; // Ensure the user hasn't switched sprite collection if (fg != null && frameGroups.IndexOf(fg) != -1) { fg.spriteCollection = spriteCollection; fg.spriteId = spriteId; foreach (tk2dSpriteAnimationFrame frame in fg.frames) { frame.spriteCollection = spriteCollection; frame.spriteId = spriteId; } RecalculateFrames(); Repaint(); } } tk2dSpriteGuiUtility.SpriteChangedCallback _spriteChangedCallbackInstance = null; tk2dSpriteGuiUtility.SpriteChangedCallback spriteChangedCallbackInstance { get { if (_spriteChangedCallbackInstance == null) { _spriteChangedCallbackInstance = new tk2dSpriteGuiUtility.SpriteChangedCallback( SpriteChangedCallbackImpl ); } return _spriteChangedCallbackInstance; } } // Editor operations public tk2dEditor.SpriteAnimationEditor.AnimOperator[] animOps = new tk2dEditor.SpriteAnimationEditor.AnimOperator[0]; // Construction/Destruction public void Destroy() { if (preview != null) preview.Destroy(); if (_animator != null) Object.DestroyImmediate(_animator.gameObject); } // Frame groups public class FrameGroup { public tk2dSpriteCollectionData spriteCollection; public int spriteId; public List<tk2dSpriteAnimationFrame> frames = new List<tk2dSpriteAnimationFrame>(); public int startFrame = 0; // this is a cache value used during the draw loop public bool SetFrameCount(int targetFrameCount) { bool changed = false; if (frames.Count > targetFrameCount) { frames.RemoveRange(targetFrameCount, frames.Count - targetFrameCount); changed = true; } while (frames.Count < targetFrameCount) { tk2dSpriteAnimationFrame f = new tk2dSpriteAnimationFrame(); f.spriteCollection = spriteCollection; f.spriteId = spriteId; frames.Add(f); changed = true; } return changed; } public List<tk2dSpriteAnimationFrame> DuplicateFrames(List<tk2dSpriteAnimationFrame> source) { List<tk2dSpriteAnimationFrame> dest = new List<tk2dSpriteAnimationFrame>(); foreach (tk2dSpriteAnimationFrame f in source) { tk2dSpriteAnimationFrame q = new tk2dSpriteAnimationFrame(); q.CopyFrom(f); dest.Add(q); } return dest; } public void Update() { foreach (tk2dSpriteAnimationFrame frame in frames) { frame.spriteCollection = spriteCollection; frame.spriteId = spriteId; } } } List<FrameGroup> frameGroups = new List<FrameGroup>(); // Sprite animator tk2dSpriteAnimator _animator = null; void InitAnimator() { if (_animator == null) { GameObject go = new GameObject("@SpriteAnimator"); go.hideFlags = HideFlags.HideAndDontSave; #if UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_3_6 || UNITY_3_7 || UNITY_3_8 || UNITY_3_9 go.active = false; #else go.SetActive(false); #endif go.AddComponent<tk2dSprite>(); _animator = go.AddComponent<tk2dSpriteAnimator>(); } } tk2dSpriteAnimator Animator { get { InitAnimator(); return _animator; } } bool CheckValidClip(tk2dSpriteAnimationClip clip) { bool nullCollectionFound = false; bool invalidSpriteIdFound = false; for (int i = 0; i < clip.frames.Length; ++i) { tk2dSpriteAnimationFrame frame = clip.frames[i]; if (frame.spriteCollection == null) { nullCollectionFound = true; } else { if (!frame.spriteCollection.IsValidSpriteId(frame.spriteId)) { if (frame.spriteCollection.FirstValidDefinitionIndex == -1) { nullCollectionFound = true; } else { invalidSpriteIdFound = true; } } } } if (nullCollectionFound) { EditorUtility.DisplayDialog("Invalid sprite collection found in clip.", "An invalid sprite collection has been found in the selected clip. Please correct this in the inspector.", "Ok"); return false; } if (invalidSpriteIdFound) { if (EditorUtility.DisplayDialog("Invalid sprite found in clip.", "An invalid sprite has been found in the selected clip. Has the sprite been deleted from the collection?\n\nDo you wish to replace this with a valid sprite from the collection?\n\nThis may not be correct, but you will be able to edit the clip after this.", "Yes", "No")) { for (int i = 0; i < clip.frames.Length; ++i) { tk2dSpriteAnimationFrame frame = clip.frames[i]; if (!frame.spriteCollection.IsValidSpriteId(frame.spriteId)) { frame.spriteId = frame.spriteCollection.FirstValidDefinitionIndex; } } return true; } else { return false; } } return true; } // Internal set clip, reset all void SetClip(tk2dSpriteAnimationClip clip) { if (this.clip != clip) { // reset stuff this.clip = clip; timelineEditor.Reset(); if (!repeatPlayAnimation) playAnimation = false; this.Animator.Stop(); // build frame groups if (clip != null) { if (CheckValidClip(clip)) { // check if clip is valid? frameGroups.Clear(); tk2dSpriteCollectionData lastSc = null; int lastSpriteId = -1; FrameGroup frameGroup = null; for (int i = 0; i < clip.frames.Length; ++i) { tk2dSpriteAnimationFrame f = clip.frames[i]; if (f.spriteCollection != lastSc || f.spriteId != lastSpriteId) { if (frameGroup != null) frameGroups.Add(frameGroup); frameGroup = new FrameGroup(); frameGroup.spriteCollection = f.spriteCollection; frameGroup.spriteId = f.spriteId; } lastSc = f.spriteCollection; lastSpriteId = f.spriteId; frameGroup.frames.Add(f); } if (frameGroup != null) frameGroups.Add(frameGroup); // Select first frame group if (frameGroups.Count > 0) { timelineEditor.CurrentState.selectedFrame = 0; } } } } } double previousTimeStamp = -1.0f; float deltaTime = 0.0f; void DrawPreview() { GUILayout.BeginVertical(GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); Rect r = GUILayoutUtility.GetRect(1, 1, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); // get frame from frame group if (playAnimation) { preview.Draw(r, Animator.Sprite.GetCurrentSpriteDef()); } else { if (timelineEditor.CurrentState.selectedFrame == -1) { preview.Draw(r, null); } else { int frame = timelineEditor.CurrentState.selectedFrame; if (frameGroups != null && frame < frameGroups.Count) { FrameGroup fg = frameGroups[frame]; tk2dSpriteCollectionData sc = fg.spriteCollection.inst; preview.Draw(r, sc.spriteDefinitions[fg.spriteId]); } } } GUILayout.EndVertical(); } void DrawClipInspector() { GUILayout.BeginHorizontal(); GUILayout.Label("Clip", EditorStyles.largeLabel); if (GUILayout.Button("Delete", GUILayout.Width(46)) && EditorUtility.DisplayDialog("Delete clip", "Are you sure you want to delete the selected clip?", "Yes", "No")) { OnClipDeleted(); } GUILayout.EndHorizontal(); GUI.SetNextControlName("tk2dAnimName"); string changedName = EditorGUILayout.TextField("Name", clip.name).Trim(); if (selectClipNameField) { GUI.FocusControl("tk2dAnimName"); selectClipNameField = false; } if (changedName != clip.name && changedName.Length > 0) { clip.name = changedName; OnClipNameChanged(); } EditorGUILayout.IntField("Frames", clip.frames.Length); float fps = EditorGUILayout.FloatField("Frame rate", clip.fps); if (fps > 0) clip.fps = fps; float clipTime = clip.frames.Length / fps; float newClipTime = EditorGUILayout.FloatField("Clip time", clipTime); if (newClipTime > 0 && newClipTime != clipTime) clip.fps = clip.frames.Length / newClipTime; tk2dSpriteAnimationClip.WrapMode newWrapMode = (tk2dSpriteAnimationClip.WrapMode)EditorGUILayout.EnumPopup("Wrap Mode", clip.wrapMode); if (clip.wrapMode == tk2dSpriteAnimationClip.WrapMode.LoopSection) { clip.loopStart = EditorGUILayout.IntField("Loop Start", clip.loopStart); clip.loopStart = Mathf.Clamp(clip.loopStart, 0, clip.frames.Length - 1); } if (newWrapMode != clip.wrapMode) { if (newWrapMode == tk2dSpriteAnimationClip.WrapMode.Single && clip.frames.Length > 1) { // Will we be truncating the animation? if (EditorUtility.DisplayDialog("Wrap mode -> Single", "This will truncate your clip to a single frame. Do you want to continue?", "Yes", "No")) { clip.wrapMode = newWrapMode; frameGroups.RemoveRange(1, frameGroups.Count - 1); frameGroups[0].SetFrameCount(1); ClipEditor.RecalculateFrames(clip, frameGroups); } } else { clip.wrapMode = newWrapMode; } } // Tools GUILayout.Space(8); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(" "); GUILayout.BeginVertical(); bool changed = false; foreach (tk2dEditor.SpriteAnimationEditor.AnimOperator animOp in animOps) { changed = animOp.OnClipInspectorGUI(clip, frameGroups, timelineEditor.CurrentState); if ((animOp.AnimEditOperations & tk2dEditor.SpriteAnimationEditor.AnimEditOperations.ClipContentChanged) != tk2dEditor.SpriteAnimationEditor.AnimEditOperations.None) { RecalculateFrames(); changed = true; } if ((animOp.AnimEditOperations & tk2dEditor.SpriteAnimationEditor.AnimEditOperations.ClipNameChanged) != tk2dEditor.SpriteAnimationEditor.AnimEditOperations.None) { OnClipNameChanged(); changed = true; } } if (changed) Repaint(); GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.Space(8); } void DrawFrameInspector() { GUILayout.Label("Frame", EditorStyles.largeLabel, GUILayout.ExpandWidth(true)); FrameGroup fg = frameGroups[timelineEditor.CurrentState.selectedFrame]; tk2dSpriteGuiUtility.SpriteSelector( fg.spriteCollection, fg.spriteId, spriteChangedCallbackInstance, fg ); int numFrames = EditorGUILayout.IntField("Frames", fg.frames.Count); if (numFrames != fg.frames.Count && numFrames > 0) { if (fg.SetFrameCount(numFrames)) { RecalculateFrames(); Repaint(); } } float time0 = fg.frames.Count / clip.fps; float time = EditorGUILayout.FloatField("Time", time0); if (time != time0) { int frameCount = Mathf.Max(1, (int)Mathf.Ceil(time * clip.fps)); if (fg.SetFrameCount(frameCount)) { RecalculateFrames(); Repaint(); } } // Tools GUILayout.Space(8); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(" "); GUILayout.BeginVertical(); bool changed = false; foreach (tk2dEditor.SpriteAnimationEditor.AnimOperator animOp in animOps) { changed = animOp.OnFrameGroupInspectorGUI(clip, frameGroups, timelineEditor.CurrentState); if ((animOp.AnimEditOperations & tk2dEditor.SpriteAnimationEditor.AnimEditOperations.ClipContentChanged) != tk2dEditor.SpriteAnimationEditor.AnimEditOperations.None) { RecalculateFrames(); changed = true; } } if (changed) Repaint(); GUILayout.EndVertical(); GUILayout.EndHorizontal(); } bool repeatPlayAnimation = false; const float repeatPlayWaitTimeConst = 1.0f; float repeatPlayWaitTime = 0; bool playAnimation = false; void TogglePlayAnimation() { if (playAnimation) { if (Animator != null) Animator.Stop(); playAnimation = false; } else { PlayAnimation(); } } void PlayAnimation() { if (Clip != null && Clip.frames.Length > 0) { playAnimation = true; previousTimeStamp = EditorApplication.timeSinceStartup; // reset time to avoid huge delta time repeatPlayWaitTime = repeatPlayWaitTimeConst; Animator.PlayFrom(Clip, 0); Repaint(); } } void DrawTransportToolbar() { GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true)); if (Event.current.type == EventType.Repaint) { if (playAnimation && !Animator.Playing) { if (repeatPlayAnimation || clip.wrapMode == tk2dSpriteAnimationClip.WrapMode.Single) { if (repeatPlayWaitTime > 0.0f) { repeatPlayWaitTime -= deltaTime; Repaint(); } else { Animator.PlayFrom(Clip, 0); repeatPlayWaitTime = repeatPlayWaitTimeConst; Repaint(); } } else { playAnimation = false; } } } GUIContent stopContent = new GUIContent("Stop", "Stop playing the current animation (Enter)"); GUIContent startContent = new GUIContent("Play", "Start playing the current animation (Enter)"); GUIContent playLabel = playAnimation ? stopContent : startContent; bool newPlayAnimation = GUILayout.Toggle(playAnimation, playLabel, EditorStyles.toolbarButton, GUILayout.Width(35)); if (newPlayAnimation != playAnimation) { if (newPlayAnimation == true) { PlayAnimation(); } else { Animator.Stop(); Repaint(); } playAnimation = newPlayAnimation; } repeatPlayAnimation = GUILayout.Toggle(repeatPlayAnimation, "Repeat", EditorStyles.toolbarButton); GUILayout.FlexibleSpace(); tk2dPreferences.inst.gridType = (tk2dGrid.Type)EditorGUILayout.EnumPopup(tk2dPreferences.inst.gridType, EditorStyles.toolbarDropDown, GUILayout.Width(95)); GUILayout.EndHorizontal(); } void DrawTriggerInspector() { GUILayout.Label("Trigger", EditorStyles.largeLabel, GUILayout.ExpandWidth(true)); tk2dSpriteAnimationFrame frame = clip.frames[timelineEditor.CurrentState.selectedTrigger]; EditorGUILayout.LabelField("Frame", timelineEditor.CurrentState.selectedTrigger.ToString()); frame.eventInfo = EditorGUILayout.TextField("Info", frame.eventInfo); frame.eventFloat = EditorGUILayout.FloatField("Float", frame.eventFloat); frame.eventInt = EditorGUILayout.IntField("Int", frame.eventInt); GUILayout.Space(8); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(" "); GUILayout.BeginVertical(); if (GUILayout.Button("Delete", EditorStyles.miniButton)) { clip.frames[timelineEditor.CurrentState.selectedTrigger].ClearTrigger(); timelineEditor.CurrentState.Reset(); Repaint(); } GUILayout.EndVertical(); GUILayout.EndHorizontal(); } Vector2 inspectorScrollbar = Vector2.zero; void DrawInspector() { EditorGUIUtility.LookLikeControls(80.0f, 40.0f); inspectorScrollbar = GUILayout.BeginScrollView(inspectorScrollbar, GUILayout.ExpandHeight(true), GUILayout.Width(inspectorWidth)); // Heading GUILayout.BeginVertical(tk2dEditorSkin.SC_InspectorHeaderBG, GUILayout.ExpandWidth(true)); DrawClipInspector(); GUILayout.EndVertical(); DrawTransportToolbar(); // Contents GUILayout.BeginVertical(tk2dEditorSkin.SC_InspectorBG, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); if (timelineEditor.CurrentState.selectedFrame != -1) DrawFrameInspector(); if (timelineEditor.CurrentState.selectedTrigger != -1) DrawTriggerInspector(); GUILayout.EndVertical(); GUILayout.EndScrollView(); Rect viewRect = GUILayoutUtility.GetLastRect(); // Resize handle inspectorWidth -= (int)tk2dGuiUtility.DragableHandle(4819518, viewRect, 0, tk2dGuiUtility.DragDirection.Horizontal); } public static void RecalculateFrames(tk2dSpriteAnimationClip clip, List<FrameGroup> frameGroups) { List<tk2dSpriteAnimationFrame> frames = new List<tk2dSpriteAnimationFrame>(); foreach (var v in frameGroups) frames.AddRange(v.frames); clip.frames = frames.ToArray(); } // Internal convenience function void RecalculateFrames() { ClipEditor.RecalculateFrames(clip, frameGroups); } void HandleKeyboardShortcuts() { Event ev = Event.current; if (ev.type == EventType.KeyDown && GUIUtility.keyboardControl == 0) { switch (ev.keyCode) { case KeyCode.UpArrow: if (OnClipSelectionChanged(-1)) ev.Use(); break; case KeyCode.DownArrow: if (OnClipSelectionChanged(1)) ev.Use(); break; case KeyCode.Return: TogglePlayAnimation(); ev.Use(); break; case KeyCode.F: if (preview != null) preview.ResetTransform(); ev.Use(); break; } } } public void Draw(int windowWidth) { if (clip == null) return; if (preview == null) preview = new tk2dSpriteAnimationPreview(); // Update if (Event.current.type == EventType.Repaint) { double t = EditorApplication.timeSinceStartup; if (previousTimeStamp < 0) previousTimeStamp = t; deltaTime = (float)(t - previousTimeStamp); previousTimeStamp = t; // Update sprite if (Animator.Playing) { Animator.ClipFps = clip.fps; Animator.UpdateAnimation(deltaTime); Repaint(); // refresh } } // Idle key handling if (GUIUtility.keyboardControl == 0) HandleKeyboardShortcuts(); GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); DrawPreview(); DrawInspector(); GUILayout.EndHorizontal(); float clipTimeMarker = -1.0f; if (playAnimation) { float clipTime = Animator.Playing ? Animator.EditorClipTime : 0.0f; clipTimeMarker = clipTime; } timelineEditor.Draw(windowWidth, clip, frameGroups, clipTimeMarker); GUILayout.EndVertical(); } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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.Linq; using System.Reflection; using Sensus.Probes; using Sensus.Probes.User.Scripts; using Sensus.Probes.User.Scripts.ProbeTriggerProperties; using Xamarin.Forms; namespace Sensus.UI { /// <summary> /// Allows the user to add a script trigger to a script runner. /// </summary> public class AddScriptTriggerPage : ContentPage { private ScriptRunner _scriptRunner; private Probe _selectedProbe; private PropertyInfo _selectedDatumProperty; private TriggerValueCondition _selectedCondition; private object _conditionValue; /// <summary> /// Initializes a new instance of the <see cref="AddScriptTriggerPage"/> class. /// </summary> /// <param name="scriptRunner">Script runner to add trigger to.</param> public AddScriptTriggerPage(ScriptRunner scriptRunner) { _scriptRunner = scriptRunner; Title = "Add Trigger"; Probe[] enabledProbes = _scriptRunner.Probe.Protocol.Probes.Where(p => p != _scriptRunner.Probe && p.Enabled).ToArray(); if (!enabledProbes.Any()) { Content = new Label { Text = "No enabled probes. Please enable them before creating triggers.", FontSize = 20 }; return; } StackLayout contentLayout = new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.FillAndExpand }; Label probeLabel = new Label { Text = "Probe:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; Picker probePicker = new Picker { Title = "Select Probe", HorizontalOptions = LayoutOptions.FillAndExpand }; foreach (Probe enabledProbe in enabledProbes) { probePicker.Items.Add(enabledProbe.DisplayName); } contentLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { probeLabel, probePicker } }); StackLayout triggerDefinitionLayout = new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.Start }; contentLayout.Children.Add(triggerDefinitionLayout); bool allowChangeCalculation = false; Switch changeSwitch = new Switch(); bool allowRegularExpression = false; Switch regexSwitch = new Switch(); Switch fireRepeatedlySwitch = new Switch(); TimePicker startTimePicker = new TimePicker { HorizontalOptions = LayoutOptions.FillAndExpand }; TimePicker endTimePicker = new TimePicker { HorizontalOptions = LayoutOptions.FillAndExpand }; probePicker.SelectedIndexChanged += (o, e) => { _selectedProbe = null; _selectedDatumProperty = null; _conditionValue = null; triggerDefinitionLayout.Children.Clear(); if (probePicker.SelectedIndex < 0) { return; } _selectedProbe = enabledProbes[probePicker.SelectedIndex]; PropertyInfo[] datumProperties = _selectedProbe.DatumType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttributes<ProbeTriggerProperty>().Any()).ToArray(); if (datumProperties.Length == 0) { return; } #region datum property picker Label datumPropertyLabel = new Label { Text = "Property:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; Picker datumPropertyPicker = new Picker { Title = "Select Datum Property", HorizontalOptions = LayoutOptions.FillAndExpand }; foreach (PropertyInfo datumProperty in datumProperties) { ProbeTriggerProperty triggerProperty = datumProperty.GetCustomAttributes<ProbeTriggerProperty>().First(); datumPropertyPicker.Items.Add(triggerProperty.Name ?? datumProperty.Name); } triggerDefinitionLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { datumPropertyLabel, datumPropertyPicker } }); #endregion #region condition picker (same for all datum types) Label conditionLabel = new Label { Text = "Condition:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; Picker conditionPicker = new Picker { Title = "Select Condition", HorizontalOptions = LayoutOptions.FillAndExpand }; TriggerValueCondition[] conditions = Enum.GetValues(typeof(TriggerValueCondition)) as TriggerValueCondition[]; foreach (TriggerValueCondition condition in conditions) { conditionPicker.Items.Add(condition.ToString()); } conditionPicker.SelectedIndexChanged += (oo, ee) => { if (conditionPicker.SelectedIndex < 0) { return; } _selectedCondition = conditions[conditionPicker.SelectedIndex]; }; triggerDefinitionLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { conditionLabel, conditionPicker } }); #endregion #region condition value for comparison, based on selected datum property -- includes change calculation (for double datum) and regex (for string datum) StackLayout conditionValueStack = new StackLayout { Orientation = StackOrientation.Vertical, HorizontalOptions = LayoutOptions.FillAndExpand }; triggerDefinitionLayout.Children.Add(conditionValueStack); datumPropertyPicker.SelectedIndexChanged += (oo, ee) => { _selectedDatumProperty = null; _conditionValue = null; conditionValueStack.Children.Clear(); if (datumPropertyPicker.SelectedIndex < 0) { return; } _selectedDatumProperty = datumProperties[datumPropertyPicker.SelectedIndex]; ProbeTriggerProperty datumTriggerAttribute = _selectedDatumProperty.GetCustomAttribute<ProbeTriggerProperty>(); View conditionValueStackView = null; if (datumTriggerAttribute is ListProbeTriggerProperty) { Picker conditionValuePicker = new Picker { Title = "Select Condition Value", HorizontalOptions = LayoutOptions.FillAndExpand }; object[] items = (datumTriggerAttribute as ListProbeTriggerProperty).Items; foreach (object item in items) { conditionValuePicker.Items.Add(item.ToString()); } conditionValuePicker.SelectedIndexChanged += (ooo, eee) => { if (conditionValuePicker.SelectedIndex < 0) { return; } _conditionValue = items[conditionValuePicker.SelectedIndex]; }; conditionValueStackView = conditionValuePicker; } else if (datumTriggerAttribute is DoubleProbeTriggerProperty) { Entry entry = new Entry { Keyboard = Keyboard.Numeric, HorizontalOptions = LayoutOptions.FillAndExpand }; entry.TextChanged += (ooo, eee) => { double value; if (double.TryParse(eee.NewTextValue, out value)) { _conditionValue = value; } }; conditionValueStackView = entry; allowChangeCalculation = true; } else if (datumTriggerAttribute is StringProbeTriggerProperty) { Entry entry = new Entry { Keyboard = Keyboard.Default, HorizontalOptions = LayoutOptions.FillAndExpand }; entry.TextChanged += (ooo, eee) => _conditionValue = eee.NewTextValue; conditionValueStackView = entry; allowRegularExpression = true; } else if (datumTriggerAttribute is BooleanProbeTriggerProperty) { Switch booleanSwitch = new Switch(); booleanSwitch.Toggled += (ooo, eee) => _conditionValue = eee.Value; conditionValueStackView = booleanSwitch; } Label conditionValueStackLabel = new Label { Text = "Value:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; conditionValueStack.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { conditionValueStackLabel, conditionValueStackView } }); #region change calculation if (allowChangeCalculation) { Label changeLabel = new Label { Text = "Change:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; changeSwitch.IsToggled = false; conditionValueStack.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { changeLabel, changeSwitch } }); } #endregion #region regular expression if (allowRegularExpression) { Label regexLabel = new Label { Text = "Regular Expression:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; regexSwitch.IsToggled = false; conditionValueStack.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { regexLabel, regexSwitch } }); } #endregion }; datumPropertyPicker.SelectedIndex = 0; #endregion #region fire repeatedly Label fireRepeatedlyLabel = new Label { Text = "Fire Repeatedly:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; fireRepeatedlySwitch.IsToggled = true; triggerDefinitionLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { fireRepeatedlyLabel, fireRepeatedlySwitch } }); #endregion #region start/end times Label startTimeLabel = new Label { Text = "Start Time:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; startTimePicker.Time = new TimeSpan(0, 0, 0); triggerDefinitionLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { startTimeLabel, startTimePicker } }); Label endTimeLabel = new Label { Text = "End Time:", FontSize = 20, VerticalTextAlignment = TextAlignment.Center }; endTimePicker.Time = new TimeSpan(23, 59, 59); triggerDefinitionLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { endTimeLabel, endTimePicker } }); #endregion }; probePicker.SelectedIndex = 0; Button okButton = new Button { Text = "OK", FontSize = 20, VerticalOptions = LayoutOptions.Start }; okButton.Clicked += async (o, e) => { try { _scriptRunner.Triggers.Add(new Probes.User.Scripts.Trigger(_selectedProbe, _selectedDatumProperty, _selectedCondition, _conditionValue, allowChangeCalculation && changeSwitch.IsToggled, fireRepeatedlySwitch.IsToggled, allowRegularExpression && regexSwitch.IsToggled, startTimePicker.Time, endTimePicker.Time)); await Navigation.PopAsync(); } catch (Exception ex) { await SensusServiceHelper.Get().FlashNotificationAsync($"Failed to add trigger: {ex.Message}"); SensusServiceHelper.Get().Logger.Log($"Failed to add trigger: {ex.Message}", LoggingLevel.Normal, GetType()); } }; contentLayout.Children.Add(okButton); Content = new ScrollView { Content = contentLayout }; } } }
using System; using Gtk; using Cairo; using Gdk; using System.Collections.Generic; using Moscrif.IDE.Option; //using Rsvg; using System.IO; using System.Reflection; using System.Runtime.InteropServices; namespace Moscrif.IDE.Editors.ImageView { public class ImageCanvas : DrawingArea { public ImageCanvas(string fileName, List<BarierPoint> shapeListPoint) { this.fileName = fileName; if (shapeListPoint != null) this.shapeListPoint = shapeListPoint; else shapeListPoint = new List<BarierPoint>(); if(MainClass.Settings.ImageEditors == null){ MainClass.Settings.ImageEditors = new Option.Settings.ImageEditorSetting(); MainClass.Settings.ImageEditors.LineWidth = 3; MainClass.Settings.ImageEditors.PointWidth = 5; MainClass.Settings.ImageEditors.LineColor = new Option.Settings.BackgroundColors(10,10,255,32767); MainClass.Settings.ImageEditors.PointColor = new Option.Settings.BackgroundColors(10,10,255,32767); MainClass.Settings.ImageEditors.SelectPointColor = new Option.Settings.BackgroundColors(255,10,10,32767); } lineWitdth = MainClass.Settings.ImageEditors.LineWidth; pointWidth = MainClass.Settings.ImageEditors.PointWidth; Gdk.Color gdkLineColor = new Gdk.Color(MainClass.Settings.ImageEditors.LineColor.Red, MainClass.Settings.ImageEditors.LineColor.Green,MainClass.Settings.ImageEditors.LineColor.Blue); Gdk.Color gdkPointColor = new Gdk.Color(MainClass.Settings.ImageEditors.PointColor.Red, MainClass.Settings.ImageEditors.PointColor.Green,MainClass.Settings.ImageEditors.PointColor.Blue); Gdk.Color gdkSelPointColor = new Gdk.Color(MainClass.Settings.ImageEditors.SelectPointColor.Red, MainClass.Settings.ImageEditors.SelectPointColor.Green,MainClass.Settings.ImageEditors.SelectPointColor.Blue); colorLine = gdkLineColor.ToCairoColor(MainClass.Settings.ImageEditors.LineColor.Alpha); colorPoint = gdkPointColor.ToCairoColor(MainClass.Settings.ImageEditors.PointColor.Alpha); colorSelectPoint = gdkSelPointColor.ToCairoColor(MainClass.Settings.ImageEditors.SelectPointColor.Alpha); Gdk.Pixbuf bg; try{ using (var fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open)) bg = new Gdk.Pixbuf(fs); bg = bg.ApplyEmbeddedOrientation(); this.HeightImage = bg.Height; this.WidthImage= bg.Width; }catch(Exception ex){ Tool.Logger.Error(ex.Message,null); } } public int WidthImage {get;set;} public int HeightImage {get;set;} private string fileName; List<BarierPoint> listPoint; List<BarierPoint> shapeListPoint; int width, height; int drawOffsetX, drawOffsetY; double scaling = 1; private BarierPoint movingPoint; private Cairo.Color colorLine; private Cairo.Color colorPoint; private Cairo.Color colorSelectPoint; private int lineWitdth; private int pointWidth; public List<BarierPoint> ListPoint { get { return this.listPoint; } } public List<BarierPoint> ShapeListPoint { get { List<BarierPoint> updateList = new List<BarierPoint>(); foreach(BarierPoint bp in this.listPoint){ BarierPoint updateBp = new BarierPoint(); updateBp.X = bp.X -(1/HeightImage); updateBp.Y = -bp.Y +(1/WidthImage);//(bp.Y -(1/WidthImage))*-1 updateList.Add(updateBp); } return updateList; } } public void RefreshSetting(){ lineWitdth = MainClass.Settings.ImageEditors.LineWidth; pointWidth = MainClass.Settings.ImageEditors.PointWidth; Gdk.Color gdkLineColor = new Gdk.Color(MainClass.Settings.ImageEditors.LineColor.Red, MainClass.Settings.ImageEditors.LineColor.Green,MainClass.Settings.ImageEditors.LineColor.Blue); Gdk.Color gdkPointColor = new Gdk.Color(MainClass.Settings.ImageEditors.PointColor.Red, MainClass.Settings.ImageEditors.PointColor.Green,MainClass.Settings.ImageEditors.PointColor.Blue); Gdk.Color gdkSelPointColor = new Gdk.Color(MainClass.Settings.ImageEditors.SelectPointColor.Red, MainClass.Settings.ImageEditors.SelectPointColor.Green,MainClass.Settings.ImageEditors.SelectPointColor.Blue); colorLine = gdkLineColor.ToCairoColor(MainClass.Settings.ImageEditors.LineColor.Alpha); colorPoint = gdkPointColor.ToCairoColor(MainClass.Settings.ImageEditors.PointColor.Alpha); colorSelectPoint = gdkSelPointColor.ToCairoColor(MainClass.Settings.ImageEditors.SelectPointColor.Alpha); try{ GdkWindow.InvalidateRect(new Gdk.Rectangle(drawOffsetX, drawOffsetY, width, height), false); } catch{} } protected override bool OnExposeEvent(Gdk.EventExpose e) { Gdk.Pixbuf bg; try{ //if(fileName.ToLower().EndsWith (".svg")){ //bg = Rsvg.Pixbuf.FromFile(fileName); // bg = Rsvg.Tool.PixbufFromFileAtSize(fileName,800,600); //} else{ using (var fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open)) bg = new Gdk.Pixbuf(fs); //} }catch(Exception ex){ Tool.Logger.Error(ex.Message,null); return true; } bg = bg.ApplyEmbeddedOrientation(); this.HeightImage = bg.Height; this.WidthImage= bg.Width; if ( this.listPoint == null ){ this.listPoint = new List<BarierPoint>(); if( this.shapeListPoint != null ){ foreach(BarierPoint bp in this.shapeListPoint){ BarierPoint updateBp = new BarierPoint(); updateBp.X = bp.X +(1/HeightImage); updateBp.Y = -bp.Y +(1/WidthImage); listPoint.Add(updateBp); } } } //Size imagesize = new Size (bg.Width, bg.Height); width = (int)(bg.Width * scaling); height = (int)(bg.Height * scaling); int x, y, w, h, d = 0; this.ParentWindow.GetGeometry(out x, out y, out w, out h, out d); drawOffsetX = (w - width) / 2; if (drawOffsetX < 0) drawOffsetX = 0; drawOffsetY = (h - height) / 2; if (drawOffsetY < 0) drawOffsetY = 0; using (Context cr = Gdk.CairoHelper.Create(e.Window)) { if(!MainClass.Platform.IsMac){ FillChecks (cr, 0, 0,w,h);//w, h); cr.Save (); cr.DrawRectangle(new Cairo.Rectangle(drawOffsetX - 1, drawOffsetY - 1, width + 1, height + 1), new Cairo.Color(0, 0, 0), 1); cr.Rectangle(new Cairo.Rectangle(drawOffsetX - 1, drawOffsetY - 1, width, height)); cr.Clip(); } cr.Scale(scaling, scaling); CairoHelper.SetSourcePixbuf(cr, bg, drawOffsetX / scaling, drawOffsetY / scaling); cr.Paint(); this.WidthRequest = width + 1; this.HeightRequest = height + 1; if (showBarierLayer) { Draw(cr, width, height); } cr.Scale(scaling, scaling); } return true; /*using (Context cr = Gdk.CairoHelper.Create (e.Window)) { int w, h; e.Window.GetSize (out w, out h); Draw (cr, w, h); } return true;*/ } #region TEST void Draw3Circles (Context cr, int xc, int yc, double radius, double alpha) { double subradius = radius * (2 / 3.0 - 0.1); cr.Color = new Cairo.Color (1.0, 0.0, 0.0, alpha); OvalPath (cr, xc + radius / 3.0 * Math.Cos (Math.PI * 0.5), yc - radius / 3.0 * Math.Sin (Math.PI * 0.5), subradius, subradius); cr.Fill (); cr.Color = new Cairo.Color (0.0, 1.0, 0.0, alpha); OvalPath (cr, xc + radius / 3.0 * Math.Cos (Math.PI * (0.5 + 2 / 0.3)), yc - radius / 3.0 * Math.Sin (Math.PI * (0.5 + 2 / 0.3)), subradius, subradius); cr.Fill (); cr.Color = new Cairo.Color (0.0, 0.0, 1.0, alpha); OvalPath (cr, xc + radius / 3.0 * Math.Cos (Math.PI * (0.5 + 4 / 0.3)), yc - radius / 3.0 * Math.Sin (Math.PI * (0.5 + 4 / 0.3)), subradius, subradius); cr.Fill (); } void Draw2 (Context cr, int width, int height) { double radius = 0.5 * Math.Min (width, height) - 10; int xc = width / 2; int yc = height / 2; Surface overlay = cr.Target.CreateSimilar (Content.ColorAlpha, width, height); Surface punch = cr.Target.CreateSimilar (Content.Alpha, width, height); Surface circles = cr.Target.CreateSimilar (Content.ColorAlpha, width, height); FillChecks (cr, 0, 0, width, height); cr.Save (); // Draw a black circle on the overlay using (Context cr_overlay = new Context (overlay)) { cr_overlay.Color = new Cairo.Color (0.0, 0.0, 0.0); OvalPath (cr_overlay, xc, yc, radius, radius); cr_overlay.Fill (); using (Context cr_tmp = new Context (punch)) Draw3Circles (cr_tmp, xc, yc, radius, 1.0); cr_overlay.Operator = Operator.DestOut; cr_overlay.SetSourceSurface (punch, 0, 0); cr_overlay.Paint (); using (Context cr_circles = new Context (circles)) { cr_circles.Operator = Operator.Over; Draw3Circles (cr_circles, xc, yc, radius, 0.5); } cr_overlay.Operator = Operator.Add; cr_overlay.SetSourceSurface (circles, 0, 0); cr_overlay.Paint (); } cr.SetSourceSurface (overlay, 0, 0); cr.Paint (); overlay.Destroy (); punch.Destroy (); circles.Destroy (); } #endregion void Draw(Context cr, int width, int height) { Surface overlay = cr.Target.CreateSimilar(Content.ColorAlpha, width, height); Surface addSurface = cr.Target.CreateSimilar(Content.ColorAlpha, width, height); // FillChecks (cr, 0, 0,width, height);//w, h); // cr.Save (); using (Context cr_overlay = new Context(overlay)) if (listPoint != null && listPoint.Count > 0) { using (Context cr_addSurface = new Context(addSurface)) { BarierPoint actualPoint; BarierPoint nearstBP; for (int i = 0; i < listPoint.Count; i++) { actualPoint = listPoint[i]; if (i == listPoint.Count-1) { nearstBP = listPoint[0]; } else nearstBP = listPoint[i + 1]; Cairo.Color clrPoint; if (actualPoint.Equals(movingPoint)) clrPoint =colorSelectPoint; else clrPoint = colorPoint; cr_addSurface.Color = clrPoint; OvalPath(cr_addSurface, actualPoint.X * scaling, actualPoint.Y * scaling, pointWidth, pointWidth); cr_addSurface.Fill(); cr_addSurface.Color = colorLine; LinePath(cr_addSurface, actualPoint.X * scaling, actualPoint.Y * scaling, nearstBP.X * scaling, nearstBP.Y * scaling); cr_addSurface.Fill(); } cr_overlay.Operator = Operator.Add; cr_overlay.SetSourceSurface(addSurface, 0, 0); cr_overlay.Paint(); } cr.Scale(1 / scaling, 1 / scaling); cr.SetSourceSurface(overlay, (int)(drawOffsetX), (int)(drawOffsetY)); cr.Paint(); } addSurface.Destroy(); overlay.Destroy(); } void FillChecks (Context cr, int x, int y, int width, int height) { int CHECK_SIZE = 32; cr.Save (); Surface check = cr.Target.CreateSimilar (Content.Color, 2 * CHECK_SIZE, 2 * CHECK_SIZE); // draw the check using (Context cr2 = new Context (check)) { cr2.Operator = Operator.Source; cr2.Color = new Cairo.Color (0.4, 0.4, 0.4); cr2.Rectangle (0, 0, 2 * CHECK_SIZE, 2 * CHECK_SIZE);//0,0 cr2.Fill (); cr2.Color = new Cairo.Color (0.7, 0.7, 0.7); cr2.Rectangle (x, y, CHECK_SIZE, CHECK_SIZE); cr2.Fill (); cr2.Rectangle (x + CHECK_SIZE, y + CHECK_SIZE, CHECK_SIZE, CHECK_SIZE); cr2.Fill (); } // Fill the whole surface with the check SurfacePattern check_pattern = new SurfacePattern (check); check_pattern.Extend = Extend.Repeat; cr.Source = check_pattern; cr.Rectangle (0, 0, width, height);//0,0 cr.Fill (); check_pattern.Destroy (); check.Destroy (); cr.Restore (); } public void StartMovingPoint(int x, int y, Cairo.PointD offset) { if (!ConvertPointToCanvasPoint(offset, ref x, ref y)) return; if (listPoint == null) listPoint = new List<BarierPoint>(); BarierPoint bp = new BarierPoint(x, y); BarierPoint nearstBP = BarierPoint.ClosestPoint(bp, listPoint); if (nearstBP != null) { movingPoint = nearstBP; //GdkWindow.InvalidateRect(new Gdk.Rectangle(drawOffsetX, drawOffsetY, width, height), false); } } public bool ConvertPointToCanvasPoint(Cairo.PointD offset, ref int x, ref int y) { if (x < drawOffsetX) return false; if (y < drawOffsetY) return false; if (x > drawOffsetX + width) return false; if (y > drawOffsetY + height) return false; x = (int)((x / scaling) - /* + offset.X*/(drawOffsetX / scaling)); y = (int)((y / scaling) - /*+ offset.Y*/(drawOffsetY / scaling)); return true; } public void StepMovingPoint(int x, int y, Cairo.PointD offset) { if (movingPoint == null) return; if (!ConvertPointToCanvasPoint(offset, ref x, ref y)) return; if (listPoint == null) listPoint = new List<BarierPoint>(); movingPoint.X = x; movingPoint.Y = y; GdkWindow.InvalidateRect(new Gdk.Rectangle(drawOffsetX, drawOffsetY, width, height), false); } public void EndMovingPoint(int x, int y, Cairo.PointD offset) { if (movingPoint == null) return; if (!ConvertPointToCanvasPoint(offset, ref x, ref y)) { movingPoint = null; return; } if (listPoint == null) listPoint = new List<BarierPoint>(); movingPoint.X = x; movingPoint.Y = y; movingPoint = null; GdkWindow.InvalidateRect(new Gdk.Rectangle(drawOffsetX, drawOffsetY, width, height), false); } public void EditPoint(int x, int y, Cairo.PointD offset) { int realX = x; int realY = y; if (!ConvertPointToCanvasPoint(offset, ref realX, ref realY)) return; if (listPoint == null) listPoint = new List<BarierPoint>(); BarierPoint bp = new BarierPoint(realX, realY); BarierPoint nearstBP = BarierPoint.ClosestPoint(bp, listPoint); double distance = 999; if(nearstBP != null){ distance = BarierPoint.Distance(bp,nearstBP); } if(distance <5.5 ){ StartMovingPoint(x,y,offset); } else { AddPoint(x,y,offset); } } public void AddPoint(int x, int y, Cairo.PointD offset) { if (!ConvertPointToCanvasPoint(offset, ref x, ref y)) return; if (listPoint == null) listPoint = new List<BarierPoint>(); BarierPoint bp = new BarierPoint(x, y); int indx = BarierPoint.ClosestLine(bp,listPoint); if(listPoint.Count >8){ } if((indx >listPoint.Count-1) || (indx<0)){ listPoint.Add(bp); } else { listPoint.Insert(indx,bp); } GdkWindow.InvalidateRect(new Gdk.Rectangle(drawOffsetX, drawOffsetY, width, height), false); } public void DeletePoint(int x, int y, Cairo.PointD offset) { if (!ConvertPointToCanvasPoint(offset, ref x, ref y)) return; if (listPoint == null) listPoint = new List<BarierPoint>(); BarierPoint bp = new BarierPoint(x, y); BarierPoint nearstBP = BarierPoint.ClosestPoint(bp, listPoint); if (nearstBP != null) { listPoint.Remove(nearstBP); GdkWindow.InvalidateRect(new Gdk.Rectangle(drawOffsetX, drawOffsetY, width, height), false); } } public void DeleteBarier() { if (listPoint != null) { listPoint.Clear(); GdkWindow.InvalidateRect(new Gdk.Rectangle(drawOffsetX, drawOffsetY, width, height), false); } } public void SetScale(double scale) { scaling = scale; GdkWindow.InvalidateRect(new Gdk.Rectangle(drawOffsetX, drawOffsetY, width, height), false); } private bool showBarierLayer; public bool ShowBarierLayer { set { showBarierLayer = value; GdkWindow.InvalidateRect(new Gdk.Rectangle(drawOffsetX, drawOffsetY, width, height), false); } } void OvalPath(Context cr, double xc, double yc, double xr, double yr) { Matrix m = cr.Matrix; cr.Translate(xc, yc); cr.Scale(1.0, yr / xr); cr.MoveTo(xr, 0.0); cr.Arc(0, 0, xr, 0, 2 * Math.PI); cr.ClosePath(); cr.Matrix = m; } void LinePath(Context cr, double xs, double ys, double xe, double ye) { Matrix m = cr.Matrix; cr.Antialias = Antialias.Subpixel; cr.LineWidth = lineWitdth; cr.LineCap = LineCap.Round; cr.MoveTo(xs, ys); cr.LineTo(xe, ye); cr.Stroke(); cr.ClosePath(); cr.Matrix = m; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Events { using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; /// <summary> /// Contains event type constants. The decision to use class and not enumeration is dictated /// by allowing users to create their own events and/or event types which would be impossible with enumerations. /// <para /> /// Note that this interface defines not only individual type constants, /// but arrays of types as well to be conveniently used with <see cref="IEvents"/> methods. /// <para /> /// NOTE: all types in range <b>from 1 to 1000 are reserved</b> for internal Ignite events /// and should not be used by user-defined events. /// </summary> public static class EventType { /// <summary> /// Built-in event type: checkpoint was saved. /// </summary> public static readonly int EvtCheckpointSaved = 1; /// <summary> /// Built-in event type: checkpoint was loaded. /// </summary> public static readonly int EvtCheckpointLoaded = 2; /// <summary> /// Built-in event type: checkpoint was removed. Reasons are: timeout expired, or or it was manually removed, /// or it was automatically removed by the task session. /// </summary> public static readonly int EvtCheckpointRemoved = 3; /// <summary> /// Built-in event type: node joined topology. New node has been discovered and joined grid topology. Note that /// even though a node has been discovered there could be a number of warnings in the log. In certain /// situations Ignite doesn't prevent a node from joining but prints warning messages into the log. /// </summary> public static readonly int EvtNodeJoined = 10; /// <summary> /// Built-in event type: node has normally left topology. /// </summary> public static readonly int EvtNodeLeft = 11; /// <summary> /// Built-in event type: node failed. Ignite detected that node has presumably crashed and is considered /// failed. /// </summary> public static readonly int EvtNodeFailed = 12; /// <summary> /// Built-in event type: node metrics updated. Generated when node's metrics are updated. In most cases this /// callback is invoked with every heartbeat received from a node (including local node). /// </summary> public static readonly int EvtNodeMetricsUpdated = 13; /// <summary> /// Built-in event type: local node segmented. Generated when node determines that it runs in invalid network /// segment. /// </summary> public static readonly int EvtNodeSegmented = 14; /// <summary> /// Built-in event type: client node disconnected. /// </summary> public static readonly int EvtClientNodeDisconnected = 16; /// <summary> /// Built-in event type: client node reconnected. /// </summary> public static readonly int EvtClientNodeReconnected = 17; /// <summary> /// Built-in event type: task started. /// </summary> public static readonly int EvtTaskStarted = 20; /// <summary> /// Built-in event type: task finished. Task got finished. This event is triggered every time a task finished /// without exception. /// </summary> public static readonly int EvtTaskFinished = 21; /// <summary> /// Built-in event type: task failed. Task failed. This event is triggered every time a task finished with an /// exception. Note that prior to this event, there could be other events recorded specific to the failure. /// </summary> public static readonly int EvtTaskFailed = 22; /// <summary> /// Built-in event type: task timed out. /// </summary> public static readonly int EvtTaskTimedout = 23; /// <summary> /// Built-in event type: task session attribute set. /// </summary> public static readonly int EvtTaskSessionAttrSet = 24; /// <summary> /// Built-in event type: task reduced. /// </summary> public static readonly int EvtTaskReduced = 25; /// <summary> /// Built-in event type: Ignite job was mapped in {@link org.apache.ignite.compute.ComputeTask#map(List, Object)} /// method. /// </summary> public static readonly int EvtJobMapped = 40; /// <summary> /// Built-in event type: Ignite job result was received by {@link /// org.apache.ignite.compute.ComputeTask#result(org.apache.ignite.compute.ComputeJobResult, List)} method. /// </summary> public static readonly int EvtJobResulted = 41; /// <summary> /// Built-in event type: Ignite job failed over. /// </summary> public static readonly int EvtJobFailedOver = 43; /// <summary> /// Built-in event type: Ignite job started. /// </summary> public static readonly int EvtJobStarted = 44; /// <summary> /// Built-in event type: Ignite job finished. Job has successfully completed and produced a result which from the /// user perspective can still be either negative or positive. /// </summary> public static readonly int EvtJobFinished = 45; /// <summary> /// Built-in event type: Ignite job timed out. /// </summary> public static readonly int EvtJobTimedout = 46; /// <summary> /// Built-in event type: Ignite job rejected during collision resolution. /// </summary> public static readonly int EvtJobRejected = 47; /// <summary> /// Built-in event type: Ignite job failed. Job has failed. This means that there was some error event during job /// execution and job did not produce a result. /// </summary> public static readonly int EvtJobFailed = 48; /// <summary> /// Built-in event type: Ignite job queued. Job arrived for execution and has been queued (added to passive queue /// during collision resolution). /// </summary> public static readonly int EvtJobQueued = 49; /// <summary> /// Built-in event type: Ignite job cancelled. /// </summary> public static readonly int EvtJobCancelled = 50; /// <summary> /// Built-in event type: entry created. /// </summary> public static readonly int EvtCacheEntryCreated = 60; /// <summary> /// Built-in event type: entry destroyed. /// </summary> public static readonly int EvtCacheEntryDestroyed = 61; /// <summary> /// Built-in event type: entry evicted. /// </summary> public static readonly int EvtCacheEntryEvicted = 62; /// <summary> /// Built-in event type: object put. /// </summary> public static readonly int EvtCacheObjectPut = 63; /// <summary> /// Built-in event type: object read. /// </summary> public static readonly int EvtCacheObjectRead = 64; /// <summary> /// Built-in event type: object removed. /// </summary> public static readonly int EvtCacheObjectRemoved = 65; /// <summary> /// Built-in event type: object locked. /// </summary> public static readonly int EvtCacheObjectLocked = 66; /// <summary> /// Built-in event type: object unlocked. /// </summary> public static readonly int EvtCacheObjectUnlocked = 67; /// <summary> /// Built-in event type: cache object swapped from swap storage. /// </summary> public static readonly int EvtCacheObjectSwapped = 68; /// <summary> /// Built-in event type: cache object unswapped from swap storage. /// </summary> public static readonly int EvtCacheObjectUnswapped = 69; /// <summary> /// Built-in event type: cache object was expired when reading it. /// </summary> public static readonly int EvtCacheObjectExpired = 70; /// <summary> /// Built-in event type: swap space data read. /// </summary> public static readonly int EvtSwapSpaceDataRead = 71; /// <summary> /// Built-in event type: swap space data stored. /// </summary> public static readonly int EvtSwapSpaceDataStored = 72; /// <summary> /// Built-in event type: swap space data removed. /// </summary> public static readonly int EvtSwapSpaceDataRemoved = 73; /// <summary> /// Built-in event type: swap space cleared. /// </summary> public static readonly int EvtSwapSpaceCleared = 74; /// <summary> /// Built-in event type: swap space data evicted. /// </summary> public static readonly int EvtSwapSpaceDataEvicted = 75; /// <summary> /// Built-in event type: cache object stored in off-heap storage. /// </summary> public static readonly int EvtCacheObjectToOffheap = 76; /// <summary> /// Built-in event type: cache object moved from off-heap storage back into memory. /// </summary> public static readonly int EvtCacheObjectFromOffheap = 77; /// <summary> /// Built-in event type: cache rebalance started. /// </summary> public static readonly int EvtCacheRebalanceStarted = 80; /// <summary> /// Built-in event type: cache rebalance stopped. /// </summary> public static readonly int EvtCacheRebalanceStopped = 81; /// <summary> /// Built-in event type: cache partition loaded. /// </summary> public static readonly int EvtCacheRebalancePartLoaded = 82; /// <summary> /// Built-in event type: cache partition unloaded. /// </summary> public static readonly int EvtCacheRebalancePartUnloaded = 83; /// <summary> /// Built-in event type: cache entry rebalanced. /// </summary> public static readonly int EvtCacheRebalanceObjectLoaded = 84; /// <summary> /// Built-in event type: cache entry unloaded. /// </summary> public static readonly int EvtCacheRebalanceObjectUnloaded = 85; /// <summary> /// Built-in event type: all nodes that hold partition left topology. /// </summary> public static readonly int EvtCacheRebalancePartDataLost = 86; /// <summary> /// Built-in event type: query executed. /// </summary> public static readonly int EvtCacheQueryExecuted = 96; /// <summary> /// Built-in event type: query entry read. /// </summary> public static readonly int EvtCacheQueryObjectRead = 97; /// <summary> /// Built-in event type: cache started. /// </summary> public static readonly int EvtCacheStarted = 98; /// <summary> /// Built-in event type: cache started. /// </summary> public static readonly int EvtCacheStopped = 99; /// <summary> /// Built-in event type: cache nodes left. /// </summary> public static readonly int EvtCacheNodesLeft = 100; /// <summary> /// All events indicating an error or failure condition. It is convenient to use when fetching all events /// indicating error or failure. /// </summary> [SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly", Justification = "Breaking change. Should be fixed in the next non-compatible release.")] public static readonly int[] EvtsError = { EvtJobTimedout, EvtJobFailed, EvtJobFailedOver, EvtJobRejected, EvtJobCancelled, EvtTaskTimedout, EvtTaskFailed, EvtCacheRebalanceStarted, EvtCacheRebalanceStopped }; /// <summary> /// All discovery events except for <see cref="EvtNodeMetricsUpdated" />. Subscription to <see /// cref="EvtNodeMetricsUpdated" /> can generate massive amount of event processing in most cases is not /// necessary. If this event is indeed required you can subscribe to it individually or use <see /// cref="EvtsDiscoveryAll" /> array. /// </summary> [SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly", Justification = "Breaking change. Should be fixed in the next non-compatible release.")] public static readonly int[] EvtsDiscovery = { EvtNodeJoined, EvtNodeLeft, EvtNodeFailed, EvtNodeSegmented, EvtClientNodeDisconnected, EvtClientNodeReconnected }; /// <summary> /// All discovery events. /// </summary> [SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly", Justification = "Breaking change. Should be fixed in the next non-compatible release.")] public static readonly int[] EvtsDiscoveryAll = { EvtNodeJoined, EvtNodeLeft, EvtNodeFailed, EvtNodeSegmented, EvtNodeMetricsUpdated, EvtClientNodeDisconnected, EvtClientNodeReconnected }; /// <summary> /// All Ignite job execution events. /// </summary> [SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly", Justification = "Breaking change. Should be fixed in the next non-compatible release.")] public static readonly int[] EvtsJobExecution = { EvtJobMapped, EvtJobResulted, EvtJobFailedOver, EvtJobStarted, EvtJobFinished, EvtJobTimedout, EvtJobRejected, EvtJobFailed, EvtJobQueued, EvtJobCancelled }; /// <summary> /// All Ignite task execution events. /// </summary> [SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly", Justification = "Breaking change. Should be fixed in the next non-compatible release.")] public static readonly int[] EvtsTaskExecution = { EvtTaskStarted, EvtTaskFinished, EvtTaskFailed, EvtTaskTimedout, EvtTaskSessionAttrSet, EvtTaskReduced }; /// <summary> /// All cache events. /// </summary> [SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly", Justification = "Breaking change. Should be fixed in the next non-compatible release.")] public static readonly int[] EvtsCache = { EvtCacheEntryCreated, EvtCacheEntryDestroyed, EvtCacheObjectPut, EvtCacheObjectRead, EvtCacheObjectRemoved, EvtCacheObjectLocked, EvtCacheObjectUnlocked, EvtCacheObjectSwapped, EvtCacheObjectUnswapped, EvtCacheObjectExpired }; /// <summary> /// All cache rebalance events. /// </summary> [SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly", Justification = "Breaking change. Should be fixed in the next non-compatible release.")] public static readonly int[] EvtsCacheRebalance = { EvtCacheRebalanceStarted, EvtCacheRebalanceStopped, EvtCacheRebalancePartLoaded, EvtCacheRebalancePartUnloaded, EvtCacheRebalanceObjectLoaded, EvtCacheRebalanceObjectUnloaded, EvtCacheRebalancePartDataLost }; /// <summary> /// All cache lifecycle events. /// </summary> [SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly", Justification = "Breaking change. Should be fixed in the next non-compatible release.")] public static readonly int[] EvtsCacheLifecycle = { EvtCacheStarted, EvtCacheStopped, EvtCacheNodesLeft }; /// <summary> /// All cache query events. /// </summary> [SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly", Justification = "Breaking change. Should be fixed in the next non-compatible release.")] public static readonly int[] EvtsCacheQuery = { EvtCacheQueryExecuted, EvtCacheQueryObjectRead }; /// <summary> /// All swap space events. /// </summary> [SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly", Justification = "Breaking change. Should be fixed in the next non-compatible release.")] public static readonly int[] EvtsSwapspace = { EvtSwapSpaceCleared, EvtSwapSpaceDataRemoved, EvtSwapSpaceDataRead, EvtSwapSpaceDataStored, EvtSwapSpaceDataEvicted }; /// <summary> /// All Ignite events. /// </summary> [SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly", Justification = "Breaking change. Should be fixed in the next non-compatible release.")] public static readonly int[] EvtsAll = GetAllEvents(); /// <summary> /// All Ignite events (<b>excluding</b> metric update event). /// </summary> [SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly", Justification = "Breaking change. Should be fixed in the next non-compatible release.")] public static readonly int[] EvtsAllMinusMetricUpdate = EvtsAll.Where(x => x != EvtNodeMetricsUpdated).ToArray(); /// <summary> /// Gets all the events. /// </summary> /// <returns>All event ids.</returns> private static int[] GetAllEvents() { return typeof (EventType).GetFields(BindingFlags.Public | BindingFlags.Static) .Where(x => x.FieldType == typeof (int)) .Select(x => (int) x.GetValue(null)).ToArray(); } } }
// 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.Completion; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources { public class NamedParameterCompletionProviderTests : AbstractCSharpCompletionProviderTests { public NamedParameterCompletionProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } internal override CompletionProvider CreateCompletionProvider() { return new NamedParameterCompletionProvider(); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SendEnterThroughToEditorTest() { const string markup = @" class Foo { public Foo(int a = 42) { } void Bar() { var b = new Foo($$ } }"; await VerifySendEnterThroughToEnterAsync(markup, "a:", sendThroughEnterOption: EnterKeyRule.Never, expected: false); await VerifySendEnterThroughToEnterAsync(markup, "a:", sendThroughEnterOption: EnterKeyRule.AfterFullyTypedWord, expected: true); await VerifySendEnterThroughToEnterAsync(markup, "a:", sendThroughEnterOption: EnterKeyRule.Always, expected: true); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitCharacterTest() { const string markup = @" class Foo { public Foo(int a = 42) { } void Bar() { var b = new Foo($$ } }"; await VerifyCommonCommitCharactersAsync(markup, textTypedSoFar: ""); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InObjectCreation() { var markup = @" class Foo { public Foo(int a = 42) { } void Bar() { var b = new Foo($$ } }"; await VerifyItemExistsAsync(markup, "a:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InBaseConstructor() { var markup = @" class Foo { public Foo(int a = 42) { } } class DogBed : Foo { public DogBed(int b) : base($$ } "; await VerifyItemExistsAsync(markup, "a:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InvocationExpression() { var markup = @" class Foo { void Bar(int a) { Bar($$ } } "; await VerifyItemExistsAsync(markup, "a:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InvocationExpressionAfterComma() { var markup = @" class Foo { void Bar(int a, string b) { Bar(b:"""", $$ } } "; await VerifyItemExistsAsync(markup, "a:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ElementAccessExpression() { var markup = @" class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } } class Program { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[$$ } } "; await VerifyItemExistsAsync(markup, "i:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialMethods() { var markup = @" partial class PartialClass { static partial void Foo(int declaring); static partial void Foo(int implementing) { } static void Caller() { Foo($$ } } "; await VerifyItemExistsAsync(markup, "declaring:"); await VerifyItemIsAbsentAsync(markup, "implementing:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterColon() { var markup = @" class Foo { void Bar(int a, string b) { Bar(a:$$ } } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(544292, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544292")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInCollectionInitializers() { var markup = @" using System.Collections.Generic; class Foo { void Bar(List<int> integers) { Bar(integers: new List<int> { 10, 11,$$ 12 }); } } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(544191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544191")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FilteringOverloadsByCallSite() { var markup = @" class Class1 { void Test() { Foo(boolean:true, $$) } void Foo(string str = ""hello"", char character = 'a') { } void Foo(string str = ""hello"", bool boolean = false) { } } "; await VerifyItemExistsAsync(markup, "str:"); await VerifyItemIsAbsentAsync(markup, "character:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DontFilterYet() { var markup = @" class Class1 { void Test() { Foo(str:"""", $$) } void Foo(string str = ""hello"", char character = 'a') { } void Foo(string str = ""hello"", bool boolean = false) { } } "; await VerifyItemExistsAsync(markup, "boolean:"); await VerifyItemExistsAsync(markup, "character:"); } [WorkItem(544191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544191")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FilteringOverloadsByCallSiteComplex() { var markup = @" class Foo { void Test() { Bar m = new Bar(); Method(obj:m, $$ } void Method(Bar obj, int num = 23, string str = """") { } void Method(double dbl = double.MinValue, string str = """") { } void Method(int num = 1, bool b = false, string str = """") { } void Method(Bar obj, bool b = false, string str = """") { } } class Bar { } "; await VerifyItemExistsAsync(markup, "str:"); await VerifyItemExistsAsync(markup, "num:"); await VerifyItemExistsAsync(markup, "b:"); await VerifyItemIsAbsentAsync(markup, "dbl:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloads() { var markup = @" class Foo { void Test() { object m = null; Method(m, $$ } void Method(object obj, int num = 23, string str = """") { } void Method(int num = 1, bool b = false, string str = """") { } void Method(object obj, bool b = false, string str = """") { } } "; await VerifyItemExistsAsync(markup, "str:"); await VerifyItemExistsAsync(markup, "num:"); await VerifyItemExistsAsync(markup, "b:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExistingNamedParamsAreFilteredOut() { var markup = @" class Foo { void Test() { object m = null; Method(obj: m, str: """", $$); } void Method(object obj, int num = 23, string str = """") { } void Method(double dbl = double.MinValue, string str = """") { } void Method(int num = 1, bool b = false, string str = """") { } void Method(object obj, bool b = false, string str = """") { } } "; await VerifyItemExistsAsync(markup, "num:"); await VerifyItemExistsAsync(markup, "b:"); await VerifyItemIsAbsentAsync(markup, "obj:"); await VerifyItemIsAbsentAsync(markup, "str:"); } [WorkItem(529369, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529369")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VerbatimIdentifierNotAKeyword() { var markup = @" class Program { void Foo(int @integer) { Foo(@i$$ } } "; await VerifyItemExistsAsync(markup, "integer:"); } [WorkItem(544209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544209")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionStringInMethodOverloads() { var markup = @" class Class1 { void Test() { Foo(boolean: true, $$) } void Foo(string obj = ""hello"") { } void Foo(bool boolean = false, Class1 obj = default(Class1)) { } } "; await VerifyItemExistsAsync(markup, "obj:", expectedDescriptionOrNull: $"({FeaturesResources.parameter}) Class1 obj = default(Class1)"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InDelegates() { var markup = @" public delegate void Del(string message); class Program { public static void DelegateMethod(string message) { System.Console.WriteLine(message); } static void Main(string[] args) { Del handler = DelegateMethod; handler($$ } }"; await VerifyItemExistsAsync(markup, "message:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InDelegateInvokeSyntax() { var markup = @" public delegate void Del(string message); class Program { public static void DelegateMethod(string message) { System.Console.WriteLine(message); } static void Main(string[] args) { Del handler = DelegateMethod; handler.Invoke($$ } }"; await VerifyItemExistsAsync(markup, "message:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInComment() { var markup = @" public class Test { static void Main() { M(x: 0, //Hit ctrl-space at the end of this comment $$ y: 1); } static void M(int x, int y) { } } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitWithColonWordFullyTyped() { var markup = @" class Program { static void Main(string[] args) { Main(args$$) } } "; var expected = @" class Program { static void Main(string[] args) { Main(args:) } } "; await VerifyProviderCommitAsync(markup, "args:", expected, ':', "args"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitWithColonWordPartiallyTyped() { var markup = @" class Program { static void Main(string[] args) { Main(ar$$) } } "; var expected = @" class Program { static void Main(string[] args) { Main(args:) } } "; await VerifyProviderCommitAsync(markup, "args:", expected, ':', "arg"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Globalization; using System.IO; using System.Text; using System.Threading.Tasks; namespace System.IO.Tests { public class StringWriterTests { static int[] iArrInvalidValues = new int[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, int.MinValue, short.MinValue }; static int[] iArrLargeValues = new int[] { int.MaxValue, int.MaxValue - 1, int.MaxValue / 2, int.MaxValue / 10, int.MaxValue / 100 }; static int[] iArrValidValues = new int[] { 10000, 100000, int.MaxValue / 2000, int.MaxValue / 5000, short.MaxValue }; private static char[] getCharArray() { return new char[]{ char.MinValue ,char.MaxValue ,'\t' ,' ' ,'$' ,'@' ,'#' ,'\0' ,'\v' ,'\'' ,'\u3190' ,'\uC3A0' ,'A' ,'5' ,'\uFE70' ,'-' ,';' ,'\u00E6' }; } private static StringBuilder getSb() { var chArr = getCharArray(); var sb = new StringBuilder(40); for (int i = 0; i < chArr.Length; i++) sb.Append(chArr[i]); return sb; } [Fact] public static void Ctor() { StringWriter sw = new StringWriter(); Assert.NotNull(sw); } [Fact] public static void CtorWithStringBuilder() { var sb = getSb(); StringWriter sw = new StringWriter(getSb()); Assert.NotNull(sw); Assert.Equal(sb.Length, sw.GetStringBuilder().Length); } [Fact] public static void CtorWithCultureInfo() { StringWriter sw = new StringWriter(new CultureInfo("en-gb")); Assert.NotNull(sw); Assert.Equal(new CultureInfo("en-gb"), sw.FormatProvider); } [Fact] public static void SimpleWriter() { var sw = new StringWriter(); sw.Write(4); var sb = sw.GetStringBuilder(); Assert.Equal("4", sb.ToString()); } [Fact] public static void WriteArray() { var chArr = getCharArray(); StringBuilder sb = getSb(); StringWriter sw = new StringWriter(sb); var sr = new StringReader(sw.GetStringBuilder().ToString()); for (int i = 0; i < chArr.Length; i++) { int tmp = sr.Read(); Assert.Equal((int)chArr[i], tmp); } } [Fact] public static void CantWriteNullArray() { var sw = new StringWriter(); Assert.Throws<ArgumentNullException>(() => sw.Write(null, 0, 0)); } [Fact] public static void CantWriteNegativeOffset() { var sw = new StringWriter(); Assert.Throws<ArgumentOutOfRangeException>(() => sw.Write(new char[0], -1, 0)); } [Fact] public static void CantWriteNegativeCount() { var sw = new StringWriter(); Assert.Throws<ArgumentOutOfRangeException>(() => sw.Write(new char[0], 0, -1)); } [Fact] public static void CantWriteIndexLargeValues() { var chArr = getCharArray(); for (int i = 0; i < iArrLargeValues.Length; i++) { StringWriter sw = new StringWriter(); AssertExtensions.Throws<ArgumentException>(null, () => sw.Write(chArr, iArrLargeValues[i], chArr.Length)); } } [Fact] public static void CantWriteCountLargeValues() { var chArr = getCharArray(); for (int i = 0; i < iArrLargeValues.Length; i++) { StringWriter sw = new StringWriter(); AssertExtensions.Throws<ArgumentException>(null, () => sw.Write(chArr, 0, iArrLargeValues[i])); } } [Fact] public static void WriteWithOffset() { StringWriter sw = new StringWriter(); StringReader sr; var chArr = getCharArray(); sw.Write(chArr, 2, 5); sr = new StringReader(sw.ToString()); for (int i = 2; i < 7; i++) { int tmp = sr.Read(); Assert.Equal((int)chArr[i], tmp); } } [Fact] public static void WriteWithLargeIndex() { for (int i = 0; i < iArrValidValues.Length; i++) { StringBuilder sb = new StringBuilder(int.MaxValue / 2000); StringWriter sw = new StringWriter(sb); var chArr = new char[int.MaxValue / 2000]; for (int j = 0; j < chArr.Length; j++) chArr[j] = (char)(j % 256); sw.Write(chArr, iArrValidValues[i] - 1, 1); string strTemp = sw.GetStringBuilder().ToString(); Assert.Equal(1, strTemp.Length); } } [Fact] public static void WriteWithLargeCount() { for (int i = 0; i < iArrValidValues.Length; i++) { StringBuilder sb = new StringBuilder(int.MaxValue / 2000); StringWriter sw = new StringWriter(sb); var chArr = new char[int.MaxValue / 2000]; for (int j = 0; j < chArr.Length; j++) chArr[j] = (char)(j % 256); sw.Write(chArr, 0, iArrValidValues[i]); string strTemp = sw.GetStringBuilder().ToString(); Assert.Equal(iArrValidValues[i], strTemp.Length); } } [Fact] public static void NewStringWriterIsEmpty() { var sw = new StringWriter(); Assert.Equal(string.Empty, sw.ToString()); } [Fact] public static void NewStringWriterHasEmptyStringBuilder() { var sw = new StringWriter(); Assert.Equal(string.Empty, sw.GetStringBuilder().ToString()); } [Fact] public static void ToStringReturnsWrittenData() { StringBuilder sb = getSb(); StringWriter sw = new StringWriter(sb); sw.Write(sb.ToString()); Assert.Equal(sb.ToString(), sw.ToString()); } [Fact] public static void StringBuilderHasCorrectData() { StringBuilder sb = getSb(); StringWriter sw = new StringWriter(sb); sw.Write(sb.ToString()); Assert.Equal(sb.ToString(), sw.GetStringBuilder().ToString()); } [Fact] public static void Closed_DisposedExceptions() { StringWriter sw = new StringWriter(); sw.Close(); ValidateDisposedExceptions(sw); } [Fact] public static void Disposed_DisposedExceptions() { StringWriter sw = new StringWriter(); sw.Dispose(); ValidateDisposedExceptions(sw); } private static void ValidateDisposedExceptions(StringWriter sw) { Assert.Throws<ObjectDisposedException>(() => { sw.Write('a'); }); Assert.Throws<ObjectDisposedException>(() => { sw.Write(new char[10], 0, 1); }); Assert.Throws<ObjectDisposedException>(() => { sw.Write("abc"); }); } [Fact] public static async Task FlushAsyncWorks() { StringBuilder sb = getSb(); StringWriter sw = new StringWriter(sb); sw.Write(sb.ToString()); await sw.FlushAsync(); // I think this is a noop in this case Assert.Equal(sb.ToString(), sw.GetStringBuilder().ToString()); } [Fact] public static void MiscWrites() { var sw = new StringWriter(); sw.Write('H'); sw.Write("ello World!"); Assert.Equal("Hello World!", sw.ToString()); } [Fact] public static async Task MiscWritesAsync() { var sw = new StringWriter(); await sw.WriteAsync('H'); await sw.WriteAsync(new char[] { 'e', 'l', 'l', 'o', ' ' }); await sw.WriteAsync("World!"); Assert.Equal("Hello World!", sw.ToString()); } [Fact] public static async Task MiscWriteLineAsync() { var sw = new StringWriter(); await sw.WriteLineAsync('H'); await sw.WriteLineAsync(new char[] { 'e', 'l', 'l', 'o' }); await sw.WriteLineAsync("World!"); Assert.Equal( string.Format("H{0}ello{0}World!{0}", Environment.NewLine), sw.ToString()); } [Fact] public static void GetEncoding() { var sw = new StringWriter(); Assert.Equal(Encoding.Unicode.WebName, sw.Encoding.WebName); } [Fact] public static void TestWriteMisc() { CultureInfo old = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = new CultureInfo("en-US"); // floating-point formatting comparison depends on culture try { var sw = new StringWriter(); sw.Write(true); sw.Write((char)'a'); sw.Write(new decimal(1234.01)); sw.Write((double)3452342.01); sw.Write((int)23456); sw.Write((long)long.MinValue); sw.Write((float)1234.50f); sw.Write((uint)uint.MaxValue); sw.Write((ulong)ulong.MaxValue); Assert.Equal("Truea1234.013452342.0123456-92233720368547758081234.5429496729518446744073709551615", sw.ToString()); } finally { CultureInfo.CurrentCulture = old; } } [Fact] public static void TestWriteObject() { var sw = new StringWriter(); sw.Write(new Object()); Assert.Equal("System.Object", sw.ToString()); } [Fact] public static void TestWriteLineMisc() { CultureInfo old = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = new CultureInfo("en-US"); // floating-point formatting comparison depends on culture try { var sw = new StringWriter(); sw.WriteLine((bool)false); sw.WriteLine((char)'B'); sw.WriteLine((int)987); sw.WriteLine((long)875634); sw.WriteLine((float)1.23457f); sw.WriteLine((uint)45634563); sw.WriteLine((ulong.MaxValue)); Assert.Equal( string.Format("False{0}B{0}987{0}875634{0}1.23457{0}45634563{0}18446744073709551615{0}", Environment.NewLine), sw.ToString()); } finally { CultureInfo.CurrentCulture = old; } } [Fact] public static void TestWriteLineObject() { var sw = new StringWriter(); sw.WriteLine(new Object()); Assert.Equal("System.Object" + Environment.NewLine, sw.ToString()); } [Fact] public static void TestWriteLineAsyncCharArray() { StringWriter sw = new StringWriter(); sw.WriteLineAsync(new char[] { 'H', 'e', 'l', 'l', 'o' }); Assert.Equal("Hello" + Environment.NewLine, sw.ToString()); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework throws NullReferenceException")] public async Task NullNewLineAsync() { using (MemoryStream ms = new MemoryStream()) { string newLine; using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8, 16, true)) { newLine = sw.NewLine; await sw.WriteLineAsync(default(string)); await sw.WriteLineAsync(default(string)); } ms.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(ms)) { Assert.Equal(newLine + newLine, await sr.ReadToEndAsync()); } } } } }
/* * Naiad ver. 0.5 * Copyright (c) Microsoft Corporation * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Research.Naiad.Runtime.Progress; namespace Microsoft.Research.Naiad.Diagnostics { /// <summary> /// Arguments of the event that is raised when a worker starts. /// </summary> public class WorkerStartArgs : EventArgs { /// <summary> /// The worker thread that is starting. /// </summary> public readonly int ThreadId; internal WorkerStartArgs(int threadId) { this.ThreadId = threadId; } } /// <summary> /// Arguments of the event that is raised when a worker is woken from sleep. /// </summary> public class WorkerWakeArgs : EventArgs { /// <summary> /// The worker thread that is waking. /// </summary> public readonly int ThreadId; internal WorkerWakeArgs(int threadId) { this.ThreadId = threadId; } } /// <summary> /// Arguments of the event that is raised when a worker goes to sleep. /// </summary> public class WorkerSleepArgs : EventArgs { /// <summary> /// The worker thread that is sleeping. /// </summary> public readonly int ThreadId; internal WorkerSleepArgs(int threadId) { this.ThreadId = threadId; } } /// <summary> /// Arguments of the event that is raised when a worker terminates. /// </summary> public class WorkerTerminateArgs : EventArgs { /// <summary> /// The worker thread that is terminating. /// </summary> public readonly int ThreadId; internal WorkerTerminateArgs(int threadId) { this.ThreadId = threadId; } } /// <summary> /// Arguments of the event that is raised when a vertex notification starts. /// </summary> public class VertexStartArgs : EventArgs { /// <summary> /// The worker thread on which the vertex is starting. /// </summary> public readonly int ThreadId; /// <summary> /// The stage of which the vertex is a member. /// </summary> public readonly Dataflow.Stage Stage; /// <summary> /// The ID of the vertex within its stage. /// </summary> public readonly int VertexId; /// <summary> /// The pointstamp of the notification that is being delivered. /// </summary> public readonly Pointstamp Pointstamp; internal VertexStartArgs(int threadId, Dataflow.Stage stage, int vertexId, Pointstamp pointstamp) { this.ThreadId = threadId; this.Stage = stage; this.VertexId = vertexId; this.Pointstamp = pointstamp; } } /// <summary> /// Arguments of the event that is raised when a vertex notification ends. /// </summary> public class VertexEndArgs : EventArgs { /// <summary> /// The worker thread on which the vertex is ending. /// </summary> public readonly int ThreadId; /// <summary> /// The stage of which the vertex is a member. /// </summary> public readonly Dataflow.Stage Stage; /// <summary> /// The ID of the vertex within its stage. /// </summary> public readonly int VertexId; /// <summary> /// The pointstamp of the notification that was delivered. /// </summary> public readonly Pointstamp Pointstamp; internal VertexEndArgs(int threadId, Dataflow.Stage stage, int vertexId, Pointstamp pointstamp) { this.ThreadId = threadId; this.Stage = stage; this.VertexId = vertexId; this.Pointstamp = pointstamp; } } /// <summary> /// Arguments of the event that is raised when a vertex notification is enqueued. /// </summary> public class VertexEnqueuedArgs : EventArgs { /// <summary> /// The worker thread on which the notification is being enqueued. /// </summary> public readonly int ThreadId; /// <summary> /// The stage of which the vertex is a member. /// </summary> public readonly Dataflow.Stage Stage; /// <summary> /// The ID of the vertex within its stage. /// </summary> public readonly int VertexId; /// <summary> /// The pointstamp of the notification that was enqueued. /// </summary> public readonly Pointstamp Pointstamp; internal VertexEnqueuedArgs(int threadId, Dataflow.Stage stage, int vertexId, Pointstamp pointstamp) { this.ThreadId = threadId; this.Stage = stage; this.VertexId = vertexId; this.Pointstamp = pointstamp; } } #if false public class OperatorReceiveArgs : EventArgs { public readonly Dataflow.Stage Stage; public readonly int VertexId; public readonly int ChannelId; public readonly int Count; public OperatorReceiveArgs(Dataflow.Stage stage, int vertexId, int channelId, int count) { this.Stage = stage; this.VertexId = vertexId; this.ChannelId = channelId; this.Count = count; } } public class OperatorSendArgs : EventArgs { public readonly Dataflow.Stage Stage; public readonly int VertexId; public readonly int ChannelId; public readonly int Count; public OperatorSendArgs(Dataflow.Stage stage, int vertexId, int channelId, int count) { this.Stage = stage; this.VertexId = vertexId; this.ChannelId = channelId; this.Count = count; } } #endif }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using log4net; using OpenMetaverse; namespace OpenSim.Framework.Console { public class ConsoleUtil { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public const int LocalIdNotFound = 0; /// <summary> /// Used by modules to display stock co-ordinate help, though possibly this should be under some general section /// rather than in each help summary. /// </summary> public const string CoordHelp = @"Each component of the coord is comma separated. There must be no spaces between the commas. If you don't care about the z component you can simply omit it. If you don't care about the x or y components then you can leave them blank (though a comma is still required) If you want to specify the maximum value of a component then you can use ~ instead of a number If you want to specify the minimum value of a component then you can use -~ instead of a number e.g. show object pos 20,20,20 to 40,40,40 delete object pos 20,20 to 40,40 show object pos ,20,20 to ,40,40 delete object pos ,,30 to ,,~ show object pos ,,-~ to ,,30"; public const string MinRawConsoleVectorValue = "-~"; public const string MaxRawConsoleVectorValue = "~"; public const string VectorSeparator = ","; public static char[] VectorSeparatorChars = VectorSeparator.ToCharArray(); /// <summary> /// Check if the given file path exists. /// </summary> /// <remarks>If not, warning is printed to the given console.</remarks> /// <returns>true if the file does not exist, false otherwise.</returns> /// <param name='console'></param> /// <param name='path'></param> public static bool CheckFileDoesNotExist(ICommandConsole console, string path) { if (File.Exists(path)) { console.OutputFormat("File {0} already exists. Please move or remove it.", path); return false; } return true; } /// <summary> /// Try to parse a console UUID from the console. /// </summary> /// <remarks> /// Will complain to the console if parsing fails. /// </remarks> /// <returns></returns> /// <param name='console'>If null then no complaint is printed.</param> /// <param name='rawUuid'></param> /// <param name='uuid'></param> public static bool TryParseConsoleUuid(ICommandConsole console, string rawUuid, out UUID uuid) { if (!UUID.TryParse(rawUuid, out uuid)) { if (console != null) console.OutputFormat("ERROR: {0} is not a valid uuid", rawUuid); return false; } return true; } public static bool TryParseConsoleLocalId(ICommandConsole console, string rawLocalId, out uint localId) { if (!uint.TryParse(rawLocalId, out localId)) { if (console != null) console.OutputFormat("ERROR: {0} is not a valid local id", localId); return false; } if (localId == 0) { if (console != null) console.OutputFormat("ERROR: {0} is not a valid local id - it must be greater than 0", localId); return false; } return true; } /// <summary> /// Tries to parse the input as either a UUID or a local ID. /// </summary> /// <returns>true if parsing succeeded, false otherwise.</returns> /// <param name='console'></param> /// <param name='rawId'></param> /// <param name='uuid'></param> /// <param name='localId'> /// Will be set to ConsoleUtil.LocalIdNotFound if parsing result was a UUID or no parse succeeded. /// </param> public static bool TryParseConsoleId(ICommandConsole console, string rawId, out UUID uuid, out uint localId) { if (TryParseConsoleUuid(null, rawId, out uuid)) { localId = LocalIdNotFound; return true; } if (TryParseConsoleLocalId(null, rawId, out localId)) { return true; } if (console != null) console.OutputFormat("ERROR: {0} is not a valid UUID or local id", rawId); return false; } /// <summary> /// Convert a minimum vector input from the console to an OpenMetaverse.Vector3 /// </summary> /// <param name='console'>Can be null if no console is available.</param> /// <param name='rawConsoleVector'>/param> /// <param name='vector'></param> /// <returns></returns> public static bool TryParseConsoleInt(ICommandConsole console, string rawConsoleInt, out int i) { if (!int.TryParse(rawConsoleInt, out i)) { if (console != null) console.OutputFormat("ERROR: {0} is not a valid integer", rawConsoleInt); return false; } return true; } /// <summary> /// Convert a minimum vector input from the console to an OpenMetaverse.Vector3 /// </summary> /// <param name='rawConsoleVector'>/param> /// <param name='vector'></param> /// <returns></returns> public static bool TryParseConsoleMinVector(string rawConsoleVector, out Vector3 vector) { return TryParseConsoleVector(rawConsoleVector, c => float.MinValue.ToString(), out vector); } /// <summary> /// Convert a maximum vector input from the console to an OpenMetaverse.Vector3 /// </summary> /// <param name='rawConsoleVector'>/param> /// <param name='vector'></param> /// <returns></returns> public static bool TryParseConsoleMaxVector(string rawConsoleVector, out Vector3 vector) { return TryParseConsoleVector(rawConsoleVector, c => float.MaxValue.ToString(), out vector); } /// <summary> /// Convert a vector input from the console to an OpenMetaverse.Vector3 /// </summary> /// <param name='rawConsoleVector'> /// A string in the form <x>,<y>,<z> where there is no space between values. /// Any component can be missing (e.g. ,,40). blankComponentFunc is invoked to replace the blank with a suitable value /// Also, if the blank component is at the end, then the comma can be missed off entirely (e.g. 40,30 or 40) /// The strings "~" and "-~" are valid in components. The first substitutes float.MaxValue whilst the second is float.MinValue /// Other than that, component values must be numeric. /// </param> /// <param name='blankComponentFunc'></param> /// <param name='vector'></param> /// <returns></returns> public static bool TryParseConsoleVector( string rawConsoleVector, Func<string, string> blankComponentFunc, out Vector3 vector) { List<string> components = rawConsoleVector.Split(VectorSeparatorChars).ToList(); if (components.Count < 1 || components.Count > 3) { vector = Vector3.Zero; return false; } for (int i = components.Count; i < 3; i++) components.Add(String.Empty); List<string> semiDigestedComponents = components.ConvertAll<string>( c => { if (String.IsNullOrEmpty(c)) return blankComponentFunc.Invoke(c); else if (c == MaxRawConsoleVectorValue) return float.MaxValue.ToString(); else if (c == MinRawConsoleVectorValue) return float.MinValue.ToString(); else return c; }); string semiDigestedConsoleVector = string.Join(VectorSeparator, semiDigestedComponents.ToArray()); // m_log.DebugFormat("[CONSOLE UTIL]: Parsing {0} into OpenMetaverse.Vector3", semiDigestedConsoleVector); return Vector3.TryParse(semiDigestedConsoleVector, out vector); } } }
// Copyright (c) 2013-2014 Andrew Downing // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Text; using ProtoBuf; [ProtoContract] public class Tile { [ProtoMember(1, AsReference = true)] private readonly Sim g; [ProtoMember(2)] public readonly int x; [ProtoMember(3)] public readonly int y; /// <summary> /// stores times when each path started or stopped seeing this tile, /// in format pathVis[path][gain/lose visibility index] /// </summary> [ProtoMember(4)] public Dictionary<int, List<long>> pathVis; /// <summary> /// stores times when each player started or stopped seeing this tile, /// in format playerVis[player][gain/lose visibility index] /// </summary> public List<long>[] playerVis; [ProtoMember(5)] private List<long> protoPlayerVis; /// <summary> /// stores times when each player started or stopped knowing that no other player can see this tile, /// in format exclusive[player][gain/lose exclusivity index] /// </summary> public List<long>[] exclusive; [ProtoMember(6)] private List<long> protoExclusive; /// <summary> /// stores where each unit can come from to get to this tile at any given time, /// in format waypoints[unit][waypoint index] /// </summary> [ProtoMember(7)] public Dictionary<int, List<Waypoint>> waypoints; private Tile() { } // for protobuf-net use only public Tile(Sim simVal, int xVal, int yVal) { g = simVal; x = xVal; y = yVal; pathVis = new Dictionary<int,List<long>>(); playerVis = new List<long>[g.players.Length]; if (Sim.enableNonLivePaths) exclusive = new List<long>[g.players.Length]; waypoints = new Dictionary<int, List<Waypoint>>(); for (int i = 0; i < g.players.Length; i++) { playerVis[i] = new List<long>(); if (Sim.enableNonLivePaths) exclusive[i] = new List<long>(); } } [ProtoBeforeSerialization] private void beforeSerialize() { protoPlayerVis = new List<long>(); for (int i = 0; i < playerVis.Length; i++) { protoPlayerVis.Add (playerVis[i].Count); protoPlayerVis.AddRange (playerVis[i]); } if (Sim.enableNonLivePaths) { protoExclusive = new List<long>(); for (int i = 0; i < exclusive.Length; i++) { protoExclusive.Add (exclusive[i].Count); protoExclusive.AddRange (exclusive[i]); } } } [ProtoAfterSerialization] private void afterSerialize() { protoPlayerVis = null; protoExclusive = null; } /// <summary> /// called manually from Sim.afterDeserialize() /// </summary> public void afterSimDeserialize() { if (pathVis == null) pathVis = new Dictionary<int, List<long>>(); if (waypoints == null) waypoints = new Dictionary<int, List<Waypoint>>(); playerVis = new List<long>[g.players.Length]; int player = 0; for (int i = 0; i < protoPlayerVis.Count; i += (int)protoPlayerVis[i] + 1) { playerVis[player] = protoPlayerVis.GetRange (i + 1, (int)protoPlayerVis[i]); player++; } protoPlayerVis = null; if (Sim.enableNonLivePaths) { exclusive = new List<long>[g.players.Length]; player = 0; for (int i = 0; i < protoExclusive.Count; i += (int)protoExclusive[i] + 1) { exclusive[player] = protoExclusive.GetRange (i + 1, (int)protoExclusive[i]); player++; } } protoExclusive = null; } /// <remarks>should only be called from TileUpdateEvt.apply()</remarks> public void pathVisToggle(Path path, long time) { if (!pathVis.ContainsKey(path.id)) pathVis.Add(path.id, new List<long>()); pathVis[path.id].Add(time); } public bool pathVisLatest(Path path) { return pathVis.ContainsKey(path.id) && visLatest(pathVis[path.id]); } public bool pathVisWhen(Path path, long time) { return pathVis.ContainsKey(path.id) && visWhen(pathVis[path.id], time); } public void playerVisRemove(Player player, long time) { // try adding tile to existing PlayerVisRemoveEvt with same player and time foreach (SimEvt evt in g.events) { if (evt is PlayerVisRemoveEvt) { PlayerVisRemoveEvt visEvt = evt as PlayerVisRemoveEvt; if (player == visEvt.player && time == visEvt.time) { // check that tile pos isn't a duplicate (recently added tiles are more likely to be duplicates) for (int i = visEvt.tiles.Count - 1; i >= Math.Max(0, visEvt.tiles.Count - 20); i--) { if (visEvt.tiles[i] == this) return; } // ok to add tile to existing event visEvt.tiles.Add (this); return; } } } // if no such PlayerVisRemoveEvt exists, add a new one g.events.addEvt(new PlayerVisRemoveEvt(time, player, this)); } /// <summary> /// returns if this tile is in the direct line of sight of a unit of specified player at latest possible time /// </summary> public bool playerDirectVisLatest(Player player) { foreach (int i in pathVis.Keys) { if (player == g.paths[i].player && visLatest(pathVis[i])) return true; } return false; } /// <summary> /// returns if this tile is in the direct line of sight of a unit of specified player at specified time /// </summary> public bool playerDirectVisWhen(Player player, long time, bool checkUnits = true) { foreach (int i in pathVis.Keys) { if (player == g.paths[i].player && visWhen(pathVis[i], time)) { if (!checkUnits) return true; Segment segment = g.paths[i].segmentWhen (time); if (segment != null && segment.units.Count > 0) return true; } } return false; } /// <summary> /// returns if this tile is either in the direct line of sight for specified player at latest possible time, /// or if player can infer that other players' units aren't in specified tile at latest time /// </summary> public bool playerVisLatest(Player player) { return visLatest(playerVis[player.id]); } /// <summary> /// returns if this tile is either in the direct line of sight for specified player at specified time, /// or if player can infer that other players' units aren't in specified tile at specified time /// </summary> public bool playerVisWhen(Player player, long time) { return visWhen(playerVis[player.id], time); } public void exclusiveAdd(Player player, long time) { if (exclusiveLatest (player)) throw new InvalidOperationException("tile is already exclusive"); exclusive[player.id].Add (time); // add waypoints to let units that can move to adjacent tile (using automatic time travel) move to this tile for (int tX = Math.Max (0, x - 1); tX <= Math.Min (g.tileLen () - 1, x + 1); tX++) { for (int tY = Math.Max (0, y - 1); tY <= Math.Min (g.tileLen () - 1, y + 1); tY++) { if (tX != x || tY != y) { foreach (var waypoint in g.tiles[tX, tY].waypoints) { long halfMoveInterval = new FP.Vector(tX - x << FP.precision, tY - y << FP.precision).length() / g.units[waypoint.Key].type.speed / 2; if (player == g.units[waypoint.Key].player && Waypoint.active (waypoint.Value.Last ()) && time >= waypoint.Value.Last ().time + halfMoveInterval) { g.events.addEvt (new WaypointAddEvt(time + halfMoveInterval, g.units[waypoint.Key], this, waypoint.Value.Last (), null)); } } } } } } public void exclusiveRemove(Player player, long time) { if (!exclusiveLatest(player)) throw new InvalidOperationException("tile is already not exclusive"); exclusive[player.id].Add (time); // clear waypoints on this tile foreach (var waypoint in waypoints) { if (player == g.units[waypoint.Key].player && Waypoint.active (waypoint.Value.Last ())) { waypointAdd (g.units[waypoint.Key], time, null, null); } } } /// <summary> /// calculates from player visibility tiles if specified player can infer that no other player can see this tile at latest possible time /// </summary> /// <remarks> /// The worst-case scenario would then be that every tile that this player can't see contains another player's unit /// of the type with the greatest visibility radius (though all units in this game have the same visibility radius). /// If no other player could see this tile in this worst case scenario, /// the player can infer that he/she is the only player that can see this tile. /// </remarks> public bool calcExclusive(Player player) { if (Sim.enableNonLivePaths && player.unseenTiles != 0) { // check that this player can see all nearby tiles if (g.inVis(g.lastUnseenTile.x - x, g.lastUnseenTile.y - y) && !g.tiles[g.lastUnseenTile.x, g.lastUnseenTile.y].playerVisLatest(player)) return false; int tXMin = Math.Max(0, x - g.tileVisRadius()); int tYMin = Math.Max(0, y - g.tileVisRadius()); for (int tX = Math.Min(g.tileLen() - 1, x + g.tileVisRadius()); tX >= tXMin; tX--) { for (int tY = Math.Min(g.tileLen() - 1, y + g.tileVisRadius()); tY >= tYMin; tY--) { if (g.inVis(tX - x, tY - y) && !g.tiles[tX, tY].playerVisLatest(player)) { g.lastUnseenTile.x = tX; g.lastUnseenTile.y = tY; return false; } } } } // check that no other players can see this tile foreach (Player player2 in g.players) { if (player != player2 && !player2.immutable && playerDirectVisLatest(player2)) return false; } return true; } /// <summary> /// returns if specified player can infer that no other player can see this tile at latest possible time /// </summary> public bool exclusiveLatest(Player player) { if (!Sim.enableNonLivePaths) return calcExclusive(player); return visLatest(exclusive[player.id]); } /// <summary> /// returns if specified player can infer that no other player can see this tile at specified time /// </summary> public bool exclusiveWhen(Player player, long time) { if (!Sim.enableNonLivePaths && time == g.timeSim) return calcExclusive (player); return visWhen(exclusive[player.id], time); } public Waypoint waypointAdd(Unit unit, long time, Waypoint prev, List<UnitSelection> start) { if (!waypoints.ContainsKey (unit.id)) waypoints[unit.id] = new List<Waypoint>(); Waypoint waypoint = new Waypoint(time, this, prev, start); waypoints[unit.id].Add (waypoint); return waypoint; } public Waypoint waypointLatest(Unit unit) { return waypoints.ContainsKey (unit.id) ? waypoints[unit.id].LastOrDefault () : null; } public Waypoint waypointWhen(Unit unit, long time) { if (waypoints.ContainsKey (unit.id)) { for (int i = waypoints[unit.id].Count - 1; i >= 0; i--) { if (time >= waypoints[unit.id][i].time) return waypoints[unit.id][i]; } } return null; } public FP.Vector centerPos() { return new FP.Vector((x << FP.precision) + (1 << FP.precision) / 2, (y << FP.precision) + (1 << FP.precision) / 2); } /// <summary> /// returns whether specified list indicates that the tile is visible at the latest possible time /// </summary> /// <remarks> /// The indices of the list are assumed to alternate between gaining visibility and losing visibility, /// where an empty list means not visible. So if there is an odd number of items in the list, the tile is visible. /// </remarks> private static bool visLatest(List<long> vis) { return vis.Count % 2 == 1; } /// <summary> /// returns index of specified list whose associated time is when the tile gained or lost visibility before the specified time /// </summary> /// <param name="vis">list of times in ascending order</param> private static int visIndexWhen(List<long> vis, long time) { int i; for (i = vis.Count - 1; i >= 0; i--) { if (time >= vis[i]) break; } return i; } /// <summary> /// returns whether specified list indicates that the tile is visible at specified time /// </summary> /// <remarks> /// The indices of the list are assumed to alternate between gaining visibility and losing visibility, /// where an even index means visible. So if the index associated with the specified time is even, the tile is visible. /// </remarks> private static bool visWhen(List<long> vis, long time) { return visIndexWhen(vis, time) % 2 == 0; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections; using System.Globalization; using Xunit; using SortedList_SortedListUtils; namespace SortedListCtorIKeyComp { public class Driver<KeyType, ValueType> { private Test m_test; public Driver(Test test) { m_test = test; } private CultureInfo _english = new CultureInfo("en"); private CultureInfo _german = new CultureInfo("de"); private CultureInfo _danish = new CultureInfo("da"); private CultureInfo _turkish = new CultureInfo("tr"); //CompareString lcid_en-US, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 1, NULL_STRING //CompareString 0x10407, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 0, NULL_STRING //CompareString lcid_da-DK, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, -1, NULL_STRING //CompareString lcid_en-US, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, 0, NULL_STRING //CompareString lcid_tr-TR, "NORM_IGNORECASE", "\u0131", 0, 1, "\u0049", 0, 1, 0, NULL_STRING private const String strAE = "AE"; private const String strUC4 = "\u00C4"; private const String straA = "aA"; private const String strAa = "Aa"; private const String strI = "I"; private const String strTurkishUpperI = "\u0131"; private const String strBB = "BB"; private const String strbb = "bb"; private const String value = "Default_Value"; public void TestEnum() { SortedList<String, String> _dic; IComparer<String> comparer; IComparer<String>[] predefinedComparers = new IComparer<String>[] { StringComparer.CurrentCulture, StringComparer.CurrentCultureIgnoreCase, StringComparer.OrdinalIgnoreCase, StringComparer.Ordinal}; foreach (IComparer<String> predefinedComparer in predefinedComparers) { _dic = new SortedList<String, String>(predefinedComparer); m_test.Eval(_dic.Comparer == predefinedComparer, String.Format("Err_4568aijueud! Comparer differ expected: {0} actual: {1}", predefinedComparer, _dic.Comparer)); m_test.Eval(_dic.Count == 0, String.Format("Err_23497sg! Count different: {0}", _dic.Count)); m_test.Eval(_dic.Keys.Count == 0, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count)); m_test.Eval(_dic.Values.Count == 0, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count)); } //Current culture CultureInfo.DefaultThreadCurrentCulture = _english; comparer = StringComparer.CurrentCulture; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_30641ajhied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strAE, value); m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_235rdag! Wrong result returned: {0}", _dic.ContainsKey(strUC4))); //bug #11263 in NDPWhidbey CultureInfo.DefaultThreadCurrentCulture = _german; comparer = StringComparer.CurrentCulture; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_54089ahued! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strAE, value); // same result in Desktop m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_23r7ag! Wrong result returned: {0}", CultureInfo.CurrentCulture.ToString()));// _dic.ContainsKey(strUC4))); //CurrentCultureIgnoreCase CultureInfo.DefaultThreadCurrentCulture = _english; comparer = StringComparer.CurrentCultureIgnoreCase; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_48856aied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(straA, value); m_test.Eval(_dic.ContainsKey(strAa), String.Format("Err_237g! Wrong result returned: {0}", _dic.ContainsKey(strAa))); CultureInfo.DefaultThreadCurrentCulture = _danish; comparer = StringComparer.CurrentCultureIgnoreCase; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_55685akdh! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0723f! Wrong result returned: {0}", _dic.ContainsKey(strAa))); //InvariantCultureIgnoreCase CultureInfo.DefaultThreadCurrentCulture = _english; comparer = StringComparer.OrdinalIgnoreCase; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_546488ajhie! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strI, value); m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234qf! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI))); CultureInfo.DefaultThreadCurrentCulture = _turkish; comparer = StringComparer.OrdinalIgnoreCase; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_1884ahied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strI, value); m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234ra7g! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI))); //Ordinal - not that many meaningful test CultureInfo.DefaultThreadCurrentCulture = _english; comparer = StringComparer.Ordinal; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_0177aued! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strBB, value); m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_1244sd! Wrong result returned: {0}", _dic.ContainsKey(strbb))); CultureInfo.DefaultThreadCurrentCulture = _danish; comparer = StringComparer.Ordinal; _dic = new SortedList<String, String>(comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_8978005aheud! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strBB, value); m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_235aeg! Wrong result returned: {0}", _dic.ContainsKey(strbb))); } public void TestParm() { //passing null will revert to the default comparison mechanism SortedList<String, String> _dic; IComparer<String> comparer = null; try { CultureInfo.DefaultThreadCurrentCulture = _english; _dic = new SortedList<String, String>(comparer); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_9237g! Wrong result returned: {0}", _dic.ContainsKey(strAa))); CultureInfo.DefaultThreadCurrentCulture = _danish; _dic = new SortedList<String, String>(comparer); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_90723f! Wrong result returned: {0}", _dic.ContainsKey(strAa))); } catch (Exception ex) { m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex)); } } public void IkeyComparerOwnImplementation() { //This just ensure that we can call our own implementation SortedList<String, String> _dic; IComparer<String> comparer = new MyOwnIKeyImplementation<String>(); try { CultureInfo.DefaultThreadCurrentCulture = _english; _dic = new SortedList<String, String>(comparer); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0237g! Wrong result returned: {0}", _dic.ContainsKey(strAa))); CultureInfo.DefaultThreadCurrentCulture = _danish; _dic = new SortedList<String, String>(comparer); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_00723f! Wrong result returned: {0}", _dic.ContainsKey(strAa))); } catch (Exception ex) { m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex)); } } } public class Constructor_IKeyComparer { [Fact] [ActiveIssue(846, PlatformID.AnyUnix)] public static void RunTests() { //This mostly follows the format established by the original author of these tests Test test = new Test(); Driver<String, String> driver1 = new Driver<String, String>(test); //Scenario 1: Pass all the enum values and ensure that the behavior is correct driver1.TestEnum(); //Scenario 2: Parm validation: null driver1.TestParm(); //Scenario 3: Implement our own IKeyComparer and check driver1.IkeyComparerOwnImplementation(); Assert.True(test.result); } } // [Serializable] internal class MyOwnIKeyImplementation<KeyType> : IComparer<KeyType> { public int GetHashCode(KeyType key) { //We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly return key.GetHashCode(); } public int Compare(KeyType key1, KeyType key2) { //We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly return key1.GetHashCode(); } public bool Equals(KeyType key1, KeyType key2) { return key1.Equals(key2); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Pay Item Leave Items Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class PILIDataSet : EduHubDataSet<PILI> { /// <inheritdoc /> public override string Name { get { return "PILI"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal PILIDataSet(EduHubContext Context) : base(Context) { Index_LEAVE_CODE = new Lazy<NullDictionary<string, IReadOnlyList<PILI>>>(() => this.ToGroupedNullDictionary(i => i.LEAVE_CODE)); Index_LEAVE_GROUP = new Lazy<NullDictionary<string, IReadOnlyList<PILI>>>(() => this.ToGroupedNullDictionary(i => i.LEAVE_GROUP)); Index_PIKEY = new Lazy<Dictionary<short, IReadOnlyList<PILI>>>(() => this.ToGroupedDictionary(i => i.PIKEY)); Index_PLTKEY = new Lazy<NullDictionary<string, IReadOnlyList<PILI>>>(() => this.ToGroupedNullDictionary(i => i.PLTKEY)); Index_TID = new Lazy<Dictionary<int, PILI>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="PILI" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="PILI" /> fields for each CSV column header</returns> internal override Action<PILI, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<PILI, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "PIKEY": mapper[i] = (e, v) => e.PIKEY = short.Parse(v); break; case "PLTKEY": mapper[i] = (e, v) => e.PLTKEY = v; break; case "LEAVE_GROUP": mapper[i] = (e, v) => e.LEAVE_GROUP = v; break; case "LEAVE_CODE": mapper[i] = (e, v) => e.LEAVE_CODE = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="PILI" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="PILI" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="PILI" /> entities</param> /// <returns>A merged <see cref="IEnumerable{PILI}"/> of entities</returns> internal override IEnumerable<PILI> ApplyDeltaEntities(IEnumerable<PILI> Entities, List<PILI> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.PIKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.PIKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<string, IReadOnlyList<PILI>>> Index_LEAVE_CODE; private Lazy<NullDictionary<string, IReadOnlyList<PILI>>> Index_LEAVE_GROUP; private Lazy<Dictionary<short, IReadOnlyList<PILI>>> Index_PIKEY; private Lazy<NullDictionary<string, IReadOnlyList<PILI>>> Index_PLTKEY; private Lazy<Dictionary<int, PILI>> Index_TID; #endregion #region Index Methods /// <summary> /// Find PILI by LEAVE_CODE field /// </summary> /// <param name="LEAVE_CODE">LEAVE_CODE value used to find PILI</param> /// <returns>List of related PILI entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PILI> FindByLEAVE_CODE(string LEAVE_CODE) { return Index_LEAVE_CODE.Value[LEAVE_CODE]; } /// <summary> /// Attempt to find PILI by LEAVE_CODE field /// </summary> /// <param name="LEAVE_CODE">LEAVE_CODE value used to find PILI</param> /// <param name="Value">List of related PILI entities</param> /// <returns>True if the list of related PILI entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByLEAVE_CODE(string LEAVE_CODE, out IReadOnlyList<PILI> Value) { return Index_LEAVE_CODE.Value.TryGetValue(LEAVE_CODE, out Value); } /// <summary> /// Attempt to find PILI by LEAVE_CODE field /// </summary> /// <param name="LEAVE_CODE">LEAVE_CODE value used to find PILI</param> /// <returns>List of related PILI entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PILI> TryFindByLEAVE_CODE(string LEAVE_CODE) { IReadOnlyList<PILI> value; if (Index_LEAVE_CODE.Value.TryGetValue(LEAVE_CODE, out value)) { return value; } else { return null; } } /// <summary> /// Find PILI by LEAVE_GROUP field /// </summary> /// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PILI</param> /// <returns>List of related PILI entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PILI> FindByLEAVE_GROUP(string LEAVE_GROUP) { return Index_LEAVE_GROUP.Value[LEAVE_GROUP]; } /// <summary> /// Attempt to find PILI by LEAVE_GROUP field /// </summary> /// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PILI</param> /// <param name="Value">List of related PILI entities</param> /// <returns>True if the list of related PILI entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByLEAVE_GROUP(string LEAVE_GROUP, out IReadOnlyList<PILI> Value) { return Index_LEAVE_GROUP.Value.TryGetValue(LEAVE_GROUP, out Value); } /// <summary> /// Attempt to find PILI by LEAVE_GROUP field /// </summary> /// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PILI</param> /// <returns>List of related PILI entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PILI> TryFindByLEAVE_GROUP(string LEAVE_GROUP) { IReadOnlyList<PILI> value; if (Index_LEAVE_GROUP.Value.TryGetValue(LEAVE_GROUP, out value)) { return value; } else { return null; } } /// <summary> /// Find PILI by PIKEY field /// </summary> /// <param name="PIKEY">PIKEY value used to find PILI</param> /// <returns>List of related PILI entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PILI> FindByPIKEY(short PIKEY) { return Index_PIKEY.Value[PIKEY]; } /// <summary> /// Attempt to find PILI by PIKEY field /// </summary> /// <param name="PIKEY">PIKEY value used to find PILI</param> /// <param name="Value">List of related PILI entities</param> /// <returns>True if the list of related PILI entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByPIKEY(short PIKEY, out IReadOnlyList<PILI> Value) { return Index_PIKEY.Value.TryGetValue(PIKEY, out Value); } /// <summary> /// Attempt to find PILI by PIKEY field /// </summary> /// <param name="PIKEY">PIKEY value used to find PILI</param> /// <returns>List of related PILI entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PILI> TryFindByPIKEY(short PIKEY) { IReadOnlyList<PILI> value; if (Index_PIKEY.Value.TryGetValue(PIKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find PILI by PLTKEY field /// </summary> /// <param name="PLTKEY">PLTKEY value used to find PILI</param> /// <returns>List of related PILI entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PILI> FindByPLTKEY(string PLTKEY) { return Index_PLTKEY.Value[PLTKEY]; } /// <summary> /// Attempt to find PILI by PLTKEY field /// </summary> /// <param name="PLTKEY">PLTKEY value used to find PILI</param> /// <param name="Value">List of related PILI entities</param> /// <returns>True if the list of related PILI entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByPLTKEY(string PLTKEY, out IReadOnlyList<PILI> Value) { return Index_PLTKEY.Value.TryGetValue(PLTKEY, out Value); } /// <summary> /// Attempt to find PILI by PLTKEY field /// </summary> /// <param name="PLTKEY">PLTKEY value used to find PILI</param> /// <returns>List of related PILI entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PILI> TryFindByPLTKEY(string PLTKEY) { IReadOnlyList<PILI> value; if (Index_PLTKEY.Value.TryGetValue(PLTKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find PILI by TID field /// </summary> /// <param name="TID">TID value used to find PILI</param> /// <returns>Related PILI entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public PILI FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find PILI by TID field /// </summary> /// <param name="TID">TID value used to find PILI</param> /// <param name="Value">Related PILI entity</param> /// <returns>True if the related PILI entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out PILI Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find PILI by TID field /// </summary> /// <param name="TID">TID value used to find PILI</param> /// <returns>Related PILI entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public PILI TryFindByTID(int TID) { PILI value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a PILI table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PILI]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[PILI]( [TID] int IDENTITY NOT NULL, [PIKEY] smallint NOT NULL, [PLTKEY] varchar(16) NULL, [LEAVE_GROUP] varchar(8) NULL, [LEAVE_CODE] varchar(8) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [PILI_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE NONCLUSTERED INDEX [PILI_Index_LEAVE_CODE] ON [dbo].[PILI] ( [LEAVE_CODE] ASC ); CREATE NONCLUSTERED INDEX [PILI_Index_LEAVE_GROUP] ON [dbo].[PILI] ( [LEAVE_GROUP] ASC ); CREATE CLUSTERED INDEX [PILI_Index_PIKEY] ON [dbo].[PILI] ( [PIKEY] ASC ); CREATE NONCLUSTERED INDEX [PILI_Index_PLTKEY] ON [dbo].[PILI] ( [PLTKEY] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PILI]') AND name = N'PILI_Index_LEAVE_CODE') ALTER INDEX [PILI_Index_LEAVE_CODE] ON [dbo].[PILI] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PILI]') AND name = N'PILI_Index_LEAVE_GROUP') ALTER INDEX [PILI_Index_LEAVE_GROUP] ON [dbo].[PILI] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PILI]') AND name = N'PILI_Index_PLTKEY') ALTER INDEX [PILI_Index_PLTKEY] ON [dbo].[PILI] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PILI]') AND name = N'PILI_Index_TID') ALTER INDEX [PILI_Index_TID] ON [dbo].[PILI] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PILI]') AND name = N'PILI_Index_LEAVE_CODE') ALTER INDEX [PILI_Index_LEAVE_CODE] ON [dbo].[PILI] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PILI]') AND name = N'PILI_Index_LEAVE_GROUP') ALTER INDEX [PILI_Index_LEAVE_GROUP] ON [dbo].[PILI] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PILI]') AND name = N'PILI_Index_PLTKEY') ALTER INDEX [PILI_Index_PLTKEY] ON [dbo].[PILI] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PILI]') AND name = N'PILI_Index_TID') ALTER INDEX [PILI_Index_TID] ON [dbo].[PILI] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="PILI"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="PILI"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<PILI> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[PILI] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the PILI data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the PILI data set</returns> public override EduHubDataSetDataReader<PILI> GetDataSetDataReader() { return new PILIDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the PILI data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the PILI data set</returns> public override EduHubDataSetDataReader<PILI> GetDataSetDataReader(List<PILI> Entities) { return new PILIDataReader(new EduHubDataSetLoadedReader<PILI>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class PILIDataReader : EduHubDataSetDataReader<PILI> { public PILIDataReader(IEduHubDataSetReader<PILI> Reader) : base (Reader) { } public override int FieldCount { get { return 8; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // PIKEY return Current.PIKEY; case 2: // PLTKEY return Current.PLTKEY; case 3: // LEAVE_GROUP return Current.LEAVE_GROUP; case 4: // LEAVE_CODE return Current.LEAVE_CODE; case 5: // LW_DATE return Current.LW_DATE; case 6: // LW_TIME return Current.LW_TIME; case 7: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // PLTKEY return Current.PLTKEY == null; case 3: // LEAVE_GROUP return Current.LEAVE_GROUP == null; case 4: // LEAVE_CODE return Current.LEAVE_CODE == null; case 5: // LW_DATE return Current.LW_DATE == null; case 6: // LW_TIME return Current.LW_TIME == null; case 7: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // PIKEY return "PIKEY"; case 2: // PLTKEY return "PLTKEY"; case 3: // LEAVE_GROUP return "LEAVE_GROUP"; case 4: // LEAVE_CODE return "LEAVE_CODE"; case 5: // LW_DATE return "LW_DATE"; case 6: // LW_TIME return "LW_TIME"; case 7: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "PIKEY": return 1; case "PLTKEY": return 2; case "LEAVE_GROUP": return 3; case "LEAVE_CODE": return 4; case "LW_DATE": return 5; case "LW_TIME": return 6; case "LW_USER": return 7; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests { public class InteractiveWindowHistoryTests : IDisposable { #region Helpers private readonly InteractiveWindowTestHost _testHost; private readonly IInteractiveWindow _window; private readonly IInteractiveWindowOperations _operations; public InteractiveWindowHistoryTests() { _testHost = new InteractiveWindowTestHost(); _window = _testHost.Window; _operations = _window.Operations; } void IDisposable.Dispose() { _testHost.Dispose(); } /// <summary> /// Sets the active code to the specified text w/o executing it. /// </summary> private void SetActiveCode(string text) { using (var edit = _window.CurrentLanguageBuffer.CreateEdit(EditOptions.None, reiteratedVersionNumber: null, editTag: null)) { edit.Replace(new Span(0, _window.CurrentLanguageBuffer.CurrentSnapshot.Length), text); edit.Apply(); } } private void InsertAndExecuteInputs(params string[] inputs) { foreach (var input in inputs) { InsertAndExecuteInput(input); } } private void InsertAndExecuteInput(string input) { _window.InsertCode(input); AssertCurrentSubmission(input); ExecuteInput(); } private void ExecuteInput() { ((InteractiveWindow)_window).ExecuteInputAsync().PumpingWait(); } private void AssertCurrentSubmission(string expected) { Assert.Equal(expected, _window.CurrentLanguageBuffer.CurrentSnapshot.GetText()); } #endregion Helpers [WpfFact] public void CheckHistoryPrevious() { const string inputString = "1 "; InsertAndExecuteInput(inputString); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString); } [WpfFact] public void CheckHistoryPreviousNotCircular() { //submit, submit, up, up, up const string inputString1 = "1 "; const string inputString2 = "2 "; InsertAndExecuteInput(inputString1); InsertAndExecuteInput(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); //this up should not be circular _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); } [WpfFact] public void CheckHistoryPreviousAfterSubmittingEntryFromHistory() { //submit, submit, submit, up, up, submit, up, up, up const string inputString1 = "1 "; const string inputString2 = "2 "; const string inputString3 = "3 "; InsertAndExecuteInput(inputString1); InsertAndExecuteInput(inputString2); InsertAndExecuteInput(inputString3); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString3); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); ExecuteInput(); //history navigation should start from the last history pointer _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); //has reached the top, no change _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); } [WpfFact] public void CheckHistoryPreviousAfterSubmittingNewEntryWhileNavigatingHistory() { //submit, submit, up, up, submit new, up, up, up const string inputString1 = "1 "; const string inputString2 = "2 "; const string inputString3 = "3 "; InsertAndExecuteInput(inputString1); InsertAndExecuteInput(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); SetActiveCode(inputString3); AssertCurrentSubmission(inputString3); ExecuteInput(); //History pointer should be reset. Previous should now bring up last entry _operations.HistoryPrevious(); AssertCurrentSubmission(inputString3); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); //has reached the top, no change _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); } [WpfFact] public void CheckHistoryNextNotCircular() { //submit, submit, down, up, down, down const string inputString1 = "1 "; const string inputString2 = "2 "; const string empty = ""; InsertAndExecuteInput(inputString1); InsertAndExecuteInput(inputString2); //Next should do nothing as history pointer is uninitialized and there is //no next entry. Buffer should be empty _operations.HistoryNext(); AssertCurrentSubmission(empty); //Go back once entry _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); //Go fwd one entry - should do nothing as history pointer is at last entry //buffer should have same value as before _operations.HistoryNext(); AssertCurrentSubmission(inputString2); //Next should again do nothing as it is the last item, bufer should have the same value _operations.HistoryNext(); AssertCurrentSubmission(inputString2); //This is to make sure the window doesn't crash ExecuteInput(); AssertCurrentSubmission(empty); } [WpfFact] public void CheckHistoryNextAfterSubmittingEntryFromHistory() { //submit, submit, submit, up, up, submit, down, down, down const string inputString1 = "1 "; const string inputString2 = "2 "; const string inputString3 = "3 "; InsertAndExecuteInput(inputString1); InsertAndExecuteInput(inputString2); InsertAndExecuteInput(inputString3); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString3); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); //submit inputString2 again. Should be added at the end of history ExecuteInput(); //history navigation should start from the last history pointer _operations.HistoryNext(); AssertCurrentSubmission(inputString3); //This next should take us to the InputString2 which was resubmitted _operations.HistoryNext(); AssertCurrentSubmission(inputString2); //has reached the top, no change _operations.HistoryNext(); AssertCurrentSubmission(inputString2); } [WpfFact] public void CheckHistoryNextAfterSubmittingNewEntryWhileNavigatingHistory() { //submit, submit, up, up, submit new, down, up const string inputString1 = "1 "; const string inputString2 = "2 "; const string inputString3 = "3 "; const string empty = ""; InsertAndExecuteInput(inputString1); InsertAndExecuteInput(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); SetActiveCode(inputString3); AssertCurrentSubmission(inputString3); ExecuteInput(); //History pointer should be reset. next should do nothing _operations.HistoryNext(); AssertCurrentSubmission(empty); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString3); } [WpfFact] public void CheckUncommittedInputAfterNavigatingHistory() { //submit, submit, up, up, submit new, down, up const string inputString1 = "1 "; const string inputString2 = "2 "; const string uncommittedInput = "uncommittedInput"; InsertAndExecuteInput(inputString1); InsertAndExecuteInput(inputString2); //Add uncommitted input SetActiveCode(uncommittedInput); //Navigate history. This should save uncommitted input _operations.HistoryPrevious(); //Navigate to next item at the end of history. //This should bring back uncommitted input _operations.HistoryNext(); AssertCurrentSubmission(uncommittedInput); } [WpfFact] public void CheckHistoryPreviousAfterReset() { const string resetCommand1 = "#reset"; const string resetCommand2 = "#reset "; InsertAndExecuteInput(resetCommand1); InsertAndExecuteInput(resetCommand2); _operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand2); _operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand1); _operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand1); } [WpfFact] public void TestHistoryPrevious() { InsertAndExecuteInputs("1", "2", "3"); _operations.HistoryPrevious(); AssertCurrentSubmission("3"); _operations.HistoryPrevious(); AssertCurrentSubmission("2"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); } [WpfFact] public void TestHistoryNext() { InsertAndExecuteInputs("1", "2", "3"); SetActiveCode("4"); _operations.HistoryNext(); AssertCurrentSubmission("4"); _operations.HistoryNext(); AssertCurrentSubmission("4"); _operations.HistoryPrevious(); AssertCurrentSubmission("3"); _operations.HistoryPrevious(); AssertCurrentSubmission("2"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryNext(); AssertCurrentSubmission("2"); _operations.HistoryNext(); AssertCurrentSubmission("3"); _operations.HistoryNext(); AssertCurrentSubmission("4"); _operations.HistoryNext(); AssertCurrentSubmission("4"); } [WpfFact] public void TestHistoryPreviousWithPattern_NoMatch() { InsertAndExecuteInputs("123", "12", "1"); _operations.HistoryPrevious("4"); AssertCurrentSubmission(""); _operations.HistoryPrevious("4"); AssertCurrentSubmission(""); } [WpfFact] public void TestHistoryPreviousWithPattern_PatternMaintained() { InsertAndExecuteInputs("123", "12", "1"); _operations.HistoryPrevious("12"); AssertCurrentSubmission("12"); // Skip over non-matching entry. _operations.HistoryPrevious("12"); AssertCurrentSubmission("123"); _operations.HistoryPrevious("12"); AssertCurrentSubmission("123"); } [WpfFact] public void TestHistoryPreviousWithPattern_PatternDropped() { InsertAndExecuteInputs("1", "2", "3"); _operations.HistoryPrevious("2"); AssertCurrentSubmission("2"); // Skip over non-matching entry. _operations.HistoryPrevious(null); AssertCurrentSubmission("1"); // Pattern isn't passed, so return to normal iteration. _operations.HistoryPrevious(null); AssertCurrentSubmission("1"); } [WpfFact] public void TestHistoryPreviousWithPattern_PatternChanged() { InsertAndExecuteInputs("10", "20", "15", "25"); _operations.HistoryPrevious("1"); AssertCurrentSubmission("15"); // Skip over non-matching entry. _operations.HistoryPrevious("2"); AssertCurrentSubmission("20"); // Skip over non-matching entry. _operations.HistoryPrevious("2"); AssertCurrentSubmission("20"); } [WpfFact] public void TestHistoryNextWithPattern_NoMatch() { InsertAndExecuteInputs("start", "1", "12", "123"); SetActiveCode("end"); _operations.HistoryPrevious(); AssertCurrentSubmission("123"); _operations.HistoryPrevious(); AssertCurrentSubmission("12"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryPrevious(); AssertCurrentSubmission("start"); _operations.HistoryNext("4"); AssertCurrentSubmission("end"); _operations.HistoryNext("4"); AssertCurrentSubmission("end"); } [WpfFact] public void TestHistoryNextWithPattern_PatternMaintained() { InsertAndExecuteInputs("start", "1", "12", "123"); SetActiveCode("end"); _operations.HistoryPrevious(); AssertCurrentSubmission("123"); _operations.HistoryPrevious(); AssertCurrentSubmission("12"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryPrevious(); AssertCurrentSubmission("start"); _operations.HistoryNext("12"); AssertCurrentSubmission("12"); // Skip over non-matching entry. _operations.HistoryNext("12"); AssertCurrentSubmission("123"); _operations.HistoryNext("12"); AssertCurrentSubmission("end"); } [WpfFact] public void TestHistoryNextWithPattern_PatternDropped() { InsertAndExecuteInputs("start", "3", "2", "1"); SetActiveCode("end"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryPrevious(); AssertCurrentSubmission("2"); _operations.HistoryPrevious(); AssertCurrentSubmission("3"); _operations.HistoryPrevious(); AssertCurrentSubmission("start"); _operations.HistoryNext("2"); AssertCurrentSubmission("2"); // Skip over non-matching entry. _operations.HistoryNext(null); AssertCurrentSubmission("1"); // Pattern isn't passed, so return to normal iteration. _operations.HistoryNext(null); AssertCurrentSubmission("end"); } [WpfFact] public void TestHistoryNextWithPattern_PatternChanged() { InsertAndExecuteInputs("start", "25", "15", "20", "10"); SetActiveCode("end"); _operations.HistoryPrevious(); AssertCurrentSubmission("10"); _operations.HistoryPrevious(); AssertCurrentSubmission("20"); _operations.HistoryPrevious(); AssertCurrentSubmission("15"); _operations.HistoryPrevious(); AssertCurrentSubmission("25"); _operations.HistoryPrevious(); AssertCurrentSubmission("start"); _operations.HistoryNext("1"); AssertCurrentSubmission("15"); // Skip over non-matching entry. _operations.HistoryNext("2"); AssertCurrentSubmission("20"); // Skip over non-matching entry. _operations.HistoryNext("2"); AssertCurrentSubmission("end"); } [WpfFact] public void TestHistorySearchPrevious() { InsertAndExecuteInputs("123", "12", "1"); // Default search string is empty. _operations.HistorySearchPrevious(); AssertCurrentSubmission("1"); // Pattern is captured before this step. _operations.HistorySearchPrevious(); AssertCurrentSubmission("12"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("123"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("123"); } [WpfFact] public void TestHistorySearchPreviousWithPattern() { InsertAndExecuteInputs("123", "12", "1"); SetActiveCode("12"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("12"); // Pattern is captured before this step. _operations.HistorySearchPrevious(); AssertCurrentSubmission("123"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("123"); } [WpfFact] public void TestHistorySearchNextWithPattern() { InsertAndExecuteInputs("12", "123", "12", "1"); SetActiveCode("end"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryPrevious(); AssertCurrentSubmission("12"); _operations.HistoryPrevious(); AssertCurrentSubmission("123"); _operations.HistoryPrevious(); AssertCurrentSubmission("12"); _operations.HistorySearchNext(); AssertCurrentSubmission("123"); // Pattern is captured before this step. _operations.HistorySearchNext(); AssertCurrentSubmission("12"); _operations.HistorySearchNext(); AssertCurrentSubmission("end"); } [WpfFact] public void TestHistoryPreviousAndSearchPrevious() { InsertAndExecuteInputs("200", "100", "30", "20", "10", "2", "1"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("10"); // Pattern is captured before this step. _operations.HistoryPrevious(); AssertCurrentSubmission("20"); // NB: Doesn't match pattern. _operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern. _operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); _operations.HistoryPrevious(); AssertCurrentSubmission("200"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("200"); // No-op results in non-matching history entry after SearchPrevious. } [WpfFact] public void TestHistoryPreviousAndSearchPrevious_ExplicitPattern() { InsertAndExecuteInputs("200", "100", "30", "20", "10", "2", "1"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("10"); // Pattern is captured before this step. _operations.HistoryPrevious("2"); AssertCurrentSubmission("20"); // NB: Doesn't match pattern. _operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern. _operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); _operations.HistoryPrevious("2"); AssertCurrentSubmission("200"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("200"); // No-op results in non-matching history entry after SearchPrevious. } [WpfFact] public void TestHistoryNextAndSearchNext() { InsertAndExecuteInputs("1", "2", "10", "20", "30", "100", "200"); SetActiveCode("4"); _operations.HistoryPrevious(); AssertCurrentSubmission("200"); _operations.HistoryPrevious(); AssertCurrentSubmission("100"); _operations.HistoryPrevious(); AssertCurrentSubmission("30"); _operations.HistoryPrevious(); AssertCurrentSubmission("20"); _operations.HistoryPrevious(); AssertCurrentSubmission("10"); _operations.HistoryPrevious(); AssertCurrentSubmission("2"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistorySearchNext(); AssertCurrentSubmission("10"); // Pattern is captured before this step. _operations.HistoryNext(); AssertCurrentSubmission("20"); // NB: Doesn't match pattern. _operations.HistorySearchNext(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern. _operations.HistorySearchNext(); AssertCurrentSubmission("4"); // Restoring input results in non-matching history entry after SearchNext. _operations.HistoryNext(); AssertCurrentSubmission("4"); } [WpfFact] public void TestHistoryNextAndSearchNext_ExplicitPattern() { InsertAndExecuteInputs("1", "2", "10", "20", "30", "100", "200"); SetActiveCode("4"); _operations.HistoryPrevious(); AssertCurrentSubmission("200"); _operations.HistoryPrevious(); AssertCurrentSubmission("100"); _operations.HistoryPrevious(); AssertCurrentSubmission("30"); _operations.HistoryPrevious(); AssertCurrentSubmission("20"); _operations.HistoryPrevious(); AssertCurrentSubmission("10"); _operations.HistoryPrevious(); AssertCurrentSubmission("2"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistorySearchNext(); AssertCurrentSubmission("10"); // Pattern is captured before this step. _operations.HistoryNext("2"); AssertCurrentSubmission("20"); // NB: Doesn't match pattern. _operations.HistorySearchNext(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern. _operations.HistorySearchNext(); AssertCurrentSubmission("4"); // Restoring input results in non-matching history entry after SearchNext. _operations.HistoryNext("2"); AssertCurrentSubmission("4"); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Reflection; using Paket.Bootstrapper.HelperProxies; namespace Paket.Bootstrapper.DownloadStrategies { internal class NugetDownloadStrategy : DownloadStrategy { internal class NugetApiHelper { private readonly string packageName; private readonly string nugetSource; const string NugetSourceAppSettingsKey = "NugetSource"; const string DefaultNugetSource = "https://www.nuget.org/api/v2"; const string GetPackageVersionTemplate = "{0}/package-versions/{1}"; const string GetLatestFromNugetUrlTemplate = "{0}/package/{1}"; const string GetSpecificFromNugetUrlTemplate = "{0}/package/{1}/{2}"; public NugetApiHelper(string packageName, string nugetSource) { this.packageName = packageName; this.nugetSource = nugetSource ?? ConfigurationManager.AppSettings[NugetSourceAppSettingsKey] ?? DefaultNugetSource; } internal string GetAllPackageVersions(bool includePrerelease) { var request = String.Format(GetPackageVersionTemplate, nugetSource, packageName); const string withPrereleases = "?includePrerelease=true"; if (includePrerelease) request += withPrereleases; return request; } internal string GetLatestPackage() { return String.Format(GetLatestFromNugetUrlTemplate, nugetSource, packageName); } internal string GetSpecificPackageVersion(string version) { return String.Format(GetSpecificFromNugetUrlTemplate, nugetSource, packageName, version); } } private IWebRequestProxy WebRequestProxy { get; set; } private IFileSystemProxy FileSystemProxy { get; set; } private string Folder { get; set; } private string NugetSource { get; set; } private const string PaketNugetPackageName = "Paket"; private const string PaketBootstrapperNugetPackageName = "Paket.Bootstrapper"; public NugetDownloadStrategy(IWebRequestProxy webRequestProxy, IFileSystemProxy fileSystemProxy, string folder, string nugetSource) { WebRequestProxy = webRequestProxy; FileSystemProxy = fileSystemProxy; Folder = folder; NugetSource = nugetSource; } public override string Name { get { return "Nuget"; } } protected override string GetLatestVersionCore(bool ignorePrerelease) { IEnumerable<string> allVersions = null; if (FileSystemProxy.DirectoryExists(NugetSource)) { var paketPrefix = "paket."; allVersions = FileSystemProxy. EnumerateFiles(NugetSource, "paket.*.nupkg", SearchOption.TopDirectoryOnly). Select(x => Path.GetFileNameWithoutExtension(x)). // If the specified character isn't a digit, then the file // likely contains the bootstrapper or paket.core Where(x => x.Length > paketPrefix.Length && Char.IsDigit(x[paketPrefix.Length])). Select(x => x.Substring(paketPrefix.Length)); } else { var apiHelper = new NugetApiHelper(PaketNugetPackageName, NugetSource); var versionRequestUrl = apiHelper.GetAllPackageVersions(!ignorePrerelease); var versions = WebRequestProxy.DownloadString(versionRequestUrl); allVersions = versions. Trim('[', ']'). Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries). Select(x => x.Trim('"')); } var latestVersion = allVersions. Select(SemVer.Create). Where(x => !ignorePrerelease || (x.PreRelease == null)). OrderBy(x => x). LastOrDefault(x => !String.IsNullOrWhiteSpace(x.Original)); return latestVersion != null ? latestVersion.Original : String.Empty; } protected override void DownloadVersionCore(string latestVersion, string target) { var apiHelper = new NugetApiHelper(PaketNugetPackageName, NugetSource); const string paketNupkgFile = "paket.latest.nupkg"; const string paketNupkgFileTemplate = "paket.{0}.nupkg"; var paketDownloadUrl = apiHelper.GetLatestPackage(); var paketFile = paketNupkgFile; if (!String.IsNullOrWhiteSpace(latestVersion)) { paketDownloadUrl = apiHelper.GetSpecificPackageVersion(latestVersion); paketFile = String.Format(paketNupkgFileTemplate, latestVersion); } var randomFullPath = Path.Combine(Folder, Path.GetRandomFileName()); FileSystemProxy.CreateDirectory(randomFullPath); var paketPackageFile = Path.Combine(randomFullPath, paketFile); if (FileSystemProxy.DirectoryExists(NugetSource)) { if (String.IsNullOrWhiteSpace(latestVersion)) latestVersion = GetLatestVersion(false); var sourcePath = Path.Combine(NugetSource, String.Format(paketNupkgFileTemplate, latestVersion)); ConsoleImpl.WriteInfo("Starting download from {0}", sourcePath); FileSystemProxy.CopyFile(sourcePath, paketPackageFile); } else { ConsoleImpl.WriteInfo("Starting download from {0}", paketDownloadUrl); try { WebRequestProxy.DownloadFile(paketDownloadUrl, paketPackageFile); } catch (WebException webException) { if (webException.Status == WebExceptionStatus.ProtocolError && !string.IsNullOrEmpty(latestVersion)) { var response = (HttpWebResponse) webException.Response; if (response.StatusCode == HttpStatusCode.NotFound) { throw new WebException(String.Format("Version {0} wasn't found (404)",latestVersion), webException); } if (response.StatusCode == HttpStatusCode.BadRequest) { // For cases like "The package version is not a valid semantic version" throw new WebException(String.Format("Unable to get version '{0}': {1}",latestVersion,response.StatusDescription), webException); } } Console.WriteLine(webException.ToString()); throw; } } FileSystemProxy.ExtractToDirectory(paketPackageFile, randomFullPath); var paketSourceFile = Path.Combine(randomFullPath, "tools", "paket.exe"); FileSystemProxy.CopyFile(paketSourceFile, target, true); FileSystemProxy.DeleteDirectory(randomFullPath, true); } protected override void SelfUpdateCore(string latestVersion) { string target = Assembly.GetExecutingAssembly().Location; var localVersion = FileSystemProxy.GetLocalFileVersion(target); if (localVersion.StartsWith(latestVersion)) { ConsoleImpl.WriteInfo("Bootstrapper is up to date. Nothing to do."); return; } var apiHelper = new NugetApiHelper(PaketBootstrapperNugetPackageName, NugetSource); const string paketNupkgFile = "paket.bootstrapper.latest.nupkg"; const string paketNupkgFileTemplate = "paket.bootstrapper.{0}.nupkg"; var getLatestFromNugetUrl = apiHelper.GetLatestPackage(); var paketDownloadUrl = getLatestFromNugetUrl; var paketFile = paketNupkgFile; if (!String.IsNullOrWhiteSpace(latestVersion)) { paketDownloadUrl = apiHelper.GetSpecificPackageVersion(latestVersion); paketFile = String.Format(paketNupkgFileTemplate, latestVersion); } var randomFullPath = Path.Combine(Folder, Path.GetRandomFileName()); FileSystemProxy.CreateDirectory(randomFullPath); var paketPackageFile = Path.Combine(randomFullPath, paketFile); if (FileSystemProxy.DirectoryExists(NugetSource)) { if (String.IsNullOrWhiteSpace(latestVersion)) latestVersion = GetLatestVersion(false); var sourcePath = Path.Combine(NugetSource, String.Format(paketNupkgFileTemplate, latestVersion)); ConsoleImpl.WriteInfo("Starting download from {0}", sourcePath); FileSystemProxy.CopyFile(sourcePath, paketPackageFile); } else { ConsoleImpl.WriteInfo("Starting download from {0}", paketDownloadUrl); WebRequestProxy.DownloadFile(paketDownloadUrl, paketPackageFile); } FileSystemProxy.ExtractToDirectory(paketPackageFile, randomFullPath); var paketSourceFile = Path.Combine(randomFullPath, "tools", "paket.bootstrapper.exe"); var renamedPath = BootstrapperHelper.GetTempFile("oldBootstrapper"); try { FileSystemProxy.MoveFile(target, renamedPath); FileSystemProxy.MoveFile(paketSourceFile, target); ConsoleImpl.WriteInfo("Self update of bootstrapper was successful."); } catch (Exception) { ConsoleImpl.WriteInfo("Self update failed. Resetting bootstrapper."); FileSystemProxy.MoveFile(renamedPath, target); throw; } FileSystemProxy.DeleteDirectory(randomFullPath, true); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; namespace DotSpatial.Data { /// <summary> /// InRamImageData can be used to create, load, manipulate and show Images whose data is kept in ram. /// This should not be used for big images. /// </summary> public class InRamImageData : ImageData { #region Fields /// <summary> /// The _my image. /// </summary> private Bitmap _myImage; #endregion #region Ctor /// <summary> /// Initializes a new instance of the <see cref="InRamImageData"/> class that is empty. This can be used to load or create ImageData. /// </summary> public InRamImageData() { } /// <summary> /// Initializes a new instance of the <see cref="InRamImageData"/> class from the specified fileName. /// </summary> /// <param name="fileName">The string filename.</param> public InRamImageData(string fileName) { Filename = fileName; Open(); } /// <summary> /// Initializes a new instance of the <see cref="InRamImageData"/> class. /// Creates the bitmap from the raw image specified. The bounds should be set on this later. /// </summary> /// <param name="rawImage">The raw image.</param> public InRamImageData(Image rawImage) { _myImage = new Bitmap(rawImage.Width, rawImage.Height); Width = rawImage.Width; Height = rawImage.Height; using (var g = Graphics.FromImage(_myImage)) g.DrawImageUnscaled(rawImage, 0, 0); WorldFile = new WorldFile(); double[] aff = { .5, 1.0, 0, rawImage.Height - .5, 0, -1.0 }; Bounds = new RasterBounds(rawImage.Height, rawImage.Width, aff); MemorySetup(); } /// <summary> /// Initializes a new instance of the <see cref="InRamImageData"/> class. /// Uses a bitmap and a geographic envelope in order to define a new imageData object. /// </summary> /// <param name="rawImage">The raw image.</param> /// <param name="bounds">The envelope bounds.</param> public InRamImageData(Bitmap rawImage, Extent bounds) { _myImage = rawImage; Width = rawImage.Width; Height = rawImage.Height; Bounds = new RasterBounds(rawImage.Height, rawImage.Width, bounds); MemorySetup(); } /// <summary> /// Initializes a new instance of the <see cref="InRamImageData"/> class. /// Constructs a new ImageData of the specified width and height. /// </summary> /// <param name="width">The integer width in pixels.</param> /// <param name="height">The integer height in pixels.</param> public InRamImageData(int width, int height) { WorldFile = new WorldFile(); double[] aff = { .5, 1.0, 0, height - .5, 0, -1.0 }; Bounds = new RasterBounds(height, width, aff); _myImage = new Bitmap(width, height); Width = width; Height = height; MemorySetup(); } #endregion /// <summary> /// Closes the image content. /// </summary> public override void Close() { // This doesn't need to do anything } /// <summary> /// Forces the image to read values from the graphic image format to the byte array format. /// </summary> public override void CopyBitmapToValues() { BitmapData bData = GetLockedBits(); Stride = bData.Stride; Values = new byte[bData.Height * bData.Stride]; Marshal.Copy(bData.Scan0, Values, 0, bData.Height * bData.Stride); _myImage.UnlockBits(bData); } /// <summary> /// Copies the values from the specified source image. /// </summary> /// <param name="source">The source image to copy values from.</param> public override void CopyValues(IImageData source) { Values = (byte[])source.Values.Clone(); NumBands = source.NumBands; BytesPerPixel = source.BytesPerPixel; } /// <summary> /// Forces the image to copy values from the byte array format to the image format. /// </summary> public override void CopyValuesToBitmap() { BitmapData bData = GetLockedBits(); Marshal.Copy(Values, 0, bData.Scan0, Values.Length); _myImage.UnlockBits(bData); } /// <summary> /// Creates a new image and world file, placing the default bounds at the origin, with one pixel per unit. /// </summary> /// <param name="fileName">The string fileName.</param> /// <param name="width">The integer width.</param> /// <param name="height">The integer height.</param> /// <param name="bandType">The ImageBandType that clarifies how the separate bands are layered in the image.</param> /// <returns>The create image.</returns> public override IImageData Create(string fileName, int width, int height, ImageBandType bandType) { Filename = fileName; WorldFile = new WorldFile(); double[] aff = { 1.0, 0, 0, -1.0, 0, height }; Bounds = new RasterBounds(height, width, aff); WorldFile.Filename = WorldFile.GenerateFilename(fileName); Width = width; Height = height; _myImage = new Bitmap(width, height); string ext = Path.GetExtension(fileName); ImageFormat imageFormat; switch (ext) { case ".bmp": imageFormat = ImageFormat.Bmp; break; case ".emf": imageFormat = ImageFormat.Emf; break; case ".exf": imageFormat = ImageFormat.Exif; break; case ".gif": imageFormat = ImageFormat.Gif; break; case ".ico": imageFormat = ImageFormat.Icon; break; case ".jpg": imageFormat = ImageFormat.Jpeg; break; case ".mbp": imageFormat = ImageFormat.MemoryBmp; break; case ".png": imageFormat = ImageFormat.Png; break; case ".tif": imageFormat = ImageFormat.Tiff; break; case ".wmf": imageFormat = ImageFormat.Wmf; break; default: throw new ArgumentOutOfRangeException(nameof(fileName), DataStrings.FileTypeNotSupported); } _myImage.Save(fileName, imageFormat); NumBands = 4; BytesPerPixel = 4; CopyBitmapToValues(); return this; } /// <summary> /// Returns the internal bitmap in this case. In other cases, this may have to be constructed /// from the unmanaged memory content. /// </summary> /// <returns>A Bitmap that represents the entire image.</returns> public override Bitmap GetBitmap() { return _myImage; } /// <summary> /// The geographic envelope gives the region that the image should be created for. /// The window gives the corresponding pixel dimensions for the image, so that images matching the resolution of the screen can be used. /// </summary> /// <param name="envelope">The geographic extents to retrieve data for.</param> /// <param name="window">The rectangle that defines the size of the drawing area in pixels.</param> /// <returns>A bitmap captured from the main image.</returns> public override Bitmap GetBitmap(Extent envelope, Rectangle window) { if (_myImage == null || window.Width == 0 || window.Height == 0) return null; if (Bounds == null || Bounds.Extent == null || Bounds.Extent.IsEmpty()) return null; // Gets the scaling factor for converting from geographic to pixel coordinates double dx = window.Width / envelope.Width; double dy = window.Height / envelope.Height; double[] a = Bounds.AffineCoefficients; // gets the affine scaling factors. float m11 = Convert.ToSingle(a[1] * dx); float m22 = Convert.ToSingle(a[5] * -dy); float m21 = Convert.ToSingle(a[2] * dx); float m12 = Convert.ToSingle(a[4] * -dy); double l = a[0] - (.5 * (a[1] + a[2])); // Left of top left pixel double t = a[3] - (.5 * (a[4] + a[5])); // top of top left pixel float xShift = (float)((l - envelope.MinX) * dx); float yShift = (float)((envelope.MaxY - t) * dy); var result = new Bitmap(window.Width, window.Height); using (var g = Graphics.FromImage(result)) { g.Transform = new Matrix(m11, m12, m21, m22, xShift, yShift); g.PixelOffsetMode = PixelOffsetMode.Half; if (m11 > 1 || m22 > 1) g.InterpolationMode = InterpolationMode.NearestNeighbor; if (!g.VisibleClipBounds.IsEmpty) { try { g.DrawImageUnscaled(_myImage, 0, 0); } catch (OverflowException) { // Raised by g.DrawImage if the new images extent is to small result.Dispose(); result = null; } } } return result; } /// <summary> /// Opens the file, assuming that the fileName has already been specified using a Dot Net Image object. /// </summary> public override void Open() { _myImage?.Dispose(); using (var stream = File.OpenRead(Filename)) using (var temp = Image.FromStream(stream)) { _myImage = new Bitmap(temp.Width, temp.Height, PixelFormat.Format32bppArgb); Width = temp.Width; Height = temp.Height; using (var g = Graphics.FromImage(_myImage)) g.DrawImage(temp, 0, 0, temp.Width, temp.Height); // don't draw unscaled because then nothing is shown } WorldFile = new WorldFile(Filename); if (WorldFile.Affine == null) WorldFile.Affine = new[] { .5, 1.0, 0, Height - .5, 0, -1.0 }; Bounds = new RasterBounds(Height, Width, WorldFile.Affine); NumBands = 4; BytesPerPixel = 4; CopyBitmapToValues(); } /// <summary> /// Saves the current image and world file. /// </summary> public override void Save() { _myImage.Save(Filename); WorldFile.Save(); } /// <summary> /// Saves the image to the specified fileName. /// </summary> /// <param name="fileName"> /// The string fileName to save this as. /// </param> public override void SaveAs(string fileName) { Filename = fileName; if (WorldFile != null) WorldFile.Filename = WorldFile.GenerateFilename(fileName); Save(); } /// <summary> /// Gets a block of data directly, converted into a bitmap. /// </summary> /// <param name="xOffset">The zero based integer column offset from the left.</param> /// <param name="yOffset">The zero based integer row offset from the top.</param> /// <param name="xSize">The integer number of pixel columns in the block. </param> /// <param name="ySize">The integer number of pixel rows in the block.</param> /// <returns>A Bitmap that is xSize, ySize.</returns> public override Bitmap ReadBlock(int xOffset, int yOffset, int xSize, int ySize) { var result = new Bitmap(xSize, ySize); using (Graphics g = Graphics.FromImage(result)) { g.DrawImage(_myImage, 0, 0, new Rectangle(xOffset, yOffset, xSize, ySize), GraphicsUnit.Pixel); } return result; } /// <summary> /// Saves a bitmap of data as a continuous block into the specified location. /// </summary> /// <param name="value">The bitmap value to save.</param> /// <param name="xOffset">The zero based integer column offset from the left.</param> /// <param name="yOffset">The zero based integer row offset from the top.</param> public override void WriteBlock(Bitmap value, int xOffset, int yOffset) { if (value == null) throw new ArgumentNullException(nameof(value)); using (var g = Graphics.FromImage(_myImage)) { g.DrawImage(value, new Rectangle(xOffset, yOffset, value.Width, value.Height), new Rectangle(0, 0, value.Width, value.Height), GraphicsUnit.Pixel); } } /// <summary> /// Release any unmanaged memory objects. /// </summary> /// <param name="disposeManagedResources"> /// The dispose Managed Resources. /// </param> protected override void Dispose(bool disposeManagedResources) { if (disposeManagedResources) { _myImage?.Dispose(); } base.Dispose(disposeManagedResources); } /// <summary> /// Extends the normal bounds changing behavior to also update the world file. /// </summary> /// <param name="bounds">Updates the world file.</param> protected override void OnBoundsChanged(IRasterBounds bounds) { if (WorldFile != null && bounds != null) WorldFile.Affine = bounds.AffineCoefficients; } private BitmapData GetLockedBits() { Rectangle bnds = new Rectangle(0, 0, Width, Height); PixelFormat pixelFormat; switch (NumBands) { case 4: pixelFormat = PixelFormat.Format32bppArgb; break; case 3: pixelFormat = PixelFormat.Format24bppRgb; break; case 1: pixelFormat = PixelFormat.Format16bppGrayScale; break; default: throw new ApplicationException("The specified number of bands is not supported."); } return _myImage.LockBits(bnds, ImageLockMode.ReadWrite, pixelFormat); } /// <summary> /// The memory setup. /// </summary> private void MemorySetup() { NumBands = 4; BytesPerPixel = 4; CopyBitmapToValues(); } } }
using System; using System.Runtime.InteropServices; namespace Godot { /// <summary> /// A color represented by red, green, blue, and alpha (RGBA) components. /// The alpha component is often used for transparency. /// Values are in floating-point and usually range from 0 to 1. /// Some properties (such as <see cref="CanvasItem.Modulate"/>) may accept values /// greater than 1 (overbright or HDR colors). /// /// If you want to supply values in a range of 0 to 255, you should use /// <see cref="Color8"/> and the <c>r8</c>/<c>g8</c>/<c>b8</c>/<c>a8</c> properties. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Color : IEquatable<Color> { /// <summary> /// The color's red component, typically on the range of 0 to 1. /// </summary> public float r; /// <summary> /// The color's green component, typically on the range of 0 to 1. /// </summary> public float g; /// <summary> /// The color's blue component, typically on the range of 0 to 1. /// </summary> public float b; /// <summary> /// The color's alpha (transparency) component, typically on the range of 0 to 1. /// </summary> public float a; /// <summary> /// Wrapper for <see cref="r"/> that uses the range 0 to 255 instead of 0 to 1. /// </summary> /// <value>Getting is equivalent to multiplying by 255 and rounding. Setting is equivalent to dividing by 255.</value> public int r8 { get { return (int)Math.Round(r * 255.0f); } set { r = value / 255.0f; } } /// <summary> /// Wrapper for <see cref="g"/> that uses the range 0 to 255 instead of 0 to 1. /// </summary> /// <value>Getting is equivalent to multiplying by 255 and rounding. Setting is equivalent to dividing by 255.</value> public int g8 { get { return (int)Math.Round(g * 255.0f); } set { g = value / 255.0f; } } /// <summary> /// Wrapper for <see cref="b"/> that uses the range 0 to 255 instead of 0 to 1. /// </summary> /// <value>Getting is equivalent to multiplying by 255 and rounding. Setting is equivalent to dividing by 255.</value> public int b8 { get { return (int)Math.Round(b * 255.0f); } set { b = value / 255.0f; } } /// <summary> /// Wrapper for <see cref="a"/> that uses the range 0 to 255 instead of 0 to 1. /// </summary> /// <value>Getting is equivalent to multiplying by 255 and rounding. Setting is equivalent to dividing by 255.</value> public int a8 { get { return (int)Math.Round(a * 255.0f); } set { a = value / 255.0f; } } /// <summary> /// The HSV hue of this color, on the range 0 to 1. /// </summary> /// <value>Getting is a long process, refer to the source code for details. Setting uses <see cref="FromHSV"/>.</value> public float h { get { float max = Math.Max(r, Math.Max(g, b)); float min = Math.Min(r, Math.Min(g, b)); float delta = max - min; if (delta == 0) { return 0; } float h; if (r == max) { h = (g - b) / delta; // Between yellow & magenta } else if (g == max) { h = 2 + ((b - r) / delta); // Between cyan & yellow } else { h = 4 + ((r - g) / delta); // Between magenta & cyan } h /= 6.0f; if (h < 0) { h += 1.0f; } return h; } set { this = FromHSV(value, s, v, a); } } /// <summary> /// The HSV saturation of this color, on the range 0 to 1. /// </summary> /// <value>Getting is equivalent to the ratio between the min and max RGB value. Setting uses <see cref="FromHSV"/>.</value> public float s { get { float max = Math.Max(r, Math.Max(g, b)); float min = Math.Min(r, Math.Min(g, b)); float delta = max - min; return max == 0 ? 0 : delta / max; } set { this = FromHSV(h, value, v, a); } } /// <summary> /// The HSV value (brightness) of this color, on the range 0 to 1. /// </summary> /// <value>Getting is equivalent to using <see cref="Math.Max(float, float)"/> on the RGB components. Setting uses <see cref="FromHSV"/>.</value> public float v { get { return Math.Max(r, Math.Max(g, b)); } set { this = FromHSV(h, s, value, a); } } /// <summary> /// Access color components using their index. /// </summary> /// <value> /// <c>[0]</c> is equivalent to <see cref="r"/>, /// <c>[1]</c> is equivalent to <see cref="g"/>, /// <c>[2]</c> is equivalent to <see cref="b"/>, /// <c>[3]</c> is equivalent to <see cref="a"/>. /// </value> public float this[int index] { get { switch (index) { case 0: return r; case 1: return g; case 2: return b; case 3: return a; default: throw new IndexOutOfRangeException(); } } set { switch (index) { case 0: r = value; return; case 1: g = value; return; case 2: b = value; return; case 3: a = value; return; default: throw new IndexOutOfRangeException(); } } } /// <summary> /// Returns a new color resulting from blending this color over another. /// If the color is opaque, the result is also opaque. /// The second color may have a range of alpha values. /// </summary> /// <param name="over">The color to blend over.</param> /// <returns>This color blended over <paramref name="over"/>.</returns> public Color Blend(Color over) { Color res; float sa = 1.0f - over.a; res.a = (a * sa) + over.a; if (res.a == 0) { return new Color(0, 0, 0, 0); } res.r = ((r * a * sa) + (over.r * over.a)) / res.a; res.g = ((g * a * sa) + (over.g * over.a)) / res.a; res.b = ((b * a * sa) + (over.b * over.a)) / res.a; return res; } /// <summary> /// Returns a new color with all components clamped between the /// components of <paramref name="min"/> and <paramref name="max"/> /// using <see cref="Mathf.Clamp(float, float, float)"/>. /// </summary> /// <param name="min">The color with minimum allowed values.</param> /// <param name="max">The color with maximum allowed values.</param> /// <returns>The color with all components clamped.</returns> public Color Clamp(Color? min = null, Color? max = null) { Color minimum = min ?? new Color(0, 0, 0, 0); Color maximum = max ?? new Color(1, 1, 1, 1); return new Color ( (float)Mathf.Clamp(r, minimum.r, maximum.r), (float)Mathf.Clamp(g, minimum.g, maximum.g), (float)Mathf.Clamp(b, minimum.b, maximum.b), (float)Mathf.Clamp(a, minimum.a, maximum.a) ); } /// <summary> /// Returns a new color resulting from making this color darker /// by the specified ratio (on the range of 0 to 1). /// </summary> /// <param name="amount">The ratio to darken by.</param> /// <returns>The darkened color.</returns> public Color Darkened(float amount) { Color res = this; res.r *= 1.0f - amount; res.g *= 1.0f - amount; res.b *= 1.0f - amount; return res; } /// <summary> /// Returns the inverted color: <c>(1 - r, 1 - g, 1 - b, a)</c>. /// </summary> /// <returns>The inverted color.</returns> public Color Inverted() { return new Color( 1.0f - r, 1.0f - g, 1.0f - b, a ); } /// <summary> /// Returns a new color resulting from making this color lighter /// by the specified ratio (on the range of 0 to 1). /// </summary> /// <param name="amount">The ratio to lighten by.</param> /// <returns>The darkened color.</returns> public Color Lightened(float amount) { Color res = this; res.r += (1.0f - res.r) * amount; res.g += (1.0f - res.g) * amount; res.b += (1.0f - res.b) * amount; return res; } /// <summary> /// Returns the result of the linear interpolation between /// this color and <paramref name="to"/> by amount <paramref name="weight"/>. /// </summary> /// <param name="to">The destination color for interpolation.</param> /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param> /// <returns>The resulting color of the interpolation.</returns> public Color Lerp(Color to, float weight) { return new Color ( Mathf.Lerp(r, to.r, weight), Mathf.Lerp(g, to.g, weight), Mathf.Lerp(b, to.b, weight), Mathf.Lerp(a, to.a, weight) ); } /// <summary> /// Returns the result of the linear interpolation between /// this color and <paramref name="to"/> by color amount <paramref name="weight"/>. /// </summary> /// <param name="to">The destination color for interpolation.</param> /// <param name="weight">A color with components on the range of 0.0 to 1.0, representing the amount of interpolation.</param> /// <returns>The resulting color of the interpolation.</returns> public Color Lerp(Color to, Color weight) { return new Color ( Mathf.Lerp(r, to.r, weight.r), Mathf.Lerp(g, to.g, weight.g), Mathf.Lerp(b, to.b, weight.b), Mathf.Lerp(a, to.a, weight.a) ); } /// <summary> /// Returns the color converted to an unsigned 32-bit integer in ABGR /// format (each byte represents a color channel). /// ABGR is the reversed version of the default format. /// </summary> /// <returns>A <see langword="uint"/> representing this color in ABGR32 format.</returns> public uint ToAbgr32() { uint c = (byte)Math.Round(a * 255); c <<= 8; c |= (byte)Math.Round(b * 255); c <<= 8; c |= (byte)Math.Round(g * 255); c <<= 8; c |= (byte)Math.Round(r * 255); return c; } /// <summary> /// Returns the color converted to an unsigned 64-bit integer in ABGR /// format (each word represents a color channel). /// ABGR is the reversed version of the default format. /// </summary> /// <returns>A <see langword="ulong"/> representing this color in ABGR64 format.</returns> public ulong ToAbgr64() { ulong c = (ushort)Math.Round(a * 65535); c <<= 16; c |= (ushort)Math.Round(b * 65535); c <<= 16; c |= (ushort)Math.Round(g * 65535); c <<= 16; c |= (ushort)Math.Round(r * 65535); return c; } /// <summary> /// Returns the color converted to an unsigned 32-bit integer in ARGB /// format (each byte represents a color channel). /// ARGB is more compatible with DirectX, but not used much in Godot. /// </summary> /// <returns>A <see langword="uint"/> representing this color in ARGB32 format.</returns> public uint ToArgb32() { uint c = (byte)Math.Round(a * 255); c <<= 8; c |= (byte)Math.Round(r * 255); c <<= 8; c |= (byte)Math.Round(g * 255); c <<= 8; c |= (byte)Math.Round(b * 255); return c; } /// <summary> /// Returns the color converted to an unsigned 64-bit integer in ARGB /// format (each word represents a color channel). /// ARGB is more compatible with DirectX, but not used much in Godot. /// </summary> /// <returns>A <see langword="ulong"/> representing this color in ARGB64 format.</returns> public ulong ToArgb64() { ulong c = (ushort)Math.Round(a * 65535); c <<= 16; c |= (ushort)Math.Round(r * 65535); c <<= 16; c |= (ushort)Math.Round(g * 65535); c <<= 16; c |= (ushort)Math.Round(b * 65535); return c; } /// <summary> /// Returns the color converted to an unsigned 32-bit integer in RGBA /// format (each byte represents a color channel). /// RGBA is Godot's default and recommended format. /// </summary> /// <returns>A <see langword="uint"/> representing this color in RGBA32 format.</returns> public uint ToRgba32() { uint c = (byte)Math.Round(r * 255); c <<= 8; c |= (byte)Math.Round(g * 255); c <<= 8; c |= (byte)Math.Round(b * 255); c <<= 8; c |= (byte)Math.Round(a * 255); return c; } /// <summary> /// Returns the color converted to an unsigned 64-bit integer in RGBA /// format (each word represents a color channel). /// RGBA is Godot's default and recommended format. /// </summary> /// <returns>A <see langword="ulong"/> representing this color in RGBA64 format.</returns> public ulong ToRgba64() { ulong c = (ushort)Math.Round(r * 65535); c <<= 16; c |= (ushort)Math.Round(g * 65535); c <<= 16; c |= (ushort)Math.Round(b * 65535); c <<= 16; c |= (ushort)Math.Round(a * 65535); return c; } /// <summary> /// Returns the color's HTML hexadecimal color string in RGBA format. /// </summary> /// <param name="includeAlpha"> /// Whether or not to include alpha. If <see langword="false"/>, the color is RGB instead of RGBA. /// </param> /// <returns>A string for the HTML hexadecimal representation of this color.</returns> public string ToHTML(bool includeAlpha = true) { string txt = string.Empty; txt += ToHex32(r); txt += ToHex32(g); txt += ToHex32(b); if (includeAlpha) { txt += ToHex32(a); } return txt; } /// <summary> /// Constructs a <see cref="Color"/> from RGBA values, typically on the range of 0 to 1. /// </summary> /// <param name="r">The color's red component, typically on the range of 0 to 1.</param> /// <param name="g">The color's green component, typically on the range of 0 to 1.</param> /// <param name="b">The color's blue component, typically on the range of 0 to 1.</param> /// <param name="a">The color's alpha (transparency) value, typically on the range of 0 to 1. Default: 1.</param> public Color(float r, float g, float b, float a = 1.0f) { this.r = r; this.g = g; this.b = b; this.a = a; } /// <summary> /// Constructs a <see cref="Color"/> from an existing color and an alpha value. /// </summary> /// <param name="c">The color to construct from. Only its RGB values are used.</param> /// <param name="a">The color's alpha (transparency) value, typically on the range of 0 to 1. Default: 1.</param> public Color(Color c, float a = 1.0f) { r = c.r; g = c.g; b = c.b; this.a = a; } /// <summary> /// Constructs a <see cref="Color"/> from an unsigned 32-bit integer in RGBA format /// (each byte represents a color channel). /// </summary> /// <param name="rgba">The <see langword="uint"/> representing the color.</param> public Color(uint rgba) { a = (rgba & 0xFF) / 255.0f; rgba >>= 8; b = (rgba & 0xFF) / 255.0f; rgba >>= 8; g = (rgba & 0xFF) / 255.0f; rgba >>= 8; r = (rgba & 0xFF) / 255.0f; } /// <summary> /// Constructs a <see cref="Color"/> from an unsigned 64-bit integer in RGBA format /// (each word represents a color channel). /// </summary> /// <param name="rgba">The <see langword="ulong"/> representing the color.</param> public Color(ulong rgba) { a = (rgba & 0xFFFF) / 65535.0f; rgba >>= 16; b = (rgba & 0xFFFF) / 65535.0f; rgba >>= 16; g = (rgba & 0xFFFF) / 65535.0f; rgba >>= 16; r = (rgba & 0xFFFF) / 65535.0f; } /// <summary> /// Constructs a <see cref="Color"/> either from an HTML color code or from a /// standardized color name. Supported color names are the same as the /// <see cref="Colors"/> constants. /// </summary> /// <param name="code">The HTML color code or color name to construct from.</param> public Color(string code) { if (HtmlIsValid(code)) { this = FromHTML(code); } else { this = Named(code); } } /// <summary> /// Constructs a <see cref="Color"/> either from an HTML color code or from a /// standardized color name, with <paramref name="alpha"/> on the range of 0 to 1. Supported /// color names are the same as the <see cref="Colors"/> constants. /// </summary> /// <param name="code">The HTML color code or color name to construct from.</param> /// <param name="alpha">The alpha (transparency) value, typically on the range of 0 to 1.</param> public Color(string code, float alpha) { this = new Color(code); a = alpha; } /// <summary> /// Constructs a <see cref="Color"/> from the HTML hexadecimal color string in RGBA format. /// </summary> /// <param name="rgba">A string for the HTML hexadecimal representation of this color.</param> /// <exception name="ArgumentOutOfRangeException"> /// Thrown when the given <paramref name="rgba"/> color code is invalid. /// </exception> private static Color FromHTML(string rgba) { Color c; if (rgba.Length == 0) { c.r = 0f; c.g = 0f; c.b = 0f; c.a = 1.0f; return c; } if (rgba[0] == '#') { rgba = rgba.Substring(1); } // If enabled, use 1 hex digit per channel instead of 2. // Other sizes aren't in the HTML/CSS spec but we could add them if desired. bool isShorthand = rgba.Length < 5; bool alpha; if (rgba.Length == 8) { alpha = true; } else if (rgba.Length == 6) { alpha = false; } else if (rgba.Length == 4) { alpha = true; } else if (rgba.Length == 3) { alpha = false; } else { throw new ArgumentOutOfRangeException( $"Invalid color code. Length is {rgba.Length}, but a length of 6 or 8 is expected: {rgba}"); } c.a = 1.0f; if (isShorthand) { c.r = ParseCol4(rgba, 0) / 15f; c.g = ParseCol4(rgba, 1) / 15f; c.b = ParseCol4(rgba, 2) / 15f; if (alpha) { c.a = ParseCol4(rgba, 3) / 15f; } } else { c.r = ParseCol8(rgba, 0) / 255f; c.g = ParseCol8(rgba, 2) / 255f; c.b = ParseCol8(rgba, 4) / 255f; if (alpha) { c.a = ParseCol8(rgba, 6) / 255f; } } if (c.r < 0) { throw new ArgumentOutOfRangeException("Invalid color code. Red part is not valid hexadecimal: " + rgba); } if (c.g < 0) { throw new ArgumentOutOfRangeException("Invalid color code. Green part is not valid hexadecimal: " + rgba); } if (c.b < 0) { throw new ArgumentOutOfRangeException("Invalid color code. Blue part is not valid hexadecimal: " + rgba); } if (c.a < 0) { throw new ArgumentOutOfRangeException("Invalid color code. Alpha part is not valid hexadecimal: " + rgba); } return c; } /// <summary> /// Returns a color constructed from integer red, green, blue, and alpha channels. /// Each channel should have 8 bits of information ranging from 0 to 255. /// </summary> /// <param name="r8">The red component represented on the range of 0 to 255.</param> /// <param name="g8">The green component represented on the range of 0 to 255.</param> /// <param name="b8">The blue component represented on the range of 0 to 255.</param> /// <param name="a8">The alpha (transparency) component represented on the range of 0 to 255.</param> /// <returns>The constructed color.</returns> public static Color Color8(byte r8, byte g8, byte b8, byte a8 = 255) { return new Color(r8 / 255f, g8 / 255f, b8 / 255f, a8 / 255f); } /// <summary> /// Returns a color according to the standardized name, with the /// specified alpha value. Supported color names are the same as /// the constants defined in <see cref="Colors"/>. /// </summary> /// <param name="name">The name of the color.</param> /// <returns>The constructed color.</returns> private static Color Named(string name) { name = name.Replace(" ", string.Empty); name = name.Replace("-", string.Empty); name = name.Replace("_", string.Empty); name = name.Replace("'", string.Empty); name = name.Replace(".", string.Empty); name = name.ToUpper(); if (!Colors.namedColors.ContainsKey(name)) { throw new ArgumentOutOfRangeException($"Invalid Color Name: {name}"); } return Colors.namedColors[name]; } /// <summary> /// Constructs a color from an HSV profile, with values on the /// range of 0 to 1. This is equivalent to using each of /// the <c>h</c>/<c>s</c>/<c>v</c> properties, but much more efficient. /// </summary> /// <param name="hue">The HSV hue, typically on the range of 0 to 1.</param> /// <param name="saturation">The HSV saturation, typically on the range of 0 to 1.</param> /// <param name="value">The HSV value (brightness), typically on the range of 0 to 1.</param> /// <param name="alpha">The alpha (transparency) value, typically on the range of 0 to 1.</param> /// <returns>The constructed color.</returns> public static Color FromHSV(float hue, float saturation, float value, float alpha = 1.0f) { if (saturation == 0) { // Achromatic (grey) return new Color(value, value, value, alpha); } int i; float f, p, q, t; hue *= 6.0f; hue %= 6f; i = (int)hue; f = hue - i; p = value * (1 - saturation); q = value * (1 - (saturation * f)); t = value * (1 - (saturation * (1 - f))); switch (i) { case 0: // Red is the dominant color return new Color(value, t, p, alpha); case 1: // Green is the dominant color return new Color(q, value, p, alpha); case 2: return new Color(p, value, t, alpha); case 3: // Blue is the dominant color return new Color(p, q, value, alpha); case 4: return new Color(t, p, value, alpha); default: // (5) Red is the dominant color return new Color(value, p, q, alpha); } } /// <summary> /// Converts a color to HSV values. This is equivalent to using each of /// the <c>h</c>/<c>s</c>/<c>v</c> properties, but much more efficient. /// </summary> /// <param name="hue">Output parameter for the HSV hue.</param> /// <param name="saturation">Output parameter for the HSV saturation.</param> /// <param name="value">Output parameter for the HSV value.</param> public void ToHSV(out float hue, out float saturation, out float value) { float max = (float)Mathf.Max(r, Mathf.Max(g, b)); float min = (float)Mathf.Min(r, Mathf.Min(g, b)); float delta = max - min; if (delta == 0) { hue = 0; } else { if (r == max) { hue = (g - b) / delta; // Between yellow & magenta } else if (g == max) { hue = 2 + ((b - r) / delta); // Between cyan & yellow } else { hue = 4 + ((r - g) / delta); // Between magenta & cyan } hue /= 6.0f; if (hue < 0) hue += 1.0f; } if (max == 0) saturation = 0; else saturation = 1 - (min / max); value = max; } private static int ParseCol4(string str, int ofs) { char character = str[ofs]; if (character >= '0' && character <= '9') { return character - '0'; } else if (character >= 'a' && character <= 'f') { return character + (10 - 'a'); } else if (character >= 'A' && character <= 'F') { return character + (10 - 'A'); } return -1; } private static int ParseCol8(string str, int ofs) { return ParseCol4(str, ofs) * 16 + ParseCol4(str, ofs + 1); } private string ToHex32(float val) { byte b = (byte)Mathf.RoundToInt(Mathf.Clamp(val * 255, 0, 255)); return b.HexEncode(); } internal static bool HtmlIsValid(string color) { if (color.Length == 0) { return false; } if (color[0] == '#') { color = color.Substring(1); } // Check if the amount of hex digits is valid. int len = color.Length; if (!(len == 3 || len == 4 || len == 6 || len == 8)) { return false; } // Check if each hex digit is valid. for (int i = 0; i < len; i++) { if (ParseCol4(color, i) == -1) { return false; } } return true; } public static Color operator +(Color left, Color right) { left.r += right.r; left.g += right.g; left.b += right.b; left.a += right.a; return left; } public static Color operator -(Color left, Color right) { left.r -= right.r; left.g -= right.g; left.b -= right.b; left.a -= right.a; return left; } public static Color operator -(Color color) { return Colors.White - color; } public static Color operator *(Color color, float scale) { color.r *= scale; color.g *= scale; color.b *= scale; color.a *= scale; return color; } public static Color operator *(float scale, Color color) { color.r *= scale; color.g *= scale; color.b *= scale; color.a *= scale; return color; } public static Color operator *(Color left, Color right) { left.r *= right.r; left.g *= right.g; left.b *= right.b; left.a *= right.a; return left; } public static Color operator /(Color color, float scale) { color.r /= scale; color.g /= scale; color.b /= scale; color.a /= scale; return color; } public static Color operator /(Color left, Color right) { left.r /= right.r; left.g /= right.g; left.b /= right.b; left.a /= right.a; return left; } public static bool operator ==(Color left, Color right) { return left.Equals(right); } public static bool operator !=(Color left, Color right) { return !left.Equals(right); } public static bool operator <(Color left, Color right) { if (Mathf.IsEqualApprox(left.r, right.r)) { if (Mathf.IsEqualApprox(left.g, right.g)) { if (Mathf.IsEqualApprox(left.b, right.b)) { return left.a < right.a; } return left.b < right.b; } return left.g < right.g; } return left.r < right.r; } public static bool operator >(Color left, Color right) { if (Mathf.IsEqualApprox(left.r, right.r)) { if (Mathf.IsEqualApprox(left.g, right.g)) { if (Mathf.IsEqualApprox(left.b, right.b)) { return left.a > right.a; } return left.b > right.b; } return left.g > right.g; } return left.r > right.r; } /// <summary> /// Returns <see langword="true"/> if this color and <paramref name="obj"/> are equal. /// </summary> /// <param name="obj">The other object to compare.</param> /// <returns>Whether or not the color and the other object are equal.</returns> public override bool Equals(object obj) { if (obj is Color) { return Equals((Color)obj); } return false; } /// <summary> /// Returns <see langword="true"/> if this color and <paramref name="other"/> are equal /// </summary> /// <param name="other">The other color to compare.</param> /// <returns>Whether or not the colors are equal.</returns> public bool Equals(Color other) { return r == other.r && g == other.g && b == other.b && a == other.a; } /// <summary> /// Returns <see langword="true"/> if this color and <paramref name="other"/> are approximately equal, /// by running <see cref="Mathf.IsEqualApprox(float, float)"/> on each component. /// </summary> /// <param name="other">The other color to compare.</param> /// <returns>Whether or not the colors are approximately equal.</returns> public bool IsEqualApprox(Color other) { return Mathf.IsEqualApprox(r, other.r) && Mathf.IsEqualApprox(g, other.g) && Mathf.IsEqualApprox(b, other.b) && Mathf.IsEqualApprox(a, other.a); } /// <summary> /// Serves as the hash function for <see cref="Color"/>. /// </summary> /// <returns>A hash code for this color.</returns> public override int GetHashCode() { return r.GetHashCode() ^ g.GetHashCode() ^ b.GetHashCode() ^ a.GetHashCode(); } /// <summary> /// Converts this <see cref="Color"/> to a string. /// </summary> /// <returns>A string representation of this color.</returns> public override string ToString() { return $"({r}, {g}, {b}, {a})"; } /// <summary> /// Converts this <see cref="Color"/> to a string with the given <paramref name="format"/>. /// </summary> /// <returns>A string representation of this color.</returns> public string ToString(string format) { return $"({r.ToString(format)}, {g.ToString(format)}, {b.ToString(format)}, {a.ToString(format)})"; } } }
namespace System.Workflow.ComponentModel.Compiler { using System; using System.Collections.Generic; using System.Reflection; using System.Workflow.ComponentModel.Design; using System.Workflow.ComponentModel.Serialization; using System.ComponentModel.Design; using System.Diagnostics.CodeAnalysis; #region Class BindValidator internal static class BindValidatorHelper { internal static Type GetActivityType(IServiceProvider serviceProvider, Activity refActivity) { Type type = null; string typeName = refActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string; if (refActivity.Site != null && !string.IsNullOrEmpty(typeName)) { ITypeProvider typeProvider = serviceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider; if (typeProvider != null && !string.IsNullOrEmpty(typeName)) type = typeProvider.GetType(typeName, false); } else { type = refActivity.GetType(); } return type; } } #endregion #region Class FieldBindValidator internal sealed class FieldBindValidator : Validator { public override ValidationErrorCollection Validate(ValidationManager manager, object obj) { ValidationErrorCollection validationErrors = base.Validate(manager, obj); FieldBind bind = obj as FieldBind; if (bind == null) throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(FieldBind).FullName), "obj"); PropertyValidationContext validationContext = manager.Context[typeof(PropertyValidationContext)] as PropertyValidationContext; if (validationContext == null) throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(BindValidationContext).Name)); Activity activity = manager.Context[typeof(Activity)] as Activity; if (activity == null) throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(Activity).Name)); ValidationError error = null; if (string.IsNullOrEmpty(bind.Name)) { error = new ValidationError(SR.GetString(SR.Error_PropertyNotSet, "Name"), ErrorNumbers.Error_PropertyNotSet); error.PropertyName = GetFullPropertyName(manager) + ".Name"; } else { BindValidationContext validationBindContext = manager.Context[typeof(BindValidationContext)] as BindValidationContext; if (validationBindContext == null) { Type baseType = BindHelpers.GetBaseType(manager, validationContext); if (baseType != null) { AccessTypes accessType = BindHelpers.GetAccessType(manager, validationContext); validationBindContext = new BindValidationContext(baseType, accessType); } //else //{ // error = new ValidationError(SR.GetString(SR.Error_BindBaseTypeNotSpecified, validationContext.PropertyName), ErrorNumbers.Error_BindBaseTypeNotSpecified); // error.PropertyName = GetFullPropertyName(manager) + ".Name"; //} } if (validationBindContext != null) { Type targetType = validationBindContext.TargetType; if (error == null) validationErrors.AddRange(this.ValidateField(manager, activity, bind, new BindValidationContext(targetType, validationBindContext.Access))); } } if (error != null) validationErrors.Add(error); return validationErrors; } private ValidationErrorCollection ValidateField(ValidationManager manager, Activity activity, FieldBind bind, BindValidationContext validationContext) { ValidationErrorCollection validationErrors = new ValidationErrorCollection(); string dsName = bind.Name; Activity activityContext = Helpers.GetEnclosingActivity(activity); Activity dataSourceActivity = activityContext; if (dsName.IndexOf('.') != -1 && dataSourceActivity != null) dataSourceActivity = Helpers.GetDataSourceActivity(activity, bind.Name, out dsName); if (dataSourceActivity == null) { ValidationError error = new ValidationError(SR.GetString(SR.Error_NoEnclosingContext, activity.Name), ErrorNumbers.Error_NoEnclosingContext); error.PropertyName = GetFullPropertyName(manager) + ".Name"; validationErrors.Add(error); } else { ValidationError error = null; // System.Type resolvedType = Helpers.GetDataSourceClass(dataSourceActivity, manager); if (resolvedType == null) { error = new ValidationError(SR.GetString(SR.Error_TypeNotResolvedInFieldName, "Name"), ErrorNumbers.Error_TypeNotResolvedInFieldName); error.PropertyName = GetFullPropertyName(manager); } else { FieldInfo fieldInfo = resolvedType.GetField(dsName, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy); if (fieldInfo == null) { error = new ValidationError(SR.GetString(SR.Error_FieldNotExists, GetFullPropertyName(manager), dsName), ErrorNumbers.Error_FieldNotExists); error.PropertyName = GetFullPropertyName(manager); } //else if (dataSourceActivity != activityContext && !fieldInfo.IsAssembly && !fieldInfo.IsPublic) //{ // error = new ValidationError(SR.GetString(SR.Error_FieldNotAccessible, GetFullPropertyName(manager), dsName), ErrorNumbers.Error_FieldNotAccessible); // error.PropertyName = GetFullPropertyName(manager); //} else if (fieldInfo.FieldType == null) { error = new ValidationError(SR.GetString(SR.Error_FieldTypeNotResolved, GetFullPropertyName(manager), dsName), ErrorNumbers.Error_FieldTypeNotResolved); error.PropertyName = GetFullPropertyName(manager); } else { MemberInfo memberInfo = fieldInfo; if ((bind.Path == null || bind.Path.Length == 0) && (validationContext.TargetType != null && !ActivityBindValidator.DoesTargetTypeMatch(validationContext.TargetType, fieldInfo.FieldType, validationContext.Access))) { error = new ValidationError(SR.GetString(SR.Error_FieldTypeMismatch, GetFullPropertyName(manager), fieldInfo.FieldType.FullName, validationContext.TargetType.FullName), ErrorNumbers.Error_FieldTypeMismatch); error.PropertyName = GetFullPropertyName(manager); } else if (!string.IsNullOrEmpty(bind.Path)) { memberInfo = MemberBind.GetMemberInfo(fieldInfo.FieldType, bind.Path); if (memberInfo == null) { error = new ValidationError(SR.GetString(SR.Error_InvalidMemberPath, dsName, bind.Path), ErrorNumbers.Error_InvalidMemberPath); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } else { IDisposable localContextScope = (WorkflowCompilationContext.Current == null ? WorkflowCompilationContext.CreateScope(manager) : null); try { if (WorkflowCompilationContext.Current.CheckTypes) { error = MemberBind.ValidateTypesInPath(fieldInfo.FieldType, bind.Path); if (error != null) error.PropertyName = GetFullPropertyName(manager) + ".Path"; } } finally { if (localContextScope != null) { localContextScope.Dispose(); } } if (error == null) { Type memberType = (memberInfo is FieldInfo ? (memberInfo as FieldInfo).FieldType : (memberInfo as PropertyInfo).PropertyType); if (!ActivityBindValidator.DoesTargetTypeMatch(validationContext.TargetType, memberType, validationContext.Access)) { error = new ValidationError(SR.GetString(SR.Error_TargetTypeDataSourcePathMismatch, validationContext.TargetType.FullName), ErrorNumbers.Error_TargetTypeDataSourcePathMismatch); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } } } } if (error == null) { if (memberInfo is PropertyInfo) { PropertyInfo pathPropertyInfo = memberInfo as PropertyInfo; if (!pathPropertyInfo.CanRead && ((validationContext.Access & AccessTypes.Read) != 0)) { error = new ValidationError(SR.GetString(SR.Error_PropertyNoGetter, pathPropertyInfo.Name, bind.Path), ErrorNumbers.Error_PropertyNoGetter); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } else if (!pathPropertyInfo.CanWrite && ((validationContext.Access & AccessTypes.Write) != 0)) { error = new ValidationError(SR.GetString(SR.Error_PropertyNoSetter, pathPropertyInfo.Name, bind.Path), ErrorNumbers.Error_PropertyNoSetter); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } } else if (memberInfo is FieldInfo) { FieldInfo pathFieldInfo = memberInfo as FieldInfo; if (((pathFieldInfo.Attributes & (FieldAttributes.InitOnly | FieldAttributes.Literal)) != 0) && ((validationContext.Access & AccessTypes.Write) != 0)) { error = new ValidationError(SR.GetString(SR.Error_ReadOnlyField, pathFieldInfo.Name), ErrorNumbers.Error_ReadOnlyField); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } } } } } if (error != null) validationErrors.Add(error); } return validationErrors; } } #endregion #region Class PropertyBindValidator internal sealed class PropertyBindValidator : Validator { public override ValidationErrorCollection Validate(ValidationManager manager, object obj) { ValidationErrorCollection validationErrors = base.Validate(manager, obj); PropertyBind bind = obj as PropertyBind; if (bind == null) throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(PropertyBind).FullName), "obj"); PropertyValidationContext validationContext = manager.Context[typeof(PropertyValidationContext)] as PropertyValidationContext; if (validationContext == null) throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(BindValidationContext).Name)); Activity activity = manager.Context[typeof(Activity)] as Activity; if (activity == null) throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(Activity).Name)); ValidationError error = null; if (string.IsNullOrEmpty(bind.Name)) { error = new ValidationError(SR.GetString(SR.Error_PropertyNotSet, "Name"), ErrorNumbers.Error_PropertyNotSet); error.PropertyName = GetFullPropertyName(manager) + ".Name"; } else { BindValidationContext validationBindContext = manager.Context[typeof(BindValidationContext)] as BindValidationContext; if (validationBindContext == null) { Type baseType = BindHelpers.GetBaseType(manager, validationContext); if (baseType != null) { AccessTypes accessType = BindHelpers.GetAccessType(manager, validationContext); validationBindContext = new BindValidationContext(baseType, accessType); } } if (validationBindContext != null) { Type targetType = validationBindContext.TargetType; if (error == null) validationErrors.AddRange(this.ValidateBindProperty(manager, activity, bind, new BindValidationContext(targetType, validationBindContext.Access))); } } if (error != null) validationErrors.Add(error); return validationErrors; } private ValidationErrorCollection ValidateBindProperty(ValidationManager manager, Activity activity, PropertyBind bind, BindValidationContext validationContext) { ValidationErrorCollection validationErrors = new ValidationErrorCollection(); string dsName = bind.Name; Activity activityContext = Helpers.GetEnclosingActivity(activity); Activity dataSourceActivity = activityContext; if (dsName.IndexOf('.') != -1 && dataSourceActivity != null) dataSourceActivity = Helpers.GetDataSourceActivity(activity, bind.Name, out dsName); if (dataSourceActivity == null) { ValidationError error = new ValidationError(SR.GetString(SR.Error_NoEnclosingContext, activity.Name), ErrorNumbers.Error_NoEnclosingContext); error.PropertyName = GetFullPropertyName(manager) + ".Name"; validationErrors.Add(error); } else { ValidationError error = null; PropertyInfo propertyInfo = null; System.Type resolvedType = null; if (propertyInfo == null) { resolvedType = BindValidatorHelper.GetActivityType(manager, dataSourceActivity); if (resolvedType != null) propertyInfo = resolvedType.GetProperty(dsName, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); } if (resolvedType == null) { error = new ValidationError(SR.GetString(SR.Error_TypeNotResolvedInPropertyName, "Name"), ErrorNumbers.Error_TypeNotResolvedInPropertyName); error.PropertyName = GetFullPropertyName(manager); } else { if (propertyInfo == null) { error = new ValidationError(SR.GetString(SR.Error_PropertyNotExists, GetFullPropertyName(manager), dsName), ErrorNumbers.Error_PropertyNotExists); error.PropertyName = GetFullPropertyName(manager); } else if (!propertyInfo.CanRead) { error = new ValidationError(SR.GetString(SR.Error_PropertyReferenceNoGetter, GetFullPropertyName(manager), dsName), ErrorNumbers.Error_PropertyReferenceNoGetter); error.PropertyName = GetFullPropertyName(manager); } else if (propertyInfo.GetGetMethod() == null) { error = new ValidationError(SR.GetString(SR.Error_PropertyReferenceGetterNoAccess, GetFullPropertyName(manager), dsName), ErrorNumbers.Error_PropertyReferenceGetterNoAccess); error.PropertyName = GetFullPropertyName(manager); } else if (dataSourceActivity != activityContext && !propertyInfo.GetGetMethod().IsAssembly && !propertyInfo.GetGetMethod().IsPublic) { error = new ValidationError(SR.GetString(SR.Error_PropertyNotAccessible, GetFullPropertyName(manager), dsName), ErrorNumbers.Error_PropertyNotAccessible); error.PropertyName = GetFullPropertyName(manager); } else if (propertyInfo.PropertyType == null) { error = new ValidationError(SR.GetString(SR.Error_PropertyTypeNotResolved, GetFullPropertyName(manager), dsName), ErrorNumbers.Error_PropertyTypeNotResolved); error.PropertyName = GetFullPropertyName(manager); } else { MemberInfo memberInfo = propertyInfo; if ((bind.Path == null || bind.Path.Length == 0) && (validationContext.TargetType != null && !ActivityBindValidator.DoesTargetTypeMatch(validationContext.TargetType, propertyInfo.PropertyType, validationContext.Access))) { error = new ValidationError(SR.GetString(SR.Error_PropertyTypeMismatch, GetFullPropertyName(manager), propertyInfo.PropertyType.FullName, validationContext.TargetType.FullName), ErrorNumbers.Error_PropertyTypeMismatch); error.PropertyName = GetFullPropertyName(manager); } else if (!string.IsNullOrEmpty(bind.Path)) { memberInfo = MemberBind.GetMemberInfo(propertyInfo.PropertyType, bind.Path); if (memberInfo == null) { error = new ValidationError(SR.GetString(SR.Error_InvalidMemberPath, dsName, bind.Path), ErrorNumbers.Error_InvalidMemberPath); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } else { IDisposable localContextScope = (WorkflowCompilationContext.Current == null ? WorkflowCompilationContext.CreateScope(manager) : null); try { if (WorkflowCompilationContext.Current.CheckTypes) { error = MemberBind.ValidateTypesInPath(propertyInfo.PropertyType, bind.Path); if (error != null) error.PropertyName = GetFullPropertyName(manager) + ".Path"; } } finally { if (localContextScope != null) { localContextScope.Dispose(); } } if (error == null) { Type memberType = (memberInfo is FieldInfo ? (memberInfo as FieldInfo).FieldType : (memberInfo as PropertyInfo).PropertyType); if (!ActivityBindValidator.DoesTargetTypeMatch(validationContext.TargetType, memberType, validationContext.Access)) { error = new ValidationError(SR.GetString(SR.Error_TargetTypeDataSourcePathMismatch, validationContext.TargetType.FullName), ErrorNumbers.Error_TargetTypeDataSourcePathMismatch); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } } } } if (error == null) { if (memberInfo is PropertyInfo) { PropertyInfo pathPropertyInfo = memberInfo as PropertyInfo; if (!pathPropertyInfo.CanRead && ((validationContext.Access & AccessTypes.Read) != 0)) { error = new ValidationError(SR.GetString(SR.Error_PropertyNoGetter, pathPropertyInfo.Name, bind.Path), ErrorNumbers.Error_PropertyNoGetter); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } else if (!pathPropertyInfo.CanWrite && ((validationContext.Access & AccessTypes.Write) != 0)) { error = new ValidationError(SR.GetString(SR.Error_PropertyNoSetter, pathPropertyInfo.Name, bind.Path), ErrorNumbers.Error_PropertyNoSetter); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } } else if (memberInfo is FieldInfo) { FieldInfo pathFieldInfo = memberInfo as FieldInfo; if (((pathFieldInfo.Attributes & (FieldAttributes.InitOnly | FieldAttributes.Literal)) != 0) && ((validationContext.Access & AccessTypes.Write) != 0)) { error = new ValidationError(SR.GetString(SR.Error_ReadOnlyField, pathFieldInfo.Name), ErrorNumbers.Error_ReadOnlyField); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } } } } } if (error != null) validationErrors.Add(error); } return validationErrors; } } #endregion #region Class MethodBindValidator internal sealed class MethodBindValidator : Validator { public override ValidationErrorCollection Validate(ValidationManager manager, object obj) { ValidationErrorCollection validationErrors = base.Validate(manager, obj); MethodBind bind = obj as MethodBind; if (bind == null) throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(MethodBind).FullName), "obj"); PropertyValidationContext validationContext = manager.Context[typeof(PropertyValidationContext)] as PropertyValidationContext; if (validationContext == null) throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(BindValidationContext).Name)); Activity activity = manager.Context[typeof(Activity)] as Activity; if (activity == null) throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(Activity).Name)); ValidationError error = null; if (string.IsNullOrEmpty(bind.Name)) { error = new ValidationError(SR.GetString(SR.Error_PropertyNotSet, "Name"), ErrorNumbers.Error_PropertyNotSet); error.PropertyName = GetFullPropertyName(manager) + ".Name"; } else { BindValidationContext validationBindContext = manager.Context[typeof(BindValidationContext)] as BindValidationContext; if (validationBindContext == null) { Type baseType = BindHelpers.GetBaseType(manager, validationContext); if (baseType != null) { AccessTypes accessType = BindHelpers.GetAccessType(manager, validationContext); validationBindContext = new BindValidationContext(baseType, accessType); } //else //{ // error = new ValidationError(SR.GetString(SR.Error_BindBaseTypeNotSpecified, validationContext.PropertyName), ErrorNumbers.Error_BindBaseTypeNotSpecified); // error.PropertyName = GetFullPropertyName(manager) + ".Name"; //} } if (validationBindContext != null) { Type targetType = validationBindContext.TargetType; if (error == null) validationErrors.AddRange(this.ValidateMethod(manager, activity, bind, new BindValidationContext(targetType, validationBindContext.Access))); } } if (error != null) validationErrors.Add(error); return validationErrors; } private ValidationErrorCollection ValidateMethod(ValidationManager manager, Activity activity, MethodBind bind, BindValidationContext validationBindContext) { ValidationErrorCollection validationErrors = new ValidationErrorCollection(); if ((validationBindContext.Access & AccessTypes.Write) != 0) { ValidationError error = new ValidationError(SR.GetString(SR.Error_HandlerReadOnly), ErrorNumbers.Error_HandlerReadOnly); error.PropertyName = GetFullPropertyName(manager); validationErrors.Add(error); } else { if (!TypeProvider.IsAssignable(typeof(Delegate), validationBindContext.TargetType)) { ValidationError error = new ValidationError(SR.GetString(SR.Error_TypeNotDelegate, validationBindContext.TargetType.FullName), ErrorNumbers.Error_TypeNotDelegate); error.PropertyName = GetFullPropertyName(manager); validationErrors.Add(error); } else { string dsName = bind.Name; Activity activityContext = Helpers.GetEnclosingActivity(activity); Activity dataSourceActivity = activityContext; if (dsName.IndexOf('.') != -1 && dataSourceActivity != null) dataSourceActivity = Helpers.GetDataSourceActivity(activity, bind.Name, out dsName); if (dataSourceActivity == null) { ValidationError error = new ValidationError(SR.GetString(SR.Error_NoEnclosingContext, activity.Name), ErrorNumbers.Error_NoEnclosingContext); error.PropertyName = GetFullPropertyName(manager) + ".Name"; validationErrors.Add(error); } else { string message = string.Empty; int errorNumber = -1; System.Type resolvedType = Helpers.GetDataSourceClass(dataSourceActivity, manager); if (resolvedType == null) { message = SR.GetString(SR.Error_TypeNotResolvedInMethodName, GetFullPropertyName(manager) + ".Name"); errorNumber = ErrorNumbers.Error_TypeNotResolvedInMethodName; } else { try { ValidationHelpers.ValidateIdentifier(manager, dsName); } catch (Exception e) { validationErrors.Add(new ValidationError(e.Message, ErrorNumbers.Error_InvalidIdentifier)); } // get the invoke method MethodInfo invokeMethod = validationBindContext.TargetType.GetMethod("Invoke"); if (invokeMethod == null) throw new Exception(SR.GetString(SR.Error_DelegateNoInvoke, validationBindContext.TargetType.FullName)); // resolve the method List<Type> paramTypes = new List<Type>(); foreach (ParameterInfo paramInfo in invokeMethod.GetParameters()) paramTypes.Add(paramInfo.ParameterType); MethodInfo methodInfo = Helpers.GetMethodExactMatch(resolvedType, dsName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy, null, paramTypes.ToArray(), null); if (methodInfo == null) { if (resolvedType.GetMethod(dsName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy) != null) { message = SR.GetString(SR.Error_MethodSignatureMismatch, GetFullPropertyName(manager) + ".Name"); errorNumber = ErrorNumbers.Error_MethodSignatureMismatch; } else { message = SR.GetString(SR.Error_MethodNotExists, GetFullPropertyName(manager) + ".Name", bind.Name); errorNumber = ErrorNumbers.Error_MethodNotExists; } } // else if (!invokeMethod.ReturnType.Equals(methodInfo.ReturnType)) { message = SR.GetString(SR.Error_MethodReturnTypeMismatch, GetFullPropertyName(manager), invokeMethod.ReturnType.FullName); errorNumber = ErrorNumbers.Error_MethodReturnTypeMismatch; } } if (message.Length > 0) { ValidationError error = new ValidationError(message, errorNumber); error.PropertyName = GetFullPropertyName(manager) + ".Path"; validationErrors.Add(error); } } } } return validationErrors; } } #endregion #region Class ActivityBindValidator internal sealed class ActivityBindValidator : Validator { [SuppressMessage("Microsoft.Globalization", "CA1307:SpecifyStringComparison", Justification = "There is no security issue since this is a design time class")] public override ValidationErrorCollection Validate(ValidationManager manager, object obj) { ValidationErrorCollection validationErrors = base.Validate(manager, obj); ActivityBind bind = obj as ActivityBind; if (bind == null) throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(ActivityBind).FullName), "obj"); Activity activity = manager.Context[typeof(Activity)] as Activity; if (activity == null) throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(Activity).Name)); PropertyValidationContext validationContext = manager.Context[typeof(PropertyValidationContext)] as PropertyValidationContext; if (validationContext == null) throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(BindValidationContext).Name)); ValidationError error = null; if (string.IsNullOrEmpty(bind.Name)) { error = new ValidationError(SR.GetString(SR.Error_IDNotSetForActivitySource), ErrorNumbers.Error_IDNotSetForActivitySource); error.PropertyName = GetFullPropertyName(manager) + ".Name"; validationErrors.Add(error); } else { Activity refActivity = Helpers.ParseActivityForBind(activity, bind.Name); if (refActivity == null) { if (bind.Name.StartsWith("/")) error = new ValidationError(SR.GetString(SR.Error_CannotResolveRelativeActivity, bind.Name), ErrorNumbers.Error_CannotResolveRelativeActivity); else error = new ValidationError(SR.GetString(SR.Error_CannotResolveActivity, bind.Name), ErrorNumbers.Error_CannotResolveActivity); error.PropertyName = GetFullPropertyName(manager) + ".Name"; validationErrors.Add(error); } if (String.IsNullOrEmpty(bind.Path)) { error = new ValidationError(SR.GetString(SR.Error_PathNotSetForActivitySource), ErrorNumbers.Error_PathNotSetForActivitySource); error.PropertyName = GetFullPropertyName(manager) + ".Path"; validationErrors.Add(error); } if (refActivity != null && validationErrors.Count == 0) { string memberName = bind.Path; string path = String.Empty; int indexOfSeparator = memberName.IndexOfAny(new char[] { '.', '/', '[' }); if (indexOfSeparator != -1) { path = memberName.Substring(indexOfSeparator); path = path.StartsWith(".") ? path.Substring(1) : path; memberName = memberName.Substring(0, indexOfSeparator); } Type baseType = BindHelpers.GetBaseType(manager, validationContext); //We need to bifurcate to field, method, property or ActivityBind, we need to distinguish based on first //part of the path MemberInfo memberInfo = null; Type declaringType = null; if (!String.IsNullOrEmpty(memberName)) { declaringType = BindValidatorHelper.GetActivityType(manager, refActivity); if (declaringType != null) { memberInfo = MemberBind.GetMemberInfo(declaringType, memberName); //it could be an indexer property that requires [..] part to get correctly resolved if (memberInfo == null && path.StartsWith("[", StringComparison.Ordinal)) { string indexerPart = bind.Path.Substring(indexOfSeparator); int closingBracketIndex = indexerPart.IndexOf(']'); if (closingBracketIndex != -1) { string firstIndexerPart = indexerPart.Substring(0, closingBracketIndex + 1); //strip potential long path like Item[0].Foo path = (closingBracketIndex + 1 < indexerPart.Length) ? indexerPart.Substring(closingBracketIndex + 1) : string.Empty; path = path.StartsWith(".") ? path.Substring(1) : path; indexerPart = firstIndexerPart; } memberName = memberName + indexerPart; memberInfo = MemberBind.GetMemberInfo(declaringType, memberName); } } } Validator validator = null; object actualBind = null; //now there are two different class hierarchies - ActivityBind is not related to the BindBase/MemberBind if (memberInfo != null) { string qualifier = (!String.IsNullOrEmpty(refActivity.QualifiedName)) ? refActivity.QualifiedName : bind.Name; if (memberInfo is FieldInfo) { actualBind = new FieldBind(qualifier + "." + memberName, path); validator = new FieldBindValidator(); } else if (memberInfo is MethodInfo) { if (typeof(Delegate).IsAssignableFrom(baseType)) { actualBind = new MethodBind(qualifier + "." + memberName); validator = new MethodBindValidator(); } else { error = new ValidationError(SR.GetString(SR.Error_InvalidMemberType, memberName, GetFullPropertyName(manager)), ErrorNumbers.Error_InvalidMemberType); error.PropertyName = GetFullPropertyName(manager); validationErrors.Add(error); } } else if (memberInfo is PropertyInfo) { //Only if the referenced activity is the same it is a PropertyBind otherwise it is a ActivityBind if (refActivity == activity) { actualBind = new PropertyBind(qualifier + "." + memberName, path); validator = new PropertyBindValidator(); } else { actualBind = bind; validator = this; } } else if (memberInfo is EventInfo) { actualBind = bind; validator = this; } } else if (memberInfo == null && baseType != null && typeof(Delegate).IsAssignableFrom(baseType)) { actualBind = bind; validator = this; } if (validator != null && actualBind != null) { if (validator == this && actualBind is ActivityBind) validationErrors.AddRange(ValidateActivityBind(manager, actualBind)); else validationErrors.AddRange(validator.Validate(manager, actualBind)); } else if (error == null) { error = new ValidationError(SR.GetString(SR.Error_PathCouldNotBeResolvedToMember, bind.Path, (!string.IsNullOrEmpty(refActivity.QualifiedName)) ? refActivity.QualifiedName : refActivity.GetType().Name), ErrorNumbers.Error_PathCouldNotBeResolvedToMember); error.PropertyName = GetFullPropertyName(manager); validationErrors.Add(error); } } } return validationErrors; } internal static bool DoesTargetTypeMatch(Type baseType, Type memberType, AccessTypes access) { if ((access & AccessTypes.ReadWrite) == AccessTypes.ReadWrite) return TypeProvider.IsRepresentingTheSameType(memberType, baseType); else if ((access & AccessTypes.Read) == AccessTypes.Read) return TypeProvider.IsAssignable(baseType, memberType, true); else if ((access & AccessTypes.Write) == AccessTypes.Write) return TypeProvider.IsAssignable(memberType, baseType, true); else return false; } private ValidationErrorCollection ValidateActivityBind(ValidationManager manager, object obj) { ValidationErrorCollection validationErrors = base.Validate(manager, obj); ActivityBind bind = obj as ActivityBind; PropertyValidationContext validationContext = manager.Context[typeof(PropertyValidationContext)] as PropertyValidationContext; if (validationContext == null) throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(BindValidationContext).Name)); Activity activity = manager.Context[typeof(Activity)] as Activity; if (activity == null) throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(Activity).Name)); ValidationError error = null; //Redirect from here to FieldBind/MethodBind by creating their instances BindValidationContext validationBindContext = manager.Context[typeof(BindValidationContext)] as BindValidationContext; if (validationBindContext == null) { Type baseType = BindHelpers.GetBaseType(manager, validationContext); if (baseType != null) { AccessTypes accessType = BindHelpers.GetAccessType(manager, validationContext); validationBindContext = new BindValidationContext(baseType, accessType); } //else //{ // error = new ValidationError(SR.GetString(SR.Error_BindBaseTypeNotSpecified, validationContext.PropertyName), ErrorNumbers.Error_BindBaseTypeNotSpecified); // error.PropertyName = GetFullPropertyName(manager) + ".Name"; //} } if (validationBindContext != null) { Type targetType = validationBindContext.TargetType; if (error == null) validationErrors.AddRange(this.ValidateActivity(manager, bind, new BindValidationContext(targetType, validationBindContext.Access))); } if (error != null) validationErrors.Add(error); return validationErrors; } private ValidationErrorCollection ValidateActivity(ValidationManager manager, ActivityBind bind, BindValidationContext validationContext) { ValidationError error = null; ValidationErrorCollection validationErrors = new ValidationErrorCollection(); Activity activity = manager.Context[typeof(Activity)] as Activity; if (activity == null) throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(Activity).Name)); Activity refActivity = Helpers.ParseActivityForBind(activity, bind.Name); if (refActivity == null) { error = (bind.Name.StartsWith("/", StringComparison.Ordinal)) ? new ValidationError(SR.GetString(SR.Error_CannotResolveRelativeActivity, bind.Name), ErrorNumbers.Error_CannotResolveRelativeActivity) : new ValidationError(SR.GetString(SR.Error_CannotResolveActivity, bind.Name), ErrorNumbers.Error_CannotResolveActivity); error.PropertyName = GetFullPropertyName(manager) + ".Name"; } else if (bind.Path == null || bind.Path.Length == 0) { error = new ValidationError(SR.GetString(SR.Error_PathNotSetForActivitySource), ErrorNumbers.Error_PathNotSetForActivitySource); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } else { // if (!bind.Name.StartsWith("/", StringComparison.Ordinal) && !ValidationHelpers.IsActivitySourceInOrder(refActivity, activity)) { error = new ValidationError(SR.GetString(SR.Error_BindActivityReference, refActivity.QualifiedName, activity.QualifiedName), ErrorNumbers.Error_BindActivityReference, true); error.PropertyName = GetFullPropertyName(manager) + ".Name"; } IDesignerHost designerHost = manager.GetService(typeof(IDesignerHost)) as IDesignerHost; WorkflowDesignerLoader loader = manager.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader; if (designerHost != null && loader != null) { Type refActivityType = null; if (designerHost.RootComponent == refActivity) { ITypeProvider typeProvider = manager.GetService(typeof(ITypeProvider)) as ITypeProvider; if (typeProvider == null) throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName)); refActivityType = typeProvider.GetType(designerHost.RootComponentClassName); } else { refActivity.GetType(); } if (refActivityType != null) { MemberInfo memberInfo = MemberBind.GetMemberInfo(refActivityType, bind.Path); if (memberInfo == null || (memberInfo is PropertyInfo && !(memberInfo as PropertyInfo).CanRead)) { error = new ValidationError(SR.GetString(SR.Error_InvalidMemberPath, refActivity.QualifiedName, bind.Path), ErrorNumbers.Error_InvalidMemberPath); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } else { Type memberType = null; if (memberInfo is FieldInfo) memberType = ((FieldInfo)(memberInfo)).FieldType; else if (memberInfo is PropertyInfo) memberType = ((PropertyInfo)(memberInfo)).PropertyType; else if (memberInfo is EventInfo) memberType = ((EventInfo)(memberInfo)).EventHandlerType; if (!DoesTargetTypeMatch(validationContext.TargetType, memberType, validationContext.Access)) { if (typeof(WorkflowParameterBinding).IsAssignableFrom(memberInfo.DeclaringType)) { error = new ValidationError(SR.GetString(SR.Warning_ParameterBinding, bind.Path, refActivity.QualifiedName, validationContext.TargetType.FullName), ErrorNumbers.Warning_ParameterBinding, true); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } else { error = new ValidationError(SR.GetString(SR.Error_TargetTypeMismatch, memberInfo.Name, memberType.FullName, validationContext.TargetType.FullName), ErrorNumbers.Error_TargetTypeMismatch); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } } } } } else { MemberInfo memberInfo = MemberBind.GetMemberInfo(refActivity.GetType(), bind.Path); if (memberInfo == null || (memberInfo is PropertyInfo && !(memberInfo as PropertyInfo).CanRead)) { error = new ValidationError(SR.GetString(SR.Error_InvalidMemberPath, refActivity.QualifiedName, bind.Path), ErrorNumbers.Error_InvalidMemberPath); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } else { DependencyProperty dependencyProperty = DependencyProperty.FromName(memberInfo.Name, memberInfo.DeclaringType); object value = BindHelpers.ResolveActivityPath(refActivity, bind.Path); if (value == null) { Type memberType = null; if (memberInfo is FieldInfo) memberType = ((FieldInfo)(memberInfo)).FieldType; else if (memberInfo is PropertyInfo) memberType = ((PropertyInfo)(memberInfo)).PropertyType; else if (memberInfo is EventInfo) memberType = ((EventInfo)(memberInfo)).EventHandlerType; if (!TypeProvider.IsAssignable(typeof(ActivityBind), memberType) && !DoesTargetTypeMatch(validationContext.TargetType, memberType, validationContext.Access)) { if (typeof(WorkflowParameterBinding).IsAssignableFrom(memberInfo.DeclaringType)) { error = new ValidationError(SR.GetString(SR.Warning_ParameterBinding, bind.Path, refActivity.QualifiedName, validationContext.TargetType.FullName), ErrorNumbers.Warning_ParameterBinding, true); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } else { error = new ValidationError(SR.GetString(SR.Error_TargetTypeMismatch, memberInfo.Name, memberType.FullName, validationContext.TargetType.FullName), ErrorNumbers.Error_TargetTypeMismatch); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } } } // If this is the top level activity, we should not valid that the bind can be resolved because // the value of bind can be set when this activity is used in another activity. else if (value is ActivityBind && refActivity.Parent != null) { ActivityBind referencedBind = value as ActivityBind; bool bindRecursionContextAdded = false; // Check for recursion BindRecursionContext recursionContext = manager.Context[typeof(BindRecursionContext)] as BindRecursionContext; if (recursionContext == null) { recursionContext = new BindRecursionContext(); manager.Context.Push(recursionContext); bindRecursionContextAdded = true; } if (recursionContext.Contains(activity, bind)) { error = new ValidationError(SR.GetString(SR.Bind_ActivityDataSourceRecursionDetected), ErrorNumbers.Bind_ActivityDataSourceRecursionDetected); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } else { recursionContext.Add(activity, bind); PropertyValidationContext propertyValidationContext = null; if (dependencyProperty != null) propertyValidationContext = new PropertyValidationContext(refActivity, dependencyProperty); else propertyValidationContext = new PropertyValidationContext(refActivity, memberInfo as PropertyInfo, memberInfo.Name); validationErrors.AddRange(ValidationHelpers.ValidateProperty(manager, refActivity, referencedBind, propertyValidationContext, validationContext)); } if (bindRecursionContextAdded) manager.Context.Pop(); } else if (validationContext.TargetType != null && !DoesTargetTypeMatch(validationContext.TargetType, value.GetType(), validationContext.Access)) { error = new ValidationError(SR.GetString(SR.Error_TargetTypeMismatch, memberInfo.Name, value.GetType().FullName, validationContext.TargetType.FullName), ErrorNumbers.Error_TargetTypeMismatch); error.PropertyName = GetFullPropertyName(manager) + ".Path"; } } } } if (error != null) validationErrors.Add(error); return validationErrors; } } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Net.Sockets; using System.Threading; namespace System.Net.NetworkInformation { public partial class NetworkChange { private static readonly object s_globalLock = new object(); public static event NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged { add { AvailabilityChangeListener.Start(value); } remove { AvailabilityChangeListener.Stop(value); } } public static event NetworkAddressChangedEventHandler NetworkAddressChanged { add { AddressChangeListener.Start(value); } remove { AddressChangeListener.Stop(value); } } internal static class AvailabilityChangeListener { private static readonly NetworkAddressChangedEventHandler s_addressChange = ChangedAddress; private static volatile bool s_isAvailable = false; private static void ChangedAddress(object sender, EventArgs eventArgs) { Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext> availabilityChangedSubscribers = null; lock (s_globalLock) { bool isAvailableNow = SystemNetworkInterface.InternalGetIsNetworkAvailable(); // If there is an Availability Change, need to execute user callbacks. if (isAvailableNow != s_isAvailable) { s_isAvailable = isAvailableNow; if (s_availabilityChangedSubscribers.Count > 0) { availabilityChangedSubscribers = new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext>(s_availabilityChangedSubscribers); } } } // Executing user callbacks if Availability Change event occured. if (availabilityChangedSubscribers != null) { bool isAvailable = s_isAvailable; NetworkAvailabilityEventArgs args = isAvailable ? s_availableEventArgs : s_notAvailableEventArgs; ContextCallback callbackContext = isAvailable ? s_runHandlerAvailable : s_runHandlerNotAvailable; foreach (KeyValuePair<NetworkAvailabilityChangedEventHandler, ExecutionContext> subscriber in availabilityChangedSubscribers) { NetworkAvailabilityChangedEventHandler handler = subscriber.Key; ExecutionContext ec = subscriber.Value; if (ec == null) // Flow supressed { handler(null, args); } else { ExecutionContext.Run(ec, callbackContext, handler); } } } } internal static void Start(NetworkAvailabilityChangedEventHandler caller) { if (caller != null) { lock (s_globalLock) { if (s_availabilityChangedSubscribers.Count == 0) { s_isAvailable = NetworkInterface.GetIsNetworkAvailable(); AddressChangeListener.UnsafeStart(s_addressChange); } s_availabilityChangedSubscribers.TryAdd(caller, ExecutionContext.Capture()); } } } internal static void Stop(NetworkAvailabilityChangedEventHandler caller) { if (caller != null) { lock (s_globalLock) { s_availabilityChangedSubscribers.Remove(caller); if (s_availabilityChangedSubscribers.Count == 0) { AddressChangeListener.Stop(s_addressChange); } } } } } // Helper class for detecting address change events. internal static unsafe class AddressChangeListener { // Need to keep the reference so it isn't GC'd before the native call executes. private static bool s_isListening = false; private static bool s_isPending = false; private static Socket s_ipv4Socket = null; private static Socket s_ipv6Socket = null; private static WaitHandle s_ipv4WaitHandle = null; private static WaitHandle s_ipv6WaitHandle = null; // Callback fired when an address change occurs. private static void AddressChangedCallback(object stateObject, bool signaled) { Dictionary<NetworkAddressChangedEventHandler, ExecutionContext> addressChangedSubscribers = null; lock (s_globalLock) { // The listener was canceled, which would only happen if we aren't listening for more events. s_isPending = false; if (!s_isListening) { return; } s_isListening = false; // Need to copy the array so the callback can call start and stop if (s_addressChangedSubscribers.Count > 0) { addressChangedSubscribers = new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext>(s_addressChangedSubscribers); } try { //wait for the next address change StartHelper(null, false, (StartIPOptions)stateObject); } catch (NetworkInformationException nie) { if (NetEventSource.IsEnabled) NetEventSource.Error(null, nie); } } // Release the lock before calling into user callback. if (addressChangedSubscribers != null) { foreach (KeyValuePair<NetworkAddressChangedEventHandler, ExecutionContext> subscriber in addressChangedSubscribers) { NetworkAddressChangedEventHandler handler = subscriber.Key; ExecutionContext ec = subscriber.Value; if (ec == null) // Flow supressed { handler(null, EventArgs.Empty); } else { ExecutionContext.Run(ec, s_runAddressChangedHandler, handler); } } } } internal static void Start(NetworkAddressChangedEventHandler caller) { StartHelper(caller, true, StartIPOptions.Both); } internal static void UnsafeStart(NetworkAddressChangedEventHandler caller) { StartHelper(caller, false, StartIPOptions.Both); } private static void StartHelper(NetworkAddressChangedEventHandler caller, bool captureContext, StartIPOptions startIPOptions) { lock (s_globalLock) { // Setup changedEvent and native overlapped struct. if (s_ipv4Socket == null) { // Sockets will be initialized by the call to OSSupportsIP*. if (Socket.OSSupportsIPv4) { s_ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0) { Blocking = false }; s_ipv4WaitHandle = new AutoResetEvent(false); } if (Socket.OSSupportsIPv6) { s_ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, 0) { Blocking = false }; s_ipv6WaitHandle = new AutoResetEvent(false); } } if (caller != null) { s_addressChangedSubscribers.TryAdd(caller, captureContext ? ExecutionContext.Capture() : null); } if (s_isListening || s_addressChangedSubscribers.Count == 0) { return; } if (!s_isPending) { if (Socket.OSSupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) != 0) { ThreadPool.RegisterWaitForSingleObject( s_ipv4WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv4, -1, true); SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking( s_ipv4Socket.Handle, (int)IOControlCode.AddressListChange, null, 0, null, 0, out int length, IntPtr.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } errorCode = Interop.Winsock.WSAEventSelect( s_ipv4Socket.SafeHandle, s_ipv4WaitHandle.GetSafeWaitHandle(), Interop.Winsock.AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } if (Socket.OSSupportsIPv6 && (startIPOptions & StartIPOptions.StartIPv6) != 0) { ThreadPool.RegisterWaitForSingleObject( s_ipv6WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv6, -1, true); SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking( s_ipv6Socket.Handle, (int)IOControlCode.AddressListChange, null, 0, null, 0, out int length, IntPtr.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } errorCode = Interop.Winsock.WSAEventSelect( s_ipv6Socket.SafeHandle, s_ipv6WaitHandle.GetSafeWaitHandle(), Interop.Winsock.AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } } s_isListening = true; s_isPending = true; } } internal static void Stop(NetworkAddressChangedEventHandler caller) { if (caller != null) { lock (s_globalLock) { s_addressChangedSubscribers.Remove(caller); if (s_addressChangedSubscribers.Count == 0 && s_isListening) { s_isListening = false; } } } } } } }
using System; using System.Linq; using NUnit.Framework; using Rothko.Services; using System.Collections.Generic; using Rothko.Model; using Rothko.Interfaces.Components; namespace Rothko.Tests.Services { [TestFixture] public class UnitMovementServiceTests { const int U = 999; // unit const int X = 9999; // uncrossable const int N = 99999; // not in range const int R = 999999; // in range UnitMovementService _Service; Unit _Unit; List<Tile> _Tiles; List<TerrainCost> _TerrainCosts; [SetUp] public void SetUp() { _Unit = new Unit() { ID = 1, IDUnitType = 1, HealthPoints = 10 }; _Tiles = new List<Tile>(); _TerrainCosts = new List<TerrainCost>(); _Service = new UnitMovementService(); } [Test] public void GetMovementRangeShouldGetExpectedMovementRangeSimpleEnvironmentOneMovePoint() { int [,]intTileArray = { { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 }, { 1, 1, U, 1, 1 }, { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 } }; int [,]expectedRangeArray = { { N, N, N, N, N }, { N, N, R, N, N }, { N, R, U, R, N }, { N, N, R, N, N }, { N, N, N, N, N } }; TestMovementRange(1, intTileArray, expectedRangeArray); } [Test] public void GetMovementRangeShouldGetExpectedMovementRangeSimpleEnvironmentTwoMovePoints() { int [,]intTileArray = { { 1, 1, 1, 1, 1 }, { 1, U, 1, 1, 1 }, { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 } }; int [,]expectedRangeArray = { { R, R, R, N, N }, { R, U, R, R, N }, { R, R, R, N, N }, { N, R, N, N, N }, { N, N, N, N, N } }; TestMovementRange(2, intTileArray, expectedRangeArray); } [Test] public void GetMovementRangeShouldGetExpectedMovementRangeDiverseEnvironmentThreeMovePoints() { int [,]intTileArray = { { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 }, { 1, 1, 3, 2, 1 }, { 1, 1, 3, U, 2 }, { 1, 1, 1, 1, 1 } }; int [,]expectedRangeArray = { { N, N, N, N, N }, { N, N, N, R, N }, { N, N, N, R, R }, { N, N, R, U, R }, { N, R, R, R, R } }; TestMovementRange(3, intTileArray, expectedRangeArray); } [Test] public void GetMovementRangeShouldGetExpectedMovementRangeDiverseEnvironmentFourMovePoints() { int [,]intTileArray = { { 1, 1, 2, 1, 1 }, { 1, 1, 2, 4, 1 }, { 3, 1, U, 3, 2 }, { 1, 2, 4, 1, 1 }, { 1, 1, 1, 1, 1 } }; int [,]expectedRangeArray = { { R, R, R, N, N }, { R, R, R, N, N }, { R, R, U, R, N }, { R, R, R, R, N }, { N, R, N, N, N } }; TestMovementRange(4, intTileArray, expectedRangeArray); } [Test] public void GetMovementRangeShouldGetExpectedMovementRangeSimpleEnvironmentThreeMovePointsWithSomeTilesUncrossable() { int [,]intTileArray = { { 1, 3, 1, X, 1 }, { 1, 3, 1, 1, 1 }, { 1, 3, U, X, 1 }, { 1, 3, 1, 1, X }, { 1, 3, X, X, 1 } }; int [,]expectedRangeArray = { { N, N, R, N, N }, { N, N, R, R, R }, { N, R, U, N, N }, { N, N, R, R, N }, { N, N, N, N, N } }; TestMovementRange(3, intTileArray, expectedRangeArray); } private void TestMovementRange (int movePoints, int[,]intTileArray, int[,]expectedRangeArray) { _Unit.MovePoints = movePoints; SetMapFromArray(intTileArray); List<IPlottable> tiles = _Service.GetMovementRange(_Unit, _Tiles, _TerrainCosts); AssertExpectedMovementRange(expectedRangeArray, tiles); } private void AssertExpectedMovementRange (int[,]intTileArray, List<IPlottable> tilesRange) { int numberOfTilesThatShouldBeInRange = 0; for (int y = 0; y < intTileArray.GetLength(0); y++) for (int x = 0; x < intTileArray.GetLength(1); x++) { if (intTileArray [y, x] == R) { Assert.IsTrue (tilesRange.Any (t => t.X == x && t.Y == y) , x.ToString () + "," + y.ToString () + ": Should be in range"); numberOfTilesThatShouldBeInRange++; } else if (intTileArray [y, x] == N || intTileArray[y, x] == U) Assert.IsFalse (tilesRange.Any (t => t.X == x && t.Y == y) , x.ToString () + "," + y.ToString () + ": Should not be in range"); } Assert.AreEqual(numberOfTilesThatShouldBeInRange, tilesRange.Count); } private void SetMapFromArray(int [,] intTileArray) { _Tiles.Clear(); for (int y = 0; y < intTileArray.GetLength(0); y++) for (int x = 0; x < intTileArray.GetLength(1); x++) { bool canCross = true; int cost = 1; if (intTileArray[y, x] == N) continue; if (intTileArray[y, x] == X) canCross = false; else if (intTileArray[y, x] == U) { _Unit.X = x; _Unit.Y = y; } else cost = intTileArray[y, x]; TerrainCost terrainCost = _TerrainCosts.FirstOrDefault(tc => tc.CanCross == canCross && tc.Cost == cost); if (terrainCost == null) { terrainCost = new TerrainCost() { IDTileType = _TerrainCosts.Count == 0 ? 1 : _TerrainCosts.Max (tc => tc.IDTileType) + 1, IDUnitType = _Unit.IDUnitType, Cost = cost, CanCross = canCross }; _TerrainCosts.Add (terrainCost); } _Tiles.Add (new Tile() { X = x, Y = y, IDTileType = terrainCost.IDTileType }); } } } }
// 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.Linq; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; using System.Collections.Generic; using Xunit; namespace System.Reflection.Emit.Tests { public sealed class DpmParams { public string MethodName; public MethodAttributes Attributes = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl; public string LibName; public string EntrypointName; public CallingConventions ManagedCallConv = CallingConventions.Standard; public CallingConvention NativeCallConv = CallingConvention.StdCall; public CharSet Charset = CharSet.Unicode; public Type ReturnType; public Type[] ParameterTypes; public Type[] ReturnTypeReqMods; public Type[] ReturnTypeOptMods; public Type[][] ParameterTypeReqMods; public Type[][] ParameterTypeOptMods; public bool NoCMods => ReturnTypeReqMods == null && ReturnTypeOptMods == null && ParameterTypeReqMods == null && ParameterTypeOptMods == null; public sealed override string ToString() => MethodName; } public class TypeBuilderDefinePInvokeMethodTests { public static IEnumerable<DpmParams> TestData { get { // The Dll/Entrypoint names can be arbitrary as these tests only generate the P/Invoke metadata and do not attempt to invoke them. // Keep the "MethodNames" unique so that if a test fails, the theory member that failed can be identified easily from the log output. yield return new DpmParams() { MethodName = "A1", LibName = "Foo1.dll", EntrypointName = "Wha1", ReturnType = typeof(int), ParameterTypes = new Type[] { typeof(string) } }; yield return new DpmParams() { MethodName = "A2", LibName = "Foo2.dll", EntrypointName = "Wha2", ReturnType = typeof(int), ParameterTypes = new Type[] { typeof(int) }, NativeCallConv = CallingConvention.Cdecl}; yield return new DpmParams() { MethodName = "A3", LibName = "Foo3.dll", EntrypointName = "Wha3", ReturnType = typeof(double), ParameterTypes = new Type[] { typeof(string) }, Charset = CharSet.Ansi}; yield return new DpmParams() { MethodName = "A4", LibName = "Foo4.dll", EntrypointName = "Wha4", ReturnType = typeof(IntPtr), ParameterTypes = new Type[] { typeof(string) }, Charset = CharSet.Unicode}; yield return new DpmParams() { MethodName = "A5", LibName = "Foo5.dll", EntrypointName = "Wha5", ReturnType = typeof(int), ParameterTypes = new Type[] { typeof(object) }, Charset = CharSet.Auto}; yield return new DpmParams() { MethodName = "A6", LibName = "Foo6.dll", EntrypointName = "Wha6", ReturnType = typeof(char), ParameterTypes = new Type[] { typeof(string) }, Charset = CharSet.None}; yield return new DpmParams() { MethodName = "B1", LibName = "Foo7.dll", EntrypointName = "B1", ReturnType = typeof(void), ParameterTypes = new Type[] { typeof(string) } }; yield return new DpmParams() { MethodName = "C1", LibName = "Foo8.dll", EntrypointName = "Wha7", ReturnType = typeof(int), ParameterTypes = new Type[] { typeof(string) }, ReturnTypeReqMods = new Type[] { typeof(int) }, ReturnTypeOptMods = new Type[] { typeof(short) }, ParameterTypeOptMods = new Type[][] { new Type[] { typeof(double) } }, ParameterTypeReqMods = new Type[][] { new Type[] { typeof(float) } }, }; } } public static IEnumerable<object[]> TheoryData1 => TestData.Where(dpm => dpm.NoCMods).Select(dpm => new object[] { dpm }); [Theory] [MemberData(nameof(TheoryData1))] public static void TestDefinePInvokeMethod1(DpmParams p) { TypeBuilder tb = Helpers.DynamicType(TypeAttributes.Public); MethodBuilder mb = tb.DefinePInvokeMethod( p.MethodName, p.LibName, p.EntrypointName, p.Attributes, p.ManagedCallConv, p.ReturnType, p.ParameterTypes, p.NativeCallConv, p.Charset); mb.SetImplementationFlags(mb.GetMethodImplementationFlags() | MethodImplAttributes.PreserveSig); Type t = tb.CreateType(); MethodInfo m = t.GetMethod(p.MethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); Assert.NotNull(m); VerifyPInvokeMethod(t, m, p); } public static IEnumerable<object[]> TheoryData2 => TestData.Where(dpm => dpm.NoCMods && dpm.EntrypointName == dpm.MethodName).Select(dpm => new object[] { dpm }); [Theory] [MemberData(nameof(TheoryData2))] public static void TestDefinePInvokeMethod2(DpmParams p) { TypeBuilder tb = Helpers.DynamicType(TypeAttributes.Public); MethodBuilder mb = tb.DefinePInvokeMethod( p.MethodName, p.LibName, p.Attributes, p.ManagedCallConv, p.ReturnType, p.ParameterTypes, p.NativeCallConv, p.Charset); mb.SetImplementationFlags(mb.GetMethodImplementationFlags() | MethodImplAttributes.PreserveSig); Type t = tb.CreateType(); MethodInfo m = t.GetMethod(p.MethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); Assert.NotNull(m); VerifyPInvokeMethod(t, m, p); } public static IEnumerable<object[]> TheoryData3 => TestData.Select(dpm => new object[] { dpm }); [Theory] [MemberData(nameof(TheoryData3))] public static void TestDefinePInvokeMethod3(DpmParams p) { TypeBuilder tb = Helpers.DynamicType(TypeAttributes.Public); MethodBuilder mb = tb.DefinePInvokeMethod( p.MethodName, p.LibName, p.EntrypointName, p.Attributes, p.ManagedCallConv, p.ReturnType, p.ReturnTypeReqMods, p.ReturnTypeOptMods, p.ParameterTypes, p.ParameterTypeReqMods, p.ParameterTypeOptMods, p.NativeCallConv, p.Charset); mb.SetImplementationFlags(mb.GetMethodImplementationFlags() | MethodImplAttributes.PreserveSig); Type t = tb.CreateType(); MethodInfo m = t.GetMethod(p.MethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); Assert.NotNull(m); VerifyPInvokeMethod(t, m, p); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public static void TestDefinePInvokeMethodExecution_Windows() { const string EnvironmentVariable = "COMPUTERNAME"; TypeBuilder tb = Helpers.DynamicType(TypeAttributes.Public); MethodBuilder mb = tb.DefinePInvokeMethod( "GetEnvironmentVariableW", "kernel32.dll", MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl, CallingConventions.Standard, typeof(int), new Type[] { typeof(string), typeof(StringBuilder), typeof(int) }, CallingConvention.StdCall, CharSet.Unicode); mb.SetImplementationFlags(mb.GetMethodImplementationFlags() | MethodImplAttributes.PreserveSig); Type t = tb.CreateType(); MethodInfo m = t.GetMethod("GetEnvironmentVariableW", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); Assert.NotNull(m); string expected = Environment.GetEnvironmentVariable(EnvironmentVariable); int numCharsRequired = (int)m.Invoke(null, new object[] { EnvironmentVariable, null, 0 }); if (numCharsRequired == 0) { // Environment variable is not defined. Make sure we got that result using both techniques. Assert.Null(expected); } else { StringBuilder sb = new StringBuilder(numCharsRequired); int numCharsWritten = (int)m.Invoke(null, new object[] { EnvironmentVariable, sb, numCharsRequired }); Assert.NotEqual(0, numCharsWritten); string actual = sb.ToString(); Assert.Equal(expected, actual); } } internal static void VerifyPInvokeMethod(Type type, MethodInfo method, DpmParams p) { Assert.Equal(type.AsType(), method.DeclaringType); Assert.Equal(p.MethodName, method.Name); Assert.Equal(p.Attributes, method.Attributes); Assert.Equal(p.ManagedCallConv, method.CallingConvention); Assert.Equal(p.ReturnType, method.ReturnType); ParameterInfo[] parameters = method.GetParameters(); Assert.Equal<Type>(p.ParameterTypes, parameters.Select(pi => pi.ParameterType)); DllImportAttribute dia = method.GetCustomAttribute<DllImportAttribute>(); Assert.NotNull(dia); Assert.Equal(p.LibName, dia.Value); Assert.Equal(p.EntrypointName, dia.EntryPoint); Assert.Equal(p.Charset, dia.CharSet); Assert.Equal(p.NativeCallConv, dia.CallingConvention); Assert.False(dia.BestFitMapping); Assert.False(dia.ExactSpelling); Assert.True(dia.PreserveSig); Assert.False(dia.SetLastError); IList<Type> returnTypeOptMods = method.ReturnParameter.GetOptionalCustomModifiers(); if (p.ReturnTypeOptMods == null) { Assert.Equal(0, returnTypeOptMods.Count); } else { Assert.Equal<Type>(p.ReturnTypeOptMods, returnTypeOptMods); } IList<Type> returnTypeReqMods = method.ReturnParameter.GetRequiredCustomModifiers(); if (p.ReturnTypeReqMods == null) { Assert.Equal(0, returnTypeReqMods.Count); } else { Assert.Equal<Type>(p.ReturnTypeReqMods, returnTypeReqMods); } if (p.ParameterTypeOptMods == null) { foreach (ParameterInfo pi in method.GetParameters()) { Assert.Equal(0, pi.GetOptionalCustomModifiers().Length); } } else { Assert.Equal(parameters.Length, p.ParameterTypeOptMods.Length); for (int i = 0; i < p.ParameterTypeOptMods.Length; i++) { Type[] mods = parameters[i].GetOptionalCustomModifiers(); Assert.Equal<Type>(p.ParameterTypeOptMods[i], mods); } } if (p.ParameterTypeReqMods == null) { foreach (ParameterInfo pi in method.GetParameters()) { Assert.Equal(0, pi.GetRequiredCustomModifiers().Length); } } else { Assert.Equal(parameters.Length, p.ParameterTypeReqMods.Length); for (int i = 0; i < p.ParameterTypeReqMods.Length; i++) { Type[] mods = parameters[i].GetRequiredCustomModifiers(); Assert.Equal<Type>(p.ParameterTypeReqMods[i], mods); } } } } }
// 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 gagr = Google.Api.Gax.ResourceNames; using gcpv = Google.Cloud.PubSub.V1; using sys = System; namespace Google.Cloud.PubSub.V1 { /// <summary>Resource name for the <c>Schema</c> resource.</summary> public sealed partial class SchemaName : gax::IResourceName, sys::IEquatable<SchemaName> { /// <summary>The possible contents of <see cref="SchemaName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/schemas/{schema}</c>.</summary> ProjectSchema = 1, } private static gax::PathTemplate s_projectSchema = new gax::PathTemplate("projects/{project}/schemas/{schema}"); /// <summary>Creates a <see cref="SchemaName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="SchemaName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static SchemaName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new SchemaName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="SchemaName"/> with the pattern <c>projects/{project}/schemas/{schema}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="schemaId">The <c>Schema</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SchemaName"/> constructed from the provided ids.</returns> public static SchemaName FromProjectSchema(string projectId, string schemaId) => new SchemaName(ResourceNameType.ProjectSchema, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), schemaId: gax::GaxPreconditions.CheckNotNullOrEmpty(schemaId, nameof(schemaId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SchemaName"/> with pattern /// <c>projects/{project}/schemas/{schema}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="schemaId">The <c>Schema</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SchemaName"/> with pattern /// <c>projects/{project}/schemas/{schema}</c>. /// </returns> public static string Format(string projectId, string schemaId) => FormatProjectSchema(projectId, schemaId); /// <summary> /// Formats the IDs into the string representation of this <see cref="SchemaName"/> with pattern /// <c>projects/{project}/schemas/{schema}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="schemaId">The <c>Schema</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SchemaName"/> with pattern /// <c>projects/{project}/schemas/{schema}</c>. /// </returns> public static string FormatProjectSchema(string projectId, string schemaId) => s_projectSchema.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(schemaId, nameof(schemaId))); /// <summary>Parses the given resource name string into a new <see cref="SchemaName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/schemas/{schema}</c></description></item> /// </list> /// </remarks> /// <param name="schemaName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SchemaName"/> if successful.</returns> public static SchemaName Parse(string schemaName) => Parse(schemaName, false); /// <summary> /// Parses the given resource name string into a new <see cref="SchemaName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/schemas/{schema}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="schemaName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="SchemaName"/> if successful.</returns> public static SchemaName Parse(string schemaName, bool allowUnparsed) => TryParse(schemaName, allowUnparsed, out SchemaName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SchemaName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/schemas/{schema}</c></description></item> /// </list> /// </remarks> /// <param name="schemaName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="SchemaName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string schemaName, out SchemaName result) => TryParse(schemaName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SchemaName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/schemas/{schema}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="schemaName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="SchemaName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string schemaName, bool allowUnparsed, out SchemaName result) { gax::GaxPreconditions.CheckNotNull(schemaName, nameof(schemaName)); gax::TemplatedResourceName resourceName; if (s_projectSchema.TryParseName(schemaName, out resourceName)) { result = FromProjectSchema(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(schemaName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private SchemaName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string schemaId = null) { Type = type; UnparsedResource = unparsedResourceName; ProjectId = projectId; SchemaId = schemaId; } /// <summary> /// Constructs a new instance of a <see cref="SchemaName"/> class from the component parts of pattern /// <c>projects/{project}/schemas/{schema}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="schemaId">The <c>Schema</c> ID. Must not be <c>null</c> or empty.</param> public SchemaName(string projectId, string schemaId) : this(ResourceNameType.ProjectSchema, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), schemaId: gax::GaxPreconditions.CheckNotNullOrEmpty(schemaId, nameof(schemaId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Schema</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string SchemaId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectSchema: return s_projectSchema.Expand(ProjectId, SchemaId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as SchemaName); /// <inheritdoc/> public bool Equals(SchemaName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(SchemaName a, SchemaName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(SchemaName a, SchemaName b) => !(a == b); } public partial class Schema { /// <summary> /// <see cref="gcpv::SchemaName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcpv::SchemaName SchemaName { get => string.IsNullOrEmpty(Name) ? null : gcpv::SchemaName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateSchemaRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetSchemaRequest { /// <summary> /// <see cref="gcpv::SchemaName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcpv::SchemaName SchemaName { get => string.IsNullOrEmpty(Name) ? null : gcpv::SchemaName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListSchemasRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteSchemaRequest { /// <summary> /// <see cref="gcpv::SchemaName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcpv::SchemaName SchemaName { get => string.IsNullOrEmpty(Name) ? null : gcpv::SchemaName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ValidateSchemaRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ValidateMessageRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gcpv::SchemaName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcpv::SchemaName SchemaName { get => string.IsNullOrEmpty(Name) ? null : gcpv::SchemaName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
//----------------------------------------------------------------------- // <copyright company="CoApp Project"> // Copyright (c) 2010-2013 Garrett Serack and CoApp Contributors. // Contributors can be discovered using the 'git log' command. // All rights reserved. // </copyright> // <license> // The software is licensed under the Apache 2.0 License (the "License") // You may not use the software except in compliance with the License. // </license> //----------------------------------------------------------------------- namespace ClrPlus.Platform { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Microsoft.Win32.SafeHandles; using Properties; using Windows.Api; using Windows.Api.Enumerations; using Windows.Api.Flags; using Windows.Api.Structures; /// <summary> /// Safe native methods. (part of alternate streams stuff) /// </summary> internal static class SafeNativeMethods { #region Constants and flags public const int MaxPath = 256; private const string LongPathPrefix = @"\\?\"; public const char StreamSeparator = ':'; public const int DefaultBufferSize = 0x1000; private const int ErrorFileNotFound = 2; // "Characters whose integer representations are in the range from 1 through 31, // except for alternate streams where these characters are allowed" // http://msdn.microsoft.com/en-us/library/aa365247(v=VS.85).aspx private static readonly char[] InvalidStreamNameChars = Path.GetInvalidFileNameChars().Where(c => c < 1 || c > 31).ToArray(); #endregion #region Utility Structures public struct Win32StreamInfo { public FileStreamAttributes StreamAttributes; public string StreamName; public long StreamSize; public FileStreamType StreamType; } #endregion #region Utility Methods private static int MakeHRFromErrorCode(int errorCode) { return (-2147024896 | errorCode); } private static string GetErrorMessage(int errorCode) { var lpBuffer = new StringBuilder(0x200); if (0 != Kernel32.FormatMessage(0x3200, IntPtr.Zero, errorCode, 0, lpBuffer, lpBuffer.Capacity, IntPtr.Zero)) { return lpBuffer.ToString(); } return string.Format(Resources.Culture, Resources.Error_UnknownError, errorCode); } private static void ThrowIOError(int errorCode, string path) { switch (errorCode) { case 0: { break; } case 2: // File not found { if (string.IsNullOrEmpty(path)) { throw new FileNotFoundException(); } throw new FileNotFoundException(null, path); } case 3: // Directory not found { if (string.IsNullOrEmpty(path)) { throw new DirectoryNotFoundException(); } throw new DirectoryNotFoundException(string.Format(Resources.Culture, Resources.Error_DirectoryNotFound, path)); } case 5: // Access denied { if (string.IsNullOrEmpty(path)) { throw new UnauthorizedAccessException(); } throw new UnauthorizedAccessException(string.Format(Resources.Culture, Resources.Error_AccessDenied_Path, path)); } case 15: // Drive not found { if (string.IsNullOrEmpty(path)) { throw new DriveNotFoundException(); } throw new DriveNotFoundException(string.Format(Resources.Culture, Resources.Error_DriveNotFound, path)); } case 32: // Sharing violation { if (string.IsNullOrEmpty(path)) { throw new IOException(GetErrorMessage(errorCode), MakeHRFromErrorCode(errorCode)); } throw new IOException(string.Format(Resources.Culture, Resources.Error_SharingViolation, path), MakeHRFromErrorCode(errorCode)); } case 80: // File already exists { if (!string.IsNullOrEmpty(path)) { throw new IOException(string.Format(Resources.Culture, Resources.Error_FileAlreadyExists, path), MakeHRFromErrorCode(errorCode)); } break; } case 87: // Invalid parameter { throw new IOException(GetErrorMessage(errorCode), MakeHRFromErrorCode(errorCode)); } case 183: // File or directory already exists { if (!string.IsNullOrEmpty(path)) { throw new IOException(string.Format(Resources.Culture, Resources.Error_AlreadyExists, path), MakeHRFromErrorCode(errorCode)); } break; } case 206: // Path too long { throw new PathTooLongException(); } case 995: // Operation canceled { throw new OperationCanceledException(); } default: { Marshal.ThrowExceptionForHR(MakeHRFromErrorCode(errorCode)); break; } } } public static void ThrowLastIOError(string path) { var errorCode = Marshal.GetLastWin32Error(); if (0 != errorCode) { var hr = Marshal.GetHRForLastWin32Error(); if (0 <= hr) { throw new Win32Exception(errorCode); } ThrowIOError(errorCode, path); } } public static NativeFileAccess ToNative(this FileAccess access) { NativeFileAccess result = 0; if (FileAccess.Read == (FileAccess.Read & access)) { result |= NativeFileAccess.GenericRead; } if (FileAccess.Write == (FileAccess.Write & access)) { result |= NativeFileAccess.GenericWrite; } return result; } public static string BuildStreamPath(string filePath, string streamName) { var result = filePath; if (!string.IsNullOrEmpty(filePath)) { if (1 == result.Length) { result = ".\\" + result; } result += StreamSeparator + streamName + StreamSeparator + "$DATA"; if (MaxPath <= result.Length) { result = LongPathPrefix + result; } } return result; } public static void ValidateStreamName(string streamName) { if (!string.IsNullOrEmpty(streamName) && -1 != streamName.IndexOfAny(InvalidStreamNameChars)) { throw new ArgumentException(Resources.Error_InvalidFileChars); } } public static int SafeGetFileAttributes(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } var result = Kernel32.GetFileAttributes(name); if (-1 == result) { var errorCode = Marshal.GetLastWin32Error(); if (ErrorFileNotFound != errorCode) { ThrowLastIOError(name); } } return result; } public static bool SafeDeleteFile(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } var result = Kernel32.DeleteFile(name); if (!result) { var errorCode = Marshal.GetLastWin32Error(); if (ErrorFileNotFound != errorCode) { ThrowLastIOError(name); } } return result; } public static SafeFileHandle SafeCreateFile(string path, NativeFileAccess access, FileShare share, IntPtr security, FileMode mode, NativeFileAttributesAndFlags flags, IntPtr template) { var result = Kernel32.CreateFile(path, access, share, security, mode, flags, template); if (!result.IsInvalid && FileType.Disk != Kernel32.GetFileType(result)) { result.Dispose(); throw new NotSupportedException(string.Format(Resources.Culture, Resources.Error_NonFile, path)); } return result; } private static long GetFileSize(string path, SafeFileHandle handle) { var result = 0L; if (null != handle && !handle.IsInvalid) { long value; if (Kernel32.GetFileSizeEx(handle, out value)) { result = value; } else { ThrowLastIOError(path); } } return result; } public static long GetFileSize(string path) { var result = 0L; if (!string.IsNullOrEmpty(path)) { using (var handle = SafeCreateFile(path, NativeFileAccess.GenericRead, FileShare.Read, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero)) { result = GetFileSize(path, handle); } } return result; } public static IList<Win32StreamInfo> ListStreams(string filePath) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath"); } if (-1 != filePath.IndexOfAny(Path.GetInvalidPathChars())) { throw new ArgumentException(Resources.Error_InvalidFileChars, "filePath"); } var result = new List<Win32StreamInfo>(); using ( var hFile = SafeCreateFile(filePath, NativeFileAccess.GenericRead, FileShare.Read, IntPtr.Zero, FileMode.Open, NativeFileAttributesAndFlags.BackupSemantics, IntPtr.Zero)) { using (var hName = new StreamName()) { if (!hFile.IsInvalid) { var streamId = new Win32StreamId(); var dwStreamHeaderSize = Marshal.SizeOf(streamId); var finished = false; var context = IntPtr.Zero; int bytesRead; string name; try { while (!finished) { // Read the next stream header: if (!Kernel32.BackupRead(hFile, ref streamId, dwStreamHeaderSize, out bytesRead, false, false, ref context)) { finished = true; } else if (dwStreamHeaderSize != bytesRead) { finished = true; } else { // Read the stream name: if (0 >= streamId.StreamNameSize) { name = null; } else { hName.EnsureCapacity(streamId.StreamNameSize); if (!Kernel32.BackupRead(hFile, hName.MemoryBlock, streamId.StreamNameSize, out bytesRead, false, false, ref context)) { name = null; finished = true; } else { // Unicode chars are 2 bytes: name = hName.ReadStreamName(bytesRead >> 1); } } // Add the stream info to the result: if (!string.IsNullOrEmpty(name)) { result.Add(new Win32StreamInfo { StreamType = (FileStreamType)streamId.StreamId, StreamAttributes = (FileStreamAttributes)streamId.StreamAttributes, StreamSize = streamId.Size, StreamName = name }); } // Skip the contents of the stream: int bytesSeekedLow, bytesSeekedHigh; if (!finished && !Kernel32.BackupSeek(hFile, (int)(streamId.Size & 0xffffffff), (int)(streamId.Size >> 32), out bytesSeekedLow, out bytesSeekedHigh, ref context)) { finished = true; } } } } finally { // Abort the backup: Kernel32.BackupRead(hFile, hName.MemoryBlock, 0, out bytesRead, true, false, ref context); } } } } return result; } #endregion } }
#define EDITOR_VERBOSE //#define WARN_NOT_SUPPORTED_ACTION //#define WARN_NOT_SUPPORTED_PLATFORM using System; using System.Runtime.InteropServices; using UnityEngine; namespace TestFlightUnity { /// <summary> /// The p/invoke wrapper around the C binding of the TestFlight SDK. // <see href="https://testflightapp.com/sdk/doc/"> /// </summary> #if UNITY_EDITOR && UNITY_ANDROID [UnityEditor.InitializeOnLoad] #endif public static class TestFlight { #if UNITY_EDITOR #if UNITY_ANDROID static TestFlight() { const string PropertiesFile = "Assets/Plugins/Android/res/raw/tf.properties"; var obj = Resources.LoadAssetAtPath<UnityEngine.Object>( PropertiesFile ); if ( obj == null ) Debug.LogWarning( string.Format("TestFlight for Android requires a {0} file.", PropertiesFile) ); } #endif public static void TakeOff( string token ) { #if EDITOR_VERBOSE Debug.Log( "TestFlight TakeOff: " + token ); #endif } public static void PassCheckpoint( string checkpoint ) { #if EDITOR_VERBOSE Debug.Log( "TestFlight PassCheckpoint: " + checkpoint ); #endif } public static void AddCustomEnvironmentInformation( string info, string key ) { #if EDITOR_VERBOSE Debug.Log( string.Format("TestFlight AddCustomEnvironmentInformation: {0} = {1}", info, key) ); #endif } public static void OpenFeedbackView() { #if EDITOR_VERBOSE Debug.Log( "TestFlight OpenFeedbackView" ); #endif } public static void SendFeedback( string feedback ) { #if EDITOR_VERBOSE Debug.Log( "TestFlight SendFeedback: " + feedback ); #endif } public static void SetDeviceID() { #if EDITOR_VERBOSE Debug.Log( "TestFlight SetDeviceID" ); #endif } public static void Log( string msg ) { #if EDITOR_VERBOSE Debug.Log( "TestFlight Log: " + msg ); #endif } public static void Crash() { #if EDITOR_VERBOSE Debug.Log( "TestFlight Crash" ); #endif } #elif UNITY_IPHONE [DllImport ( "__Internal" )] private static extern void TF_TakeOff( string token ); [DllImport ( "__Internal" )] private static extern void TF_PassCheckpoint( string checkpoint ); [DllImport ( "__Internal" )] private static extern void TF_AddCustomEnvironmentInformation( string info, string key ); [DllImport ( "__Internal" )] private static extern void TF_OpenFeedbackView(); [DllImport ( "__Internal" )] private static extern void TF_SendFeedback( string feedback ); [DllImport ( "__Internal" )] private static extern void TF_SetDeviceID(); [DllImport ( "__Internal" )] private static extern void TF_Log( string msg ); [DllImport ( "__Internal" )] private static extern void TF_Crash(); public static void TakeOff( string token ) { TF_TakeOff( token ); } public static void PassCheckpoint( string checkpoint ) { TF_PassCheckpoint( checkpoint ); } public static void AddCustomEnvironmentInformation( string info, string key ) { TF_AddCustomEnvironmentInformation( info, key ); } public static void OpenFeedbackView() { TF_OpenFeedbackView(); } public static void SendFeedback( string feedback ) { TF_SendFeedback( feedback ); } public static void SetDeviceID() { TF_SetDeviceID(); } public static void Log( string msg ) { TF_Log( msg ); } public static void Crash() { TF_Crash(); } #elif UNITY_ANDROID static AndroidJavaClass tf; public static void TakeOff( string token ) { using ( AndroidJavaClass jc = new AndroidJavaClass( "com.unity3d.player.UnityPlayer" ) ) using ( AndroidJavaObject activity = jc.GetStatic<AndroidJavaObject>( "currentActivity" ) ) using ( AndroidJavaObject app = activity.Call<AndroidJavaObject>( "getApplicationContext" ) ) CallJavaTF( "takeOff", app, token ); } public static void PassCheckpoint( string checkpoint ) { CallJavaTF( "passCheckpoint", checkpoint ); } public static void AddCustomEnvironmentInformation( string info, string key ) { #if WARN_NOT_SUPPORTED_ACTION Debug.LogWarning( string.Format("TestFlight AddCustomEnvironmentInformation not supported: {0} = {1}", info, key) ); #endif } public static void OpenFeedbackView() { #if WARN_NOT_SUPPORTED_ACTION Debug.LogWarning( "TestFlight OpenFeedbackView not supported" ); #endif } public static void SendFeedback( string feedback ) { #if WARN_NOT_SUPPORTED_ACTION Debug.LogWarning( "TestFlight SendFeedback not supported: " + feedback ); #endif } public static void SetDeviceID() { #if WARN_NOT_SUPPORTED_ACTION Debug.LogWarning( "TestFlight SetDeviceID not supported" ); #endif } public static void Log( string msg ) { CallJavaTF( "log", msg ); } public static void Crash() { #if WARN_NOT_SUPPORTED_ACTION Debug.LogWarning( "TestFlight Crash not supported" ); #endif } static void CallJavaTF( string method, params object[] args ) { if ( tf == null ) tf = new AndroidJavaClass( "com.testflightapp.lib.TestFlight" ); tf.CallStatic( method, args ); } #else public static void TakeOff( string token ) { #if WARN_NOT_SUPPORTED_PLATFORM Debug.LogWarning( "TestFlight TakeOff, platform not supported: " + token ); #endif } public static void PassCheckpoint( string checkpoint ) { #if WARN_NOT_SUPPORTED_PLATFORM Debug.LogWarning( "TestFlight PassCheckpoint, platform not supported: " + checkpoint ); #endif } public static void AddCustomEnvironmentInformation( string info, string key ) { #if WARN_NOT_SUPPORTED_PLATFORM Debug.LogWarning( string.Format("TestFlight AddCustomEnvironmentInformation, platform not supported: {0} = {1}", info, key) ); #endif } public static void OpenFeedbackView() { #if WARN_NOT_SUPPORTED_PLATFORM Debug.LogWarning( "TestFlight OpenFeedbackView, platform not supported" ); #endif } public static void SendFeedback( string feedback ) { #if WARN_NOT_SUPPORTED_PLATFORM Debug.LogWarning( "TestFlight SendFeedback, platform not supported: " + feedback ); #endif } public static void SetDeviceID() { #if WARN_NOT_SUPPORTED_PLATFORM Debug.LogWarning( "TestFlight SetDeviceID, platform not supported" ); #endif } public static void Log( string msg ) { #if WARN_NOT_SUPPORTED_PLATFORM Debug.LogWarning( "TestFlight Log, platform not supported: " + msg ); #endif } public static void Crash() { #if WARN_NOT_SUPPORTED_PLATFORM Debug.LogWarning( "TestFlight Crash, platform not supported" ); #endif } #endif } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>CustomerNegativeCriterion</c> resource.</summary> public sealed partial class CustomerNegativeCriterionName : gax::IResourceName, sys::IEquatable<CustomerNegativeCriterionName> { /// <summary>The possible contents of <see cref="CustomerNegativeCriterionName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/customerNegativeCriteria/{criterion_id}</c>. /// </summary> CustomerCriterion = 1, } private static gax::PathTemplate s_customerCriterion = new gax::PathTemplate("customers/{customer_id}/customerNegativeCriteria/{criterion_id}"); /// <summary> /// Creates a <see cref="CustomerNegativeCriterionName"/> containing an unparsed resource name. /// </summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="CustomerNegativeCriterionName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CustomerNegativeCriterionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CustomerNegativeCriterionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CustomerNegativeCriterionName"/> with the pattern /// <c>customers/{customer_id}/customerNegativeCriteria/{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="CustomerNegativeCriterionName"/> constructed from the provided ids. /// </returns> public static CustomerNegativeCriterionName FromCustomerCriterion(string customerId, string criterionId) => new CustomerNegativeCriterionName(ResourceNameType.CustomerCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerNegativeCriterionName"/> with /// pattern <c>customers/{customer_id}/customerNegativeCriteria/{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerNegativeCriterionName"/> with pattern /// <c>customers/{customer_id}/customerNegativeCriteria/{criterion_id}</c>. /// </returns> public static string Format(string customerId, string criterionId) => FormatCustomerCriterion(customerId, criterionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerNegativeCriterionName"/> with /// pattern <c>customers/{customer_id}/customerNegativeCriteria/{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerNegativeCriterionName"/> with pattern /// <c>customers/{customer_id}/customerNegativeCriteria/{criterion_id}</c>. /// </returns> public static string FormatCustomerCriterion(string customerId, string criterionId) => s_customerCriterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerNegativeCriterionName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/customerNegativeCriteria/{criterion_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="customerNegativeCriterionName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <returns>The parsed <see cref="CustomerNegativeCriterionName"/> if successful.</returns> public static CustomerNegativeCriterionName Parse(string customerNegativeCriterionName) => Parse(customerNegativeCriterionName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerNegativeCriterionName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/customerNegativeCriteria/{criterion_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerNegativeCriterionName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="CustomerNegativeCriterionName"/> if successful.</returns> public static CustomerNegativeCriterionName Parse(string customerNegativeCriterionName, bool allowUnparsed) => TryParse(customerNegativeCriterionName, allowUnparsed, out CustomerNegativeCriterionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerNegativeCriterionName"/> /// instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/customerNegativeCriteria/{criterion_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="customerNegativeCriterionName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerNegativeCriterionName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string customerNegativeCriterionName, out CustomerNegativeCriterionName result) => TryParse(customerNegativeCriterionName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerNegativeCriterionName"/> /// instance; optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/customerNegativeCriteria/{criterion_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerNegativeCriterionName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerNegativeCriterionName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string customerNegativeCriterionName, bool allowUnparsed, out CustomerNegativeCriterionName result) { gax::GaxPreconditions.CheckNotNull(customerNegativeCriterionName, nameof(customerNegativeCriterionName)); gax::TemplatedResourceName resourceName; if (s_customerCriterion.TryParseName(customerNegativeCriterionName, out resourceName)) { result = FromCustomerCriterion(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(customerNegativeCriterionName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CustomerNegativeCriterionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string criterionId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; CriterionId = criterionId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="CustomerNegativeCriterionName"/> class from the component parts of /// pattern <c>customers/{customer_id}/customerNegativeCriteria/{criterion_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> public CustomerNegativeCriterionName(string customerId, string criterionId) : this(ResourceNameType.CustomerCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CriterionId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerCriterion: return s_customerCriterion.Expand(CustomerId, CriterionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as CustomerNegativeCriterionName); /// <inheritdoc/> public bool Equals(CustomerNegativeCriterionName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CustomerNegativeCriterionName a, CustomerNegativeCriterionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CustomerNegativeCriterionName a, CustomerNegativeCriterionName b) => !(a == b); } public partial class CustomerNegativeCriterion { /// <summary> /// <see cref="CustomerNegativeCriterionName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal CustomerNegativeCriterionName ResourceNameAsCustomerNegativeCriterionName { get => string.IsNullOrEmpty(ResourceName) ? null : CustomerNegativeCriterionName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
// 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.Http.Headers; using Xunit; namespace System.Net.Http.Tests { public class ContentRangeHeaderValueTest { [Fact] public void Ctor_LengthOnlyOverloadUseInvalidValues_Throw() { Assert.Throws<ArgumentOutOfRangeException>(() => { ContentRangeHeaderValue v = new ContentRangeHeaderValue(-1); }); } [Fact] public void Ctor_LengthOnlyOverloadValidValues_ValuesCorrectlySet() { ContentRangeHeaderValue range = new ContentRangeHeaderValue(5); Assert.False(range.HasRange); Assert.True(range.HasLength); Assert.Equal("bytes", range.Unit); Assert.Null(range.From); Assert.Null(range.To); Assert.Equal(5, range.Length); } [Fact] public void Ctor_FromAndToOverloadUseInvalidValues_Throw() { Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(-1, 1); }); // "Negative 'from'" Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(0, -1); }); // "Negative 'to'" Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(2, 1); }); // "'from' > 'to'" } [Fact] public void Ctor_FromAndToOverloadValidValues_ValuesCorrectlySet() { ContentRangeHeaderValue range = new ContentRangeHeaderValue(0, 1); Assert.True(range.HasRange); Assert.False(range.HasLength); Assert.Equal("bytes", range.Unit); Assert.Equal(0, range.From); Assert.Equal(1, range.To); Assert.Null(range.Length); } [Fact] public void Ctor_FromToAndLengthOverloadUseInvalidValues_Throw() { Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(-1, 1, 2); }); // "Negative 'from'" Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(0, -1, 2); }); // "Negative 'to'" Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(0, 1, -1); }); // "Negative 'length'" Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(2, 1, 3); }); // "'from' > 'to'" Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(1, 2, 1); }); // "'to' > 'length'" } [Fact] public void Ctor_FromToAndLengthOverloadValidValues_ValuesCorrectlySet() { ContentRangeHeaderValue range = new ContentRangeHeaderValue(0, 1, 2); Assert.True(range.HasRange); Assert.True(range.HasLength); Assert.Equal("bytes", range.Unit); Assert.Equal(0, range.From); Assert.Equal(1, range.To); Assert.Equal(2, range.Length); } [Fact] public void Unit_GetAndSetValidAndInvalidValues_MatchExpectation() { ContentRangeHeaderValue range = new ContentRangeHeaderValue(0); range.Unit = "myunit"; Assert.Equal("myunit", range.Unit); // "Unit (custom value)" Assert.Throws<ArgumentException>(() => { range.Unit = null; }); // "<null>" Assert.Throws<ArgumentException>(() => { range.Unit = ""; }); // "empty string" Assert.Throws<FormatException>(() => { range.Unit = " x"; }); // "leading space" Assert.Throws<FormatException>(() => { range.Unit = "x "; }); // "trailing space" Assert.Throws<FormatException>(() => { range.Unit = "x y"; }); // "invalid token" } [Fact] public void ToString_UseDifferentRanges_AllSerializedCorrectly() { ContentRangeHeaderValue range = new ContentRangeHeaderValue(1, 2, 3); range.Unit = "myunit"; Assert.Equal("myunit 1-2/3", range.ToString()); // "Range with all fields set" range = new ContentRangeHeaderValue(123456789012345678, 123456789012345679); Assert.Equal("bytes 123456789012345678-123456789012345679/*", range.ToString()); // "Only range, no length" range = new ContentRangeHeaderValue(150); Assert.Equal("bytes */150", range.ToString()); // "Only length, no range" } [Fact] public void GetHashCode_UseSameAndDifferentRanges_SameOrDifferentHashCodes() { ContentRangeHeaderValue range1 = new ContentRangeHeaderValue(1, 2, 5); ContentRangeHeaderValue range2 = new ContentRangeHeaderValue(1, 2); ContentRangeHeaderValue range3 = new ContentRangeHeaderValue(5); ContentRangeHeaderValue range4 = new ContentRangeHeaderValue(1, 2, 5); range4.Unit = "BYTES"; ContentRangeHeaderValue range5 = new ContentRangeHeaderValue(1, 2, 5); range5.Unit = "myunit"; Assert.NotEqual(range1.GetHashCode(), range2.GetHashCode()); // "bytes 1-2/5 vs. bytes 1-2/*" Assert.NotEqual(range1.GetHashCode(), range3.GetHashCode()); // "bytes 1-2/5 vs. bytes */5" Assert.NotEqual(range2.GetHashCode(), range3.GetHashCode()); // "bytes 1-2/* vs. bytes */5" Assert.Equal(range1.GetHashCode(), range4.GetHashCode()); // "bytes 1-2/5 vs. BYTES 1-2/5" Assert.NotEqual(range1.GetHashCode(), range5.GetHashCode()); // "bytes 1-2/5 vs. myunit 1-2/5" } [Fact] public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions() { ContentRangeHeaderValue range1 = new ContentRangeHeaderValue(1, 2, 5); ContentRangeHeaderValue range2 = new ContentRangeHeaderValue(1, 2); ContentRangeHeaderValue range3 = new ContentRangeHeaderValue(5); ContentRangeHeaderValue range4 = new ContentRangeHeaderValue(1, 2, 5); range4.Unit = "BYTES"; ContentRangeHeaderValue range5 = new ContentRangeHeaderValue(1, 2, 5); range5.Unit = "myunit"; ContentRangeHeaderValue range6 = new ContentRangeHeaderValue(1, 3, 5); ContentRangeHeaderValue range7 = new ContentRangeHeaderValue(2, 2, 5); ContentRangeHeaderValue range8 = new ContentRangeHeaderValue(1, 2, 6); Assert.False(range1.Equals(null)); // "bytes 1-2/5 vs. <null>" Assert.False(range1.Equals(range2)); // "bytes 1-2/5 vs. bytes 1-2/*" Assert.False(range1.Equals(range3)); // "bytes 1-2/5 vs. bytes */5" Assert.False(range2.Equals(range3)); // "bytes 1-2/* vs. bytes */5" Assert.True(range1.Equals(range4)); // "bytes 1-2/5 vs. BYTES 1-2/5" Assert.True(range4.Equals(range1)); // "BYTES 1-2/5 vs. bytes 1-2/5" Assert.False(range1.Equals(range5)); // "bytes 1-2/5 vs. myunit 1-2/5" Assert.False(range1.Equals(range6)); // "bytes 1-2/5 vs. bytes 1-3/5" Assert.False(range1.Equals(range7)); // "bytes 1-2/5 vs. bytes 2-2/5" Assert.False(range1.Equals(range8)); // "bytes 1-2/5 vs. bytes 1-2/6" } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { ContentRangeHeaderValue source = new ContentRangeHeaderValue(1, 2, 5); source.Unit = "custom"; ContentRangeHeaderValue clone = (ContentRangeHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Unit, clone.Unit); Assert.Equal(source.From, clone.From); Assert.Equal(source.To, clone.To); Assert.Equal(source.Length, clone.Length); } [Fact] public void GetContentRangeLength_DifferentValidScenarios_AllReturnNonZero() { ContentRangeHeaderValue result = null; CallGetContentRangeLength("bytes 1-2/3", 0, 11, out result); Assert.Equal("bytes", result.Unit); Assert.Equal(1, result.From); Assert.Equal(2, result.To); Assert.Equal(3, result.Length); Assert.True(result.HasRange); Assert.True(result.HasLength); CallGetContentRangeLength(" custom 1234567890123456789-1234567890123456799/*", 1, 48, out result); Assert.Equal("custom", result.Unit); Assert.Equal(1234567890123456789, result.From); Assert.Equal(1234567890123456799, result.To); Assert.Null(result.Length); Assert.True(result.HasRange); Assert.False(result.HasLength); // Note that the final space should be skipped by GetContentRangeLength() and be considered by the returned // value. CallGetContentRangeLength(" custom * / 123 ", 1, 15, out result); Assert.Equal("custom", result.Unit); Assert.Null(result.From); Assert.Null(result.To); Assert.Equal(123, result.Length); Assert.False(result.HasRange); Assert.True(result.HasLength); // Note that we don't have a public constructor for value 'bytes */*' since the RFC doesn't mentione a // scenario for it. However, if a server returns this value, we're flexible and accept it. CallGetContentRangeLength("bytes */*", 0, 9, out result); Assert.Equal("bytes", result.Unit); Assert.Null(result.From); Assert.Null(result.To); Assert.Null(result.Length); Assert.False(result.HasRange); Assert.False(result.HasLength); } [Fact] public void GetContentRangeLength_DifferentInvalidScenarios_AllReturnZero() { CheckInvalidGetContentRangeLength(" bytes 1-2/3", 0); CheckInvalidGetContentRangeLength("bytes 3-2/5", 0); CheckInvalidGetContentRangeLength("bytes 6-6/5", 0); CheckInvalidGetContentRangeLength("bytes 1-6/5", 0); CheckInvalidGetContentRangeLength("bytes 1-2/", 0); CheckInvalidGetContentRangeLength("bytes 1-2", 0); CheckInvalidGetContentRangeLength("bytes 1-/", 0); CheckInvalidGetContentRangeLength("bytes 1-", 0); CheckInvalidGetContentRangeLength("bytes 1", 0); CheckInvalidGetContentRangeLength("bytes ", 0); CheckInvalidGetContentRangeLength("bytes a-2/3", 0); CheckInvalidGetContentRangeLength("bytes 1-b/3", 0); CheckInvalidGetContentRangeLength("bytes 1-2/c", 0); CheckInvalidGetContentRangeLength("bytes1-2/3", 0); // More than 19 digits >>Int64.MaxValue CheckInvalidGetContentRangeLength("bytes 1-12345678901234567890/3", 0); CheckInvalidGetContentRangeLength("bytes 12345678901234567890-3/3", 0); CheckInvalidGetContentRangeLength("bytes 1-2/12345678901234567890", 0); // Exceed Int64.MaxValue, but use 19 digits CheckInvalidGetContentRangeLength("bytes 1-9999999999999999999/3", 0); CheckInvalidGetContentRangeLength("bytes 9999999999999999999-3/3", 0); CheckInvalidGetContentRangeLength("bytes 1-2/9999999999999999999", 0); CheckInvalidGetContentRangeLength(string.Empty, 0); CheckInvalidGetContentRangeLength(null, 0); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { // Only verify parser functionality (i.e. ContentRangeHeaderParser.TryParse()). We don't need to validate // all possible range values (verification done by tests for ContentRangeHeaderValue.GetContentRangeLength()). CheckValidParse(" bytes 1-2/3 ", new ContentRangeHeaderValue(1, 2, 3)); CheckValidParse("bytes * / 3", new ContentRangeHeaderValue(3)); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse("bytes 1-2/3,"); // no character after 'length' allowed CheckInvalidParse("x bytes 1-2/3"); CheckInvalidParse("bytes 1-2/3.4"); CheckInvalidParse(null); CheckInvalidParse(string.Empty); } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { // Only verify parser functionality (i.e. ContentRangeHeaderParser.TryParse()). We don't need to validate // all possible range values (verification done by tests for ContentRangeHeaderValue.GetContentRangeLength()). CheckValidTryParse(" bytes 1-2/3 ", new ContentRangeHeaderValue(1, 2, 3)); CheckValidTryParse("bytes * / 3", new ContentRangeHeaderValue(3)); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse("bytes 1-2/3,"); // no character after 'length' allowed CheckInvalidTryParse("x bytes 1-2/3"); CheckInvalidTryParse("bytes 1-2/3.4"); CheckInvalidTryParse(null); CheckInvalidTryParse(string.Empty); } #region Helper methods private void CheckValidParse(string input, ContentRangeHeaderValue expectedResult) { ContentRangeHeaderValue result = ContentRangeHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>(() => { ContentRangeHeaderValue.Parse(input); }); } private void CheckValidTryParse(string input, ContentRangeHeaderValue expectedResult) { ContentRangeHeaderValue result = null; Assert.True(ContentRangeHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input) { ContentRangeHeaderValue result = null; Assert.False(ContentRangeHeaderValue.TryParse(input, out result)); Assert.Null(result); } private static void CallGetContentRangeLength(string input, int startIndex, int expectedLength, out ContentRangeHeaderValue result) { object temp = null; Assert.Equal(expectedLength, ContentRangeHeaderValue.GetContentRangeLength(input, startIndex, out temp)); result = temp as ContentRangeHeaderValue; } private static void CheckInvalidGetContentRangeLength(string input, int startIndex) { object result = null; Assert.Equal(0, ContentRangeHeaderValue.GetContentRangeLength(input, startIndex, out result)); Assert.Null(result); } #endregion } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using vector = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Vector3; using rotation = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Quaternion; using LSLInteger = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLInteger; using Aurora.ScriptEngine.AuroraDotNetEngine; using Aurora.ScriptEngine.AuroraDotNetEngine.APIs.Interfaces; using Aurora.ScriptEngine.AuroraDotNetEngine.CompilerTools; namespace Aurora.ScriptEngine.AuroraDotNetEngine.Runtime { public partial class ScriptBaseClass { // LSL CONSTANTS public static readonly LSLInteger TRUE = new LSLInteger(1); public static readonly LSLInteger FALSE = new LSLInteger(0); public static readonly LSLInteger STATUS_PHYSICS = 1; public static readonly LSLInteger STATUS_ROTATE_X = 2; public static readonly LSLInteger STATUS_ROTATE_Y = 4; public static readonly LSLInteger STATUS_ROTATE_Z = 8; public static readonly LSLInteger STATUS_PHANTOM = 16; public static readonly LSLInteger STATUS_SANDBOX = 32; public static readonly LSLInteger STATUS_BLOCK_GRAB = 64; public static readonly LSLInteger STATUS_DIE_AT_EDGE = 128; public static readonly LSLInteger STATUS_RETURN_AT_EDGE = 256; public static readonly LSLInteger STATUS_CAST_SHADOWS = 512; public static readonly LSLInteger AGENT = 1; public static readonly LSLInteger ACTIVE = 2; public static readonly LSLInteger PASSIVE = 4; public static readonly LSLInteger SCRIPTED = 8; public static readonly LSLInteger CONTROL_FWD = 1; public static readonly LSLInteger CONTROL_BACK = 2; public static readonly LSLInteger CONTROL_LEFT = 4; public static readonly LSLInteger CONTROL_RIGHT = 8; public static readonly LSLInteger CONTROL_UP = 16; public static readonly LSLInteger CONTROL_DOWN = 32; public static readonly LSLInteger CONTROL_ROT_LEFT = 256; public static readonly LSLInteger CONTROL_ROT_RIGHT = 512; public static readonly LSLInteger CONTROL_LBUTTON = 268435456; public static readonly LSLInteger CONTROL_ML_LBUTTON = 1073741824; //Permissions public static readonly LSLInteger PERMISSION_DEBIT = 2; public static readonly LSLInteger PERMISSION_TAKE_CONTROLS = 4; public static readonly LSLInteger PERMISSION_REMAP_CONTROLS = 8; public static readonly LSLInteger PERMISSION_TRIGGER_ANIMATION = 16; public static readonly LSLInteger PERMISSION_ATTACH = 32; public static readonly LSLInteger PERMISSION_RELEASE_OWNERSHIP = 64; public static readonly LSLInteger PERMISSION_CHANGE_LINKS = 128; public static readonly LSLInteger PERMISSION_CHANGE_JOINTS = 256; public static readonly LSLInteger PERMISSION_CHANGE_PERMISSIONS = 512; public static readonly LSLInteger PERMISSION_TRACK_CAMERA = 1024; public static readonly LSLInteger PERMISSION_CONTROL_CAMERA = 2048; public static readonly LSLInteger PERMISSION_COMBAT = 8196; public static readonly LSLInteger AGENT_FLYING = 1; public static readonly LSLInteger AGENT_ATTACHMENTS = 2; public static readonly LSLInteger AGENT_SCRIPTED = 4; public static readonly LSLInteger AGENT_MOUSELOOK = 8; public static readonly LSLInteger AGENT_SITTING = 16; public static readonly LSLInteger AGENT_ON_OBJECT = 32; public static readonly LSLInteger AGENT_AWAY = 64; public static readonly LSLInteger AGENT_WALKING = 128; public static readonly LSLInteger AGENT_IN_AIR = 256; public static readonly LSLInteger AGENT_TYPING = 512; public static readonly LSLInteger AGENT_CROUCHING = 1024; public static readonly LSLInteger AGENT_BUSY = 2048; public static readonly LSLInteger AGENT_ALWAYS_RUN = 4096; //Particle Systems public static readonly LSLInteger PSYS_PART_INTERP_COLOR_MASK = 1; public static readonly LSLInteger PSYS_PART_INTERP_SCALE_MASK = 2; public static readonly LSLInteger PSYS_PART_BOUNCE_MASK = 4; public static readonly LSLInteger PSYS_PART_WIND_MASK = 8; public static readonly LSLInteger PSYS_PART_FOLLOW_SRC_MASK = 16; public static readonly LSLInteger PSYS_PART_FOLLOW_VELOCITY_MASK = 32; public static readonly LSLInteger PSYS_PART_TARGET_POS_MASK = 64; public static readonly LSLInteger PSYS_PART_TARGET_LINEAR_MASK = 128; public static readonly LSLInteger PSYS_PART_EMISSIVE_MASK = 256; public static readonly LSLInteger PSYS_PART_FLAGS = 0; public static readonly LSLInteger PSYS_PART_START_COLOR = 1; public static readonly LSLInteger PSYS_PART_START_ALPHA = 2; public static readonly LSLInteger PSYS_PART_END_COLOR = 3; public static readonly LSLInteger PSYS_PART_END_ALPHA = 4; public static readonly LSLInteger PSYS_PART_START_SCALE = 5; public static readonly LSLInteger PSYS_PART_END_SCALE = 6; public static readonly LSLInteger PSYS_PART_MAX_AGE = 7; public static readonly LSLInteger PSYS_SRC_ACCEL = 8; public static readonly LSLInteger PSYS_SRC_PATTERN = 9; public static readonly LSLInteger PSYS_SRC_INNERANGLE = 10; public static readonly LSLInteger PSYS_SRC_OUTERANGLE = 11; public static readonly LSLInteger PSYS_SRC_TEXTURE = 12; public static readonly LSLInteger PSYS_SRC_BURST_RATE = 13; public static readonly LSLInteger PSYS_SRC_BURST_PART_COUNT = 15; public static readonly LSLInteger PSYS_SRC_BURST_RADIUS = 16; public static readonly LSLInteger PSYS_SRC_BURST_SPEED_MIN = 17; public static readonly LSLInteger PSYS_SRC_BURST_SPEED_MAX = 18; public static readonly LSLInteger PSYS_SRC_MAX_AGE = 19; public static readonly LSLInteger PSYS_SRC_TARGET_KEY = 20; public static readonly LSLInteger PSYS_SRC_OMEGA = 21; public static readonly LSLInteger PSYS_SRC_ANGLE_BEGIN = 22; public static readonly LSLInteger PSYS_SRC_ANGLE_END = 23; public static readonly LSLInteger PSYS_SRC_PATTERN_DROP = 1; public static readonly LSLInteger PSYS_SRC_PATTERN_EXPLODE = 2; public static readonly LSLInteger PSYS_SRC_PATTERN_ANGLE = 4; public static readonly LSLInteger PSYS_SRC_PATTERN_ANGLE_CONE = 8; public static readonly LSLInteger PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY = 16; public static readonly LSLInteger VEHICLE_TYPE_NONE = 0; public static readonly LSLInteger VEHICLE_TYPE_SLED = 1; public static readonly LSLInteger VEHICLE_TYPE_CAR = 2; public static readonly LSLInteger VEHICLE_TYPE_BOAT = 3; public static readonly LSLInteger VEHICLE_TYPE_AIRPLANE = 4; public static readonly LSLInteger VEHICLE_TYPE_BALLOON = 5; public static readonly LSLInteger VEHICLE_LINEAR_FRICTION_TIMESCALE = 16; public static readonly LSLInteger VEHICLE_ANGULAR_FRICTION_TIMESCALE = 17; public static readonly LSLInteger VEHICLE_LINEAR_MOTOR_DIRECTION = 18; public static readonly LSLInteger VEHICLE_LINEAR_MOTOR_OFFSET = 20; public static readonly LSLInteger VEHICLE_ANGULAR_MOTOR_DIRECTION = 19; public static readonly LSLInteger VEHICLE_HOVER_HEIGHT = 24; public static readonly LSLInteger VEHICLE_HOVER_EFFICIENCY = 25; public static readonly LSLInteger VEHICLE_HOVER_TIMESCALE = 26; public static readonly LSLInteger VEHICLE_BUOYANCY = 27; public static readonly LSLInteger VEHICLE_LINEAR_DEFLECTION_EFFICIENCY = 28; public static readonly LSLInteger VEHICLE_LINEAR_DEFLECTION_TIMESCALE = 29; public static readonly LSLInteger VEHICLE_LINEAR_MOTOR_TIMESCALE = 30; public static readonly LSLInteger VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE = 31; public static readonly LSLInteger VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY = 32; public static readonly LSLInteger VEHICLE_ANGULAR_DEFLECTION_TIMESCALE = 33; public static readonly LSLInteger VEHICLE_ANGULAR_MOTOR_TIMESCALE = 34; public static readonly LSLInteger VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE = 35; public static readonly LSLInteger VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY = 36; public static readonly LSLInteger VEHICLE_VERTICAL_ATTRACTION_TIMESCALE = 37; public static readonly LSLInteger VEHICLE_BANKING_EFFICIENCY = 38; public static readonly LSLInteger VEHICLE_BANKING_MIX = 39; public static readonly LSLInteger VEHICLE_BANKING_TIMESCALE = 40; public static readonly LSLInteger VEHICLE_REFERENCE_FRAME = 44; public static readonly LSLInteger VEHICLE_RANGE_BLOCK = 45; public static readonly LSLInteger VEHICLE_ROLL_FRAME = 46; public static readonly LSLInteger VEHICLE_FLAG_NO_DEFLECTION_UP = 1; public static readonly LSLInteger VEHICLE_FLAG_LIMIT_ROLL_ONLY = 2; public static readonly LSLInteger VEHICLE_FLAG_HOVER_WATER_ONLY = 4; public static readonly LSLInteger VEHICLE_FLAG_HOVER_TERRAIN_ONLY = 8; public static readonly LSLInteger VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT = 16; public static readonly LSLInteger VEHICLE_FLAG_HOVER_UP_ONLY = 32; public static readonly LSLInteger VEHICLE_FLAG_LIMIT_MOTOR_UP = 64; public static readonly LSLInteger VEHICLE_FLAG_MOUSELOOK_STEER = 128; public static readonly LSLInteger VEHICLE_FLAG_MOUSELOOK_BANK = 256; public static readonly LSLInteger VEHICLE_FLAG_CAMERA_DECOUPLED = 512; public static readonly LSLInteger VEHICLE_FLAG_NO_X = 1024; public static readonly LSLInteger VEHICLE_FLAG_NO_Y = 2048; public static readonly LSLInteger VEHICLE_FLAG_NO_Z = 4096; public static readonly LSLInteger VEHICLE_FLAG_LOCK_HOVER_HEIGHT = 8192; public static readonly LSLInteger VEHICLE_FLAG_NO_DEFLECTION = 16392; public static readonly LSLInteger VEHICLE_FLAG_LOCK_ROTATION = 32784; public static readonly LSLInteger INVENTORY_ALL = -1; public static readonly LSLInteger INVENTORY_NONE = -1; public static readonly LSLInteger INVENTORY_TEXTURE = 0; public static readonly LSLInteger INVENTORY_SOUND = 1; public static readonly LSLInteger INVENTORY_LANDMARK = 3; public static readonly LSLInteger INVENTORY_CLOTHING = 5; public static readonly LSLInteger INVENTORY_OBJECT = 6; public static readonly LSLInteger INVENTORY_NOTECARD = 7; public static readonly LSLInteger INVENTORY_SCRIPT = 10; public static readonly LSLInteger INVENTORY_BODYPART = 13; public static readonly LSLInteger INVENTORY_ANIMATION = 20; public static readonly LSLInteger INVENTORY_GESTURE = 21; public static readonly LSLInteger ATTACH_CHEST = 1; public static readonly LSLInteger ATTACH_HEAD = 2; public static readonly LSLInteger ATTACH_LSHOULDER = 3; public static readonly LSLInteger ATTACH_RSHOULDER = 4; public static readonly LSLInteger ATTACH_LHAND = 5; public static readonly LSLInteger ATTACH_RHAND = 6; public static readonly LSLInteger ATTACH_LFOOT = 7; public static readonly LSLInteger ATTACH_RFOOT = 8; public static readonly LSLInteger ATTACH_BACK = 9; public static readonly LSLInteger ATTACH_PELVIS = 10; public static readonly LSLInteger ATTACH_MOUTH = 11; public static readonly LSLInteger ATTACH_CHIN = 12; public static readonly LSLInteger ATTACH_LEAR = 13; public static readonly LSLInteger ATTACH_REAR = 14; public static readonly LSLInteger ATTACH_LEYE = 15; public static readonly LSLInteger ATTACH_REYE = 16; public static readonly LSLInteger ATTACH_NOSE = 17; public static readonly LSLInteger ATTACH_RUARM = 18; public static readonly LSLInteger ATTACH_RLARM = 19; public static readonly LSLInteger ATTACH_LUARM = 20; public static readonly LSLInteger ATTACH_LLARM = 21; public static readonly LSLInteger ATTACH_RHIP = 22; public static readonly LSLInteger ATTACH_RULEG = 23; public static readonly LSLInteger ATTACH_RLLEG = 24; public static readonly LSLInteger ATTACH_LHIP = 25; public static readonly LSLInteger ATTACH_LULEG = 26; public static readonly LSLInteger ATTACH_LLLEG = 27; public static readonly LSLInteger ATTACH_BELLY = 28; public static readonly LSLInteger ATTACH_RPEC = 29; public static readonly LSLInteger ATTACH_LPEC = 30; public static readonly LSLInteger ATTACH_HUD_CENTER_2 = 31; public static readonly LSLInteger ATTACH_HUD_TOP_RIGHT = 32; public static readonly LSLInteger ATTACH_HUD_TOP_CENTER = 33; public static readonly LSLInteger ATTACH_HUD_TOP_LEFT = 34; public static readonly LSLInteger ATTACH_HUD_CENTER_1 = 35; public static readonly LSLInteger ATTACH_HUD_BOTTOM_LEFT = 36; public static readonly LSLInteger ATTACH_HUD_BOTTOM = 37; public static readonly LSLInteger ATTACH_HUD_BOTTOM_RIGHT = 38; public static readonly LSLInteger LAND_LEVEL = 0; public static readonly LSLInteger LAND_RAISE = 1; public static readonly LSLInteger LAND_LOWER = 2; public static readonly LSLInteger LAND_SMOOTH = 3; public static readonly LSLInteger LAND_NOISE = 4; public static readonly LSLInteger LAND_REVERT = 5; public static readonly LSLInteger LAND_SMALL_BRUSH = 1; public static readonly LSLInteger LAND_MEDIUM_BRUSH = 2; public static readonly LSLInteger LAND_LARGE_BRUSH = 3; //Agent Dataserver public static readonly LSLInteger DATA_ONLINE = 1; public static readonly LSLInteger DATA_NAME = 2; public static readonly LSLInteger DATA_BORN = 3; public static readonly LSLInteger DATA_RATING = 4; public static readonly LSLInteger DATA_SIM_POS = 5; public static readonly LSLInteger DATA_SIM_STATUS = 6; public static readonly LSLInteger DATA_SIM_RATING = 7; public static readonly LSLInteger DATA_PAYINFO = 8; public static readonly LSLInteger DATA_SIM_RELEASE = 128; public static readonly LSLInteger ANIM_ON = 1; public static readonly LSLInteger LOOP = 2; public static readonly LSLInteger REVERSE = 4; public static readonly LSLInteger PING_PONG = 8; public static readonly LSLInteger SMOOTH = 16; public static readonly LSLInteger ROTATE = 32; public static readonly LSLInteger SCALE = 64; public static readonly LSLInteger ALL_SIDES = -1; public static readonly LSLInteger LINK_SET = -1; public static readonly LSLInteger LINK_ROOT = 1; public static readonly LSLInteger LINK_ALL_OTHERS = -2; public static readonly LSLInteger LINK_ALL_CHILDREN = -3; public static readonly LSLInteger LINK_THIS = -4; public static readonly LSLInteger CHANGED_INVENTORY = 1; public static readonly LSLInteger CHANGED_COLOR = 2; public static readonly LSLInteger CHANGED_SHAPE = 4; public static readonly LSLInteger CHANGED_SCALE = 8; public static readonly LSLInteger CHANGED_TEXTURE = 16; public static readonly LSLInteger CHANGED_LINK = 32; public static readonly LSLInteger CHANGED_ALLOWED_DROP = 64; public static readonly LSLInteger CHANGED_OWNER = 128; public static readonly LSLInteger CHANGED_REGION = 256; public static readonly LSLInteger CHANGED_TELEPORT = 512; public static readonly LSLInteger CHANGED_REGION_RESTART = 1024; public static readonly LSLInteger CHANGED_REGION_START = 1024; //LL Changed the constant from CHANGED_REGION_RESTART public static readonly LSLInteger CHANGED_MEDIA = 2048; public static readonly LSLInteger CHANGED_ANIMATION = 16384; public static readonly LSLInteger CHANGED_STATE = 32768; public static readonly LSLInteger TYPE_INVALID = 0; public static readonly LSLInteger TYPE_INTEGER = 1; public static readonly LSLInteger TYPE_FLOAT = 2; public static readonly LSLInteger TYPE_STRING = 3; public static readonly LSLInteger TYPE_KEY = 4; public static readonly LSLInteger TYPE_VECTOR = 5; public static readonly LSLInteger TYPE_ROTATION = 6; //XML RPC Remote Data Channel public static readonly LSLInteger REMOTE_DATA_CHANNEL = 1; public static readonly LSLInteger REMOTE_DATA_REQUEST = 2; public static readonly LSLInteger REMOTE_DATA_REPLY = 3; //llHTTPRequest public static readonly LSLInteger HTTP_METHOD = 0; public static readonly LSLInteger HTTP_MIMETYPE = 1; public static readonly LSLInteger HTTP_BODY_MAXLENGTH = 2; public static readonly LSLInteger HTTP_VERIFY_CERT = 3; public static readonly LSLInteger PRIM_MATERIAL = 2; public static readonly LSLInteger PRIM_PHYSICS = 3; public static readonly LSLInteger PRIM_TEMP_ON_REZ = 4; public static readonly LSLInteger PRIM_PHANTOM = 5; public static readonly LSLInteger PRIM_POSITION = 6; public static readonly LSLInteger PRIM_SIZE = 7; public static readonly LSLInteger PRIM_ROTATION = 8; public static readonly LSLInteger PRIM_TYPE = 9; public static readonly LSLInteger PRIM_TEXTURE = 17; public static readonly LSLInteger PRIM_COLOR = 18; public static readonly LSLInteger PRIM_BUMP_SHINY = 19; public static readonly LSLInteger PRIM_FULLBRIGHT = 20; public static readonly LSLInteger PRIM_FLEXIBLE = 21; public static readonly LSLInteger PRIM_TEXGEN = 22; public static readonly LSLInteger PRIM_POINT_LIGHT = 23; // Huh? public static readonly LSLInteger PRIM_CAST_SHADOWS = 24; // Not implemented, here for completeness sake public static readonly LSLInteger PRIM_GLOW = 25; public static readonly LSLInteger PRIM_TEXT = 26; public static readonly LSLInteger PRIM_NAME = 27; public static readonly LSLInteger PRIM_DESC = 28; public static readonly LSLInteger PRIM_ROT_LOCAL = 29; public static readonly LSLInteger PRIM_TEXGEN_DEFAULT = 0; public static readonly LSLInteger PRIM_TEXGEN_PLANAR = 1; public static readonly LSLInteger PRIM_TYPE_BOX = 0; public static readonly LSLInteger PRIM_TYPE_CYLINDER = 1; public static readonly LSLInteger PRIM_TYPE_PRISM = 2; public static readonly LSLInteger PRIM_TYPE_SPHERE = 3; public static readonly LSLInteger PRIM_TYPE_TORUS = 4; public static readonly LSLInteger PRIM_TYPE_TUBE = 5; public static readonly LSLInteger PRIM_TYPE_RING = 6; public static readonly LSLInteger PRIM_TYPE_SCULPT = 7; public static readonly LSLInteger PRIM_HOLE_DEFAULT = 0; public static readonly LSLInteger PRIM_HOLE_CIRCLE = 16; public static readonly LSLInteger PRIM_HOLE_SQUARE = 32; public static readonly LSLInteger PRIM_HOLE_TRIANGLE = 48; public static readonly LSLInteger PRIM_MATERIAL_STONE = 0; public static readonly LSLInteger PRIM_MATERIAL_METAL = 1; public static readonly LSLInteger PRIM_MATERIAL_GLASS = 2; public static readonly LSLInteger PRIM_MATERIAL_WOOD = 3; public static readonly LSLInteger PRIM_MATERIAL_FLESH = 4; public static readonly LSLInteger PRIM_MATERIAL_PLASTIC = 5; public static readonly LSLInteger PRIM_MATERIAL_RUBBER = 6; public static readonly LSLInteger PRIM_MATERIAL_LIGHT = 7; public static readonly LSLInteger PRIM_SHINY_NONE = 0; public static readonly LSLInteger PRIM_SHINY_LOW = 1; public static readonly LSLInteger PRIM_SHINY_MEDIUM = 2; public static readonly LSLInteger PRIM_SHINY_HIGH = 3; public static readonly LSLInteger PRIM_BUMP_NONE = 0; public static readonly LSLInteger PRIM_BUMP_BRIGHT = 1; public static readonly LSLInteger PRIM_BUMP_DARK = 2; public static readonly LSLInteger PRIM_BUMP_WOOD = 3; public static readonly LSLInteger PRIM_BUMP_BARK = 4; public static readonly LSLInteger PRIM_BUMP_BRICKS = 5; public static readonly LSLInteger PRIM_BUMP_CHECKER = 6; public static readonly LSLInteger PRIM_BUMP_CONCRETE = 7; public static readonly LSLInteger PRIM_BUMP_TILE = 8; public static readonly LSLInteger PRIM_BUMP_STONE = 9; public static readonly LSLInteger PRIM_BUMP_DISKS = 10; public static readonly LSLInteger PRIM_BUMP_GRAVEL = 11; public static readonly LSLInteger PRIM_BUMP_BLOBS = 12; public static readonly LSLInteger PRIM_BUMP_SIDING = 13; public static readonly LSLInteger PRIM_BUMP_LARGETILE = 14; public static readonly LSLInteger PRIM_BUMP_STUCCO = 15; public static readonly LSLInteger PRIM_BUMP_SUCTION = 16; public static readonly LSLInteger PRIM_BUMP_WEAVE = 17; public static readonly LSLInteger PRIM_SCULPT_TYPE_SPHERE = 1; public static readonly LSLInteger PRIM_SCULPT_TYPE_TORUS = 2; public static readonly LSLInteger PRIM_SCULPT_TYPE_PLANE = 3; public static readonly LSLInteger PRIM_SCULPT_TYPE_CYLINDER = 4; public static readonly LSLInteger MASK_BASE = 0; public static readonly LSLInteger MASK_OWNER = 1; public static readonly LSLInteger MASK_GROUP = 2; public static readonly LSLInteger MASK_EVERYONE = 3; public static readonly LSLInteger MASK_NEXT = 4; public static readonly LSLInteger PERM_TRANSFER = 8192; public static readonly LSLInteger PERM_MODIFY = 16384; public static readonly LSLInteger PERM_COPY = 32768; public static readonly LSLInteger PERM_MOVE = 524288; public static readonly LSLInteger PERM_ALL = 2147483647; public static readonly LSLInteger PARCEL_MEDIA_COMMAND_STOP = 0; public static readonly LSLInteger PARCEL_MEDIA_COMMAND_PAUSE = 1; public static readonly LSLInteger PARCEL_MEDIA_COMMAND_PLAY = 2; public static readonly LSLInteger PARCEL_MEDIA_COMMAND_LOOP = 3; public static readonly LSLInteger PARCEL_MEDIA_COMMAND_TEXTURE = 4; public static readonly LSLInteger PARCEL_MEDIA_COMMAND_URL = 5; public static readonly LSLInteger PARCEL_MEDIA_COMMAND_TIME = 6; public static readonly LSLInteger PARCEL_MEDIA_COMMAND_AGENT = 7; public static readonly LSLInteger PARCEL_MEDIA_COMMAND_UNLOAD = 8; public static readonly LSLInteger PARCEL_MEDIA_COMMAND_AUTO_ALIGN = 9; public static readonly LSLInteger PARCEL_MEDIA_COMMAND_TYPE = 10; public static readonly LSLInteger PARCEL_MEDIA_COMMAND_SIZE = 11; public static readonly LSLInteger PARCEL_MEDIA_COMMAND_DESC = 12; public static readonly LSLInteger PARCEL_MEDIA_COMMAND_LOOP_SET = 13; // constants for llGetPrimMediaParams/llSetPrimMediaParams public static readonly LSLInteger PRIM_MEDIA_ALT_IMAGE_ENABLE = 0; public static readonly LSLInteger PRIM_MEDIA_CONTROLS = 1; public static readonly LSLInteger PRIM_MEDIA_CURRENT_URL = 2; public static readonly LSLInteger PRIM_MEDIA_HOME_URL = 3; public static readonly LSLInteger PRIM_MEDIA_AUTO_LOOP = 4; public static readonly LSLInteger PRIM_MEDIA_AUTO_PLAY = 5; public static readonly LSLInteger PRIM_MEDIA_AUTO_SCALE = 6; public static readonly LSLInteger PRIM_MEDIA_AUTO_ZOOM = 7; public static readonly LSLInteger PRIM_MEDIA_FIRST_CLICK_INTERACT = 8; public static readonly LSLInteger PRIM_MEDIA_WIDTH_PIXELS = 9; public static readonly LSLInteger PRIM_MEDIA_HEIGHT_PIXELS = 10; public static readonly LSLInteger PRIM_MEDIA_WHITELIST_ENABLE = 11; public static readonly LSLInteger PRIM_MEDIA_WHITELIST = 12; public static readonly LSLInteger PRIM_MEDIA_PERMS_INTERACT = 13; public static readonly LSLInteger PRIM_MEDIA_PERMS_CONTROL = 14; public static readonly LSLInteger PRIM_MEDIA_CONTROLS_STANDARD = 0; public static readonly LSLInteger PRIM_MEDIA_CONTROLS_MINI = 1; public static readonly LSLInteger PRIM_MEDIA_PERM_NONE = 0; public static readonly LSLInteger PRIM_MEDIA_PERM_OWNER = 1; public static readonly LSLInteger PRIM_MEDIA_PERM_GROUP = 2; public static readonly LSLInteger PRIM_MEDIA_PERM_ANYONE = 4; // extra constants for llSetPrimMediaParams public static readonly LSLInteger LSL_STATUS_OK = new LSLInteger(0); public static readonly LSLInteger LSL_STATUS_MALFORMED_PARAMS = new LSLInteger(1000); public static readonly LSLInteger LSL_STATUS_TYPE_MISMATCH = new LSLInteger(1001); public static readonly LSLInteger LSL_STATUS_BOUNDS_ERROR = new LSLInteger(1002); public static readonly LSLInteger LSL_STATUS_NOT_FOUND = new LSLInteger(1003); public static readonly LSLInteger LSL_STATUS_NOT_SUPPORTED = new LSLInteger(1004); public static readonly LSLInteger LSL_STATUS_INTERNAL_ERROR = new LSLInteger(1999); public static readonly LSLInteger LSL_STATUS_WHITELIST_FAILED = new LSLInteger(2001); public static readonly LSLInteger PARCEL_FLAG_ALLOW_FLY = 0x1; // parcel allows flying public static readonly LSLInteger PARCEL_FLAG_ALLOW_SCRIPTS = 0x2; // parcel allows outside scripts public static readonly LSLInteger PARCEL_FLAG_ALLOW_LANDMARK = 0x8; // parcel allows landmarks to be created public static readonly LSLInteger PARCEL_FLAG_ALLOW_TERRAFORM = 0x10; // parcel allows anyone to terraform the land public static readonly LSLInteger PARCEL_FLAG_ALLOW_DAMAGE = 0x20; // parcel allows damage public static readonly LSLInteger PARCEL_FLAG_ALLOW_CREATE_OBJECTS = 0x40; // parcel allows anyone to create objects public static readonly LSLInteger PARCEL_FLAG_USE_ACCESS_GROUP = 0x100; // parcel limits access to a group public static readonly LSLInteger PARCEL_FLAG_USE_ACCESS_LIST = 0x200; // parcel limits access to a list of residents public static readonly LSLInteger PARCEL_FLAG_USE_BAN_LIST = 0x400; // parcel uses a ban list, including restricting access based on payment info public static readonly LSLInteger PARCEL_FLAG_USE_LAND_PASS_LIST = 0x800; // parcel allows passes to be purchased public static readonly LSLInteger PARCEL_FLAG_LOCAL_SOUND_ONLY = 0x8000; // parcel restricts spatialized sound to the parcel public static readonly LSLInteger PARCEL_FLAG_RESTRICT_PUSHOBJECT = 0x200000; // parcel restricts llPushObject public static readonly LSLInteger PARCEL_FLAG_ALLOW_GROUP_SCRIPTS = 0x2000000; // parcel allows scripts owned by group public static readonly LSLInteger PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS = 0x4000000; // parcel allows group object creation public static readonly LSLInteger PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY = 0x8000000; // parcel allows objects owned by any user to enter public static readonly LSLInteger PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY = 0x10000000; // parcel allows with the same group to enter public static readonly LSLInteger REGION_FLAG_ALLOW_DAMAGE = 0x1; // region is entirely damage enabled public static readonly LSLInteger REGION_FLAG_FIXED_SUN = 0x10; // region has a fixed sun position public static readonly LSLInteger REGION_FLAG_BLOCK_TERRAFORM = 0x40; // region terraforming disabled public static readonly LSLInteger REGION_FLAG_SANDBOX = 0x100; // region is a sandbox public static readonly LSLInteger REGION_FLAG_DISABLE_COLLISIONS = 0x1000; // region has disabled collisions public static readonly LSLInteger REGION_FLAG_DISABLE_PHYSICS = 0x4000; // region has disabled physics public static readonly LSLInteger REGION_FLAG_BLOCK_FLY = 0x80000; // region blocks flying public static readonly LSLInteger REGION_FLAG_ALLOW_DIRECT_TELEPORT = 0x100000; // region allows direct teleports public static readonly LSLInteger REGION_FLAG_RESTRICT_PUSHOBJECT = 0x400000; // region restricts llPushObject public static readonly LSLInteger PAY_HIDE = new LSLInteger(-1); public static readonly LSLInteger PAY_DEFAULT = new LSLInteger(-2); public static readonly string NULL_KEY = "00000000-0000-0000-0000-000000000000"; public static readonly string EOF = "\n\n\n"; public static readonly double PI = 3.1415926535897932384626433832795; public static readonly double TWO_PI = 6.283185307179586476925286766559; public static readonly double PI_BY_TWO = 1.5707963267948966192313216916398; public static readonly double DEG_TO_RAD = 0.01745329238f; public static readonly double RAD_TO_DEG = 57.29578f; public static readonly double SQRT2 = 1.4142135623730950488016887242097; public static readonly LSLInteger STRING_TRIM_HEAD = 1; public static readonly LSLInteger STRING_TRIM_TAIL = 2; public static readonly LSLInteger STRING_TRIM = 3; public static readonly LSLInteger LIST_STAT_RANGE = 0; public static readonly LSLInteger LIST_STAT_MIN = 1; public static readonly LSLInteger LIST_STAT_MAX = 2; public static readonly LSLInteger LIST_STAT_MEAN = 3; public static readonly LSLInteger LIST_STAT_MEDIAN = 4; public static readonly LSLInteger LIST_STAT_STD_DEV = 5; public static readonly LSLInteger LIST_STAT_SUM = 6; public static readonly LSLInteger LIST_STAT_SUM_SQUARES = 7; public static readonly LSLInteger LIST_STAT_NUM_COUNT = 8; public static readonly LSLInteger LIST_STAT_GEOMETRIC_MEAN = 9; public static readonly LSLInteger LIST_STAT_HARMONIC_MEAN = 100; //ParcelPrim Categories public static readonly LSLInteger PARCEL_COUNT_TOTAL = 0; public static readonly LSLInteger PARCEL_COUNT_OWNER = 1; public static readonly LSLInteger PARCEL_COUNT_GROUP = 2; public static readonly LSLInteger PARCEL_COUNT_OTHER = 3; public static readonly LSLInteger PARCEL_COUNT_SELECTED = 4; public static readonly LSLInteger PARCEL_COUNT_TEMP = 5; public static readonly LSLInteger DEBUG_CHANNEL = 0x7FFFFFFF; public static readonly LSLInteger PUBLIC_CHANNEL = 0x00000000; public static readonly LSLInteger OBJECT_NAME = 1; public static readonly LSLInteger OBJECT_DESC = 2; public static readonly LSLInteger OBJECT_POS = 3; public static readonly LSLInteger OBJECT_ROT = 4; public static readonly LSLInteger OBJECT_VELOCITY = 5; public static readonly LSLInteger OBJECT_OWNER = 6; public static readonly LSLInteger OBJECT_GROUP = 7; public static readonly LSLInteger OBJECT_CREATOR = 8; public static readonly LSLInteger OBJECT_RUNNING_SCRIPT_COUNT = 9; public static readonly LSLInteger OBJECT_TOTAL_SCRIPT_COUNT = 10; public static readonly LSLInteger OBJECT_SCRIPT_MEMORY = 11; public static readonly vector ZERO_VECTOR = new vector(0.0, 0.0, 0.0); public static readonly rotation ZERO_ROTATION = new rotation(0.0, 0.0, 0.0, 1.0); // constants for llSetCameraParams public static readonly LSLInteger CAMERA_PITCH = 0; public static readonly LSLInteger CAMERA_FOCUS_OFFSET = 1; public static readonly LSLInteger CAMERA_FOCUS_OFFSET_X = 2; public static readonly LSLInteger CAMERA_FOCUS_OFFSET_Y = 3; public static readonly LSLInteger CAMERA_FOCUS_OFFSET_Z = 4; public static readonly LSLInteger CAMERA_POSITION_LAG = 5; public static readonly LSLInteger CAMERA_FOCUS_LAG = 6; public static readonly LSLInteger CAMERA_DISTANCE = 7; public static readonly LSLInteger CAMERA_BEHINDNESS_ANGLE = 8; public static readonly LSLInteger CAMERA_BEHINDNESS_LAG = 9; public static readonly LSLInteger CAMERA_POSITION_THRESHOLD = 10; public static readonly LSLInteger CAMERA_FOCUS_THRESHOLD = 11; public static readonly LSLInteger CAMERA_ACTIVE = 12; public static readonly LSLInteger CAMERA_POSITION = 13; public static readonly LSLInteger CAMERA_POSITION_X = 14; public static readonly LSLInteger CAMERA_POSITION_Y = 15; public static readonly LSLInteger CAMERA_POSITION_Z = 16; public static readonly LSLInteger CAMERA_FOCUS = 17; public static readonly LSLInteger CAMERA_FOCUS_X = 18; public static readonly LSLInteger CAMERA_FOCUS_Y = 19; public static readonly LSLInteger CAMERA_FOCUS_Z = 20; public static readonly LSLInteger CAMERA_POSITION_LOCKED = 21; public static readonly LSLInteger CAMERA_FOCUS_LOCKED = 22; // constants for llGetParcelDetails public static readonly LSLInteger PARCEL_DETAILS_NAME = 0; public static readonly LSLInteger PARCEL_DETAILS_DESC = 1; public static readonly LSLInteger PARCEL_DETAILS_OWNER = 2; public static readonly LSLInteger PARCEL_DETAILS_GROUP = 3; public static readonly LSLInteger PARCEL_DETAILS_AREA = 4; public static readonly LSLInteger PARCEL_DETAILS_ID = 5; // constants for llSetClickAction public static readonly LSLInteger CLICK_ACTION_NONE = 0; public static readonly LSLInteger CLICK_ACTION_TOUCH = 0; public static readonly LSLInteger CLICK_ACTION_SIT = 1; public static readonly LSLInteger CLICK_ACTION_BUY = 2; public static readonly LSLInteger CLICK_ACTION_PAY = 3; public static readonly LSLInteger CLICK_ACTION_OPEN = 4; public static readonly LSLInteger CLICK_ACTION_PLAY = 5; public static readonly LSLInteger CLICK_ACTION_OPEN_MEDIA = 6; // constants for the llDetectedTouch* functions public static readonly LSLInteger TOUCH_INVALID_FACE = -1; public static readonly vector TOUCH_INVALID_TEXCOORD = new vector(-1.0, -1.0, 0.0); public static readonly vector TOUCH_INVALID_VECTOR = ZERO_VECTOR; // Constants for default textures public const string TEXTURE_BLANK = "5748decc-f629-461c-9a36-a35a221fe21f"; public const string TEXTURE_DEFAULT = "89556747-24cb-43ed-920b-47caed15465f"; public const string TEXTURE_PLYWOOD = "89556747-24cb-43ed-920b-47caed15465f"; public const string TEXTURE_TRANSPARENT = "8dcd4a48-2d37-4909-9f78-f7a9eb4ef903"; public const string TEXTURE_MEDIA = "8b5fec65-8d8d-9dc5-cda8-8fdf2716e361"; // Constants for osGetRegionStats public static readonly LSLInteger STATS_TIME_DILATION = 0; public static readonly LSLInteger STATS_SIM_FPS = 1; public static readonly LSLInteger STATS_PHYSICS_FPS = 2; public static readonly LSLInteger STATS_AGENT_UPDATES = 3; public static readonly LSLInteger STATS_ROOT_AGENTS = 4; public static readonly LSLInteger STATS_CHILD_AGENTS = 5; public static readonly LSLInteger STATS_TOTAL_PRIMS = 6; public static readonly LSLInteger STATS_ACTIVE_PRIMS = 7; public static readonly LSLInteger STATS_FRAME_MS = 8; public static readonly LSLInteger STATS_NET_MS = 9; public static readonly LSLInteger STATS_PHYSICS_MS = 10; public static readonly LSLInteger STATS_IMAGE_MS = 11; public static readonly LSLInteger STATS_OTHER_MS = 12; public static readonly LSLInteger STATS_IN_PACKETS_PER_SECOND = 13; public static readonly LSLInteger STATS_OUT_PACKETS_PER_SECOND = 14; public static readonly LSLInteger STATS_UNACKED_BYTES = 15; public static readonly LSLInteger STATS_AGENT_MS = 16; public static readonly LSLInteger STATS_PENDING_DOWNLOADS = 17; public static readonly LSLInteger STATS_PENDING_UPLOADS = 18; public static readonly LSLInteger STATS_ACTIVE_SCRIPTS = 19; public static readonly LSLInteger STATS_SCRIPT_LPS = 20; public const string URL_REQUEST_GRANTED = "URL_REQUEST_GRANTED"; public const string URL_REQUEST_DENIED = "URL_REQUEST_DENIED"; public static readonly LSLInteger PASS_IF_NOT_HANDLED = 0; public static readonly LSLInteger PASS_ALWAYS = 1; public static readonly LSLInteger PASS_NEVER = 2; public static readonly LSLInteger RC_REJECT_TYPES = 1; public static readonly LSLInteger RC_DATA_FLAGS = 2; public static readonly LSLInteger RC_MAX_HITS = 3; public static readonly LSLInteger RC_DETECT_PHANTOM = 4; public static readonly LSLInteger RC_REJECT_AGENTS = 1; public static readonly LSLInteger RC_REJECT_PHYSICAL = 2; public static readonly LSLInteger RC_REJECT_NONPHYSICAL = 3; public static readonly LSLInteger RC_REJECT_LAND = 4; public static readonly LSLInteger RC_GET_NORMAL = 1; public static readonly LSLInteger RC_GET_ROOT_KEY = 2; public static readonly LSLInteger RC_GET_LINK_NUM = 3; public static readonly LSLInteger RCERR_CAST_TIME_EXCEEDED = 1; } }
// // UnaryType.cs.cs // // This file was generated by XMLSPY 2004 Enterprise Edition. // // YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE // OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION. // // Refer to the XMLSPY Documentation for further details. // http://www.altova.com/xmlspy // using System; using System.Collections; using System.Xml; using Altova.Types; namespace XMLRules { public class UnaryType : Altova.Node { #region Forward constructors public UnaryType() : base() { SetCollectionParents(); } public UnaryType(XmlDocument doc) : base(doc) { SetCollectionParents(); } public UnaryType(XmlNode node) : base(node) { SetCollectionParents(); } public UnaryType(Altova.Node node) : base(node) { SetCollectionParents(); } #endregion // Forward constructors public override void AdjustPrefix() { int nCount; nCount = DomChildCount(NodeType.Element, "", "UnaryOperator"); for (int i = 0; i < nCount; i++) { XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "UnaryOperator", i); InternalAdjustPrefix(DOMNode, true); new UnaryOperator(DOMNode).AdjustPrefix(); } nCount = DomChildCount(NodeType.Element, "", "LogicalExpression"); for (int i = 0; i < nCount; i++) { XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "LogicalExpression", i); InternalAdjustPrefix(DOMNode, true); new LogicalExpression(DOMNode).AdjustPrefix(); } } #region UnaryOperator accessor methods public int GetUnaryOperatorMinCount() { return 1; } public int UnaryOperatorMinCount { get { return 1; } } public int GetUnaryOperatorMaxCount() { return 1; } public int UnaryOperatorMaxCount { get { return 1; } } public int GetUnaryOperatorCount() { return DomChildCount(NodeType.Element, "", "UnaryOperator"); } public int UnaryOperatorCount { get { return DomChildCount(NodeType.Element, "", "UnaryOperator"); } } public bool HasUnaryOperator() { return HasDomChild(NodeType.Element, "", "UnaryOperator"); } public UnaryOperator GetUnaryOperatorAt(int index) { return new UnaryOperator(GetDomChildAt(NodeType.Element, "", "UnaryOperator", index)); } public UnaryOperator GetUnaryOperator() { return GetUnaryOperatorAt(0); } public UnaryOperator UnaryOperator { get { return GetUnaryOperatorAt(0); } } public void RemoveUnaryOperatorAt(int index) { RemoveDomChildAt(NodeType.Element, "", "UnaryOperator", index); } public void RemoveUnaryOperator() { while (HasUnaryOperator()) RemoveUnaryOperatorAt(0); } public void AddUnaryOperator(UnaryOperator newValue) { AppendDomElement("", "UnaryOperator", newValue); } public void InsertUnaryOperatorAt(UnaryOperator newValue, int index) { InsertDomElementAt("", "UnaryOperator", index, newValue); } public void ReplaceUnaryOperatorAt(UnaryOperator newValue, int index) { ReplaceDomElementAt("", "UnaryOperator", index, newValue); } #endregion // UnaryOperator accessor methods #region UnaryOperator collection public UnaryOperatorCollection MyUnaryOperators = new UnaryOperatorCollection( ); public class UnaryOperatorCollection: IEnumerable { UnaryType parent; public UnaryType Parent { set { parent = value; } } public UnaryOperatorEnumerator GetEnumerator() { return new UnaryOperatorEnumerator(parent); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class UnaryOperatorEnumerator: IEnumerator { int nIndex; UnaryType parent; public UnaryOperatorEnumerator(UnaryType par) { parent = par; nIndex = -1; } public void Reset() { nIndex = -1; } public bool MoveNext() { nIndex++; return(nIndex < parent.UnaryOperatorCount ); } public UnaryOperator Current { get { return(parent.GetUnaryOperatorAt(nIndex)); } } object IEnumerator.Current { get { return(Current); } } } #endregion // UnaryOperator collection #region LogicalExpression accessor methods public int GetLogicalExpressionMinCount() { return 1; } public int LogicalExpressionMinCount { get { return 1; } } public int GetLogicalExpressionMaxCount() { return 1; } public int LogicalExpressionMaxCount { get { return 1; } } public int GetLogicalExpressionCount() { return DomChildCount(NodeType.Element, "", "LogicalExpression"); } public int LogicalExpressionCount { get { return DomChildCount(NodeType.Element, "", "LogicalExpression"); } } public bool HasLogicalExpression() { return HasDomChild(NodeType.Element, "", "LogicalExpression"); } public LogicalExpression GetLogicalExpressionAt(int index) { return new LogicalExpression(GetDomChildAt(NodeType.Element, "", "LogicalExpression", index)); } public LogicalExpression GetLogicalExpression() { return GetLogicalExpressionAt(0); } public LogicalExpression LogicalExpression { get { return GetLogicalExpressionAt(0); } } public void RemoveLogicalExpressionAt(int index) { RemoveDomChildAt(NodeType.Element, "", "LogicalExpression", index); } public void RemoveLogicalExpression() { while (HasLogicalExpression()) RemoveLogicalExpressionAt(0); } public void AddLogicalExpression(LogicalExpression newValue) { AppendDomElement("", "LogicalExpression", newValue); } public void InsertLogicalExpressionAt(LogicalExpression newValue, int index) { InsertDomElementAt("", "LogicalExpression", index, newValue); } public void ReplaceLogicalExpressionAt(LogicalExpression newValue, int index) { ReplaceDomElementAt("", "LogicalExpression", index, newValue); } #endregion // LogicalExpression accessor methods #region LogicalExpression collection public LogicalExpressionCollection MyLogicalExpressions = new LogicalExpressionCollection( ); public class LogicalExpressionCollection: IEnumerable { UnaryType parent; public UnaryType Parent { set { parent = value; } } public LogicalExpressionEnumerator GetEnumerator() { return new LogicalExpressionEnumerator(parent); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class LogicalExpressionEnumerator: IEnumerator { int nIndex; UnaryType parent; public LogicalExpressionEnumerator(UnaryType par) { parent = par; nIndex = -1; } public void Reset() { nIndex = -1; } public bool MoveNext() { nIndex++; return(nIndex < parent.LogicalExpressionCount ); } public LogicalExpression Current { get { return(parent.GetLogicalExpressionAt(nIndex)); } } object IEnumerator.Current { get { return(Current); } } } #endregion // LogicalExpression collection private void SetCollectionParents() { MyUnaryOperators.Parent = this; MyLogicalExpressions.Parent = this; } } }
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using IServiceProvider = System.IServiceProvider; using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants; namespace Microsoft.VisualStudio.Project { /// <summary> /// This abstract class handles opening, saving of items in the hierarchy. /// </summary> [CLSCompliant(false)] public abstract class DocumentManager { #region fields private HierarchyNode node = null; #endregion #region properties protected HierarchyNode Node { get { return this.node; } } #endregion #region ctors protected DocumentManager(HierarchyNode node) { this.node = node; } #endregion #region virtual methods /// <summary> /// Open a document using the standard editor. This method has no implementation since a document is abstract in this context /// </summary> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="windowFrame">A reference to the window frame that is mapped to the document</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>NotImplementedException</returns> /// <remarks>See FileDocumentManager class for an implementation of this method</remarks> public virtual int Open(ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) { throw new NotImplementedException(); } /// <summary> /// Open a document using a specific editor. This method has no implementation. /// </summary> /// <param name="editorFlags">Specifies actions to take when opening a specific editor. Possible editor flags are defined in the enumeration Microsoft.VisualStudio.Shell.Interop.__VSOSPEFLAGS</param> /// <param name="editorType">Unique identifier of the editor type</param> /// <param name="physicalView">Name of the physical view. If null, the environment calls MapLogicalView on the editor factory to determine the physical view that corresponds to the logical view. In this case, null does not specify the primary view, but rather indicates that you do not know which view corresponds to the logical view</param> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="frame">A reference to the window frame that is mapped to the document</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>NotImplementedException</returns> /// <remarks>See FileDocumentManager for an implementation of this method</remarks> public virtual int OpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame, WindowFrameShowAction windowFrameAction) { throw new NotImplementedException(); } /// <summary> /// Close an open document window /// </summary> /// <param name="closeFlag">Decides how to close the document</param> /// <returns>S_OK if successful, otherwise an error is returned</returns> public virtual int Close(__FRAMECLOSE closeFlag) { if(this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed) { return VSConstants.E_FAIL; } // Get info about the document bool isDirty, isOpen, isOpenedByUs; uint docCookie; IVsPersistDocData ppIVsPersistDocData; this.GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out ppIVsPersistDocData); if(isOpenedByUs) { IVsUIShellOpenDocument shell = this.Node.ProjectMgr.Site.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; Guid logicalView = Guid.Empty; uint grfIDO = 0; IVsUIHierarchy pHierOpen; uint[] itemIdOpen = new uint[1]; IVsWindowFrame windowFrame; int fOpen; ErrorHandler.ThrowOnFailure(shell.IsDocumentOpen(this.Node.ProjectMgr, this.Node.ID, this.Node.Url, ref logicalView, grfIDO, out pHierOpen, itemIdOpen, out windowFrame, out fOpen)); if(windowFrame != null) { docCookie = 0; return windowFrame.CloseFrame((uint)closeFlag); } } return VSConstants.S_OK; } /// <summary> /// Silently saves an open document /// </summary> /// <param name="saveIfDirty">Save the open document only if it is dirty</param> /// <remarks>The call to SaveDocData may return Microsoft.VisualStudio.Shell.Interop.PFF_RESULTS.STG_S_DATALOSS to indicate some characters could not be represented in the current codepage</remarks> public virtual void Save(bool saveIfDirty) { bool isDirty, isOpen, isOpenedByUs; uint docCookie; IVsPersistDocData persistDocData; this.GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out persistDocData); if(isDirty && saveIfDirty && persistDocData != null) { string name; int cancelled; ErrorHandler.ThrowOnFailure(persistDocData.SaveDocData(VSSAVEFLAGS.VSSAVE_SilentSave, out name, out cancelled)); } } #endregion #region helper methods /// <summary> /// Get document properties from RDT /// </summary> internal void GetDocInfo( out bool isOpen, // true if the doc is opened out bool isDirty, // true if the doc is dirty out bool isOpenedByUs, // true if opened by our project out uint docCookie, // VSDOCCOOKIE if open out IVsPersistDocData persistDocData) { isOpen = isDirty = isOpenedByUs = false; docCookie = (uint)ShellConstants.VSDOCCOOKIE_NIL; persistDocData = null; if(this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed) { return; } IVsHierarchy hierarchy; uint vsitemid = VSConstants.VSITEMID_NIL; VsShellUtilities.GetRDTDocumentInfo(this.node.ProjectMgr.Site, this.node.Url, out hierarchy, out vsitemid, out persistDocData, out docCookie); if(hierarchy == null || docCookie == (uint)ShellConstants.VSDOCCOOKIE_NIL) { return; } isOpen = true; // check if the doc is opened by another project if(Utilities.IsSameComObject(this.node.ProjectMgr, hierarchy)) { isOpenedByUs = true; } if(persistDocData != null) { int isDocDataDirty; ErrorHandler.ThrowOnFailure(persistDocData.IsDocDataDirty(out isDocDataDirty)); isDirty = (isDocDataDirty != 0); } } protected string GetOwnerCaption() { Debug.Assert(this.node != null, "No node has been initialized for the document manager"); object pvar; ErrorHandler.ThrowOnFailure(this.node.GetProperty(this.node.ID, (int)__VSHPROPID.VSHPROPID_Caption, out pvar)); return (pvar as string); } protected static void CloseWindowFrame(ref IVsWindowFrame windowFrame) { if(windowFrame != null) { try { ErrorHandler.ThrowOnFailure(windowFrame.CloseFrame(0)); } finally { windowFrame = null; } } } protected string GetFullPathForDocument() { string fullPath = String.Empty; Debug.Assert(this.node != null, "No node has been initialized for the document manager"); // Get the URL representing the item fullPath = this.node.GetMkDocument(); Debug.Assert(!String.IsNullOrEmpty(fullPath), "Could not retrive the fullpath for the node" + this.Node.ID.ToString(CultureInfo.CurrentCulture)); return fullPath; } #endregion #region static methods /// <summary> /// Updates the caption for all windows associated to the document. /// </summary> /// <param name="site">The service provider.</param> /// <param name="caption">The new caption.</param> /// <param name="docData">The IUnknown interface to a document data object associated with a registered document.</param> public static void UpdateCaption(IServiceProvider site, string caption, IntPtr docData) { if(site == null) { throw new ArgumentNullException("site"); } if(String.IsNullOrEmpty(caption)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "caption"); } IVsUIShell uiShell = site.GetService(typeof(SVsUIShell)) as IVsUIShell; // We need to tell the windows to update their captions. IEnumWindowFrames windowFramesEnum; ErrorHandler.ThrowOnFailure(uiShell.GetDocumentWindowEnum(out windowFramesEnum)); IVsWindowFrame[] windowFrames = new IVsWindowFrame[1]; uint fetched; while(windowFramesEnum.Next(1, windowFrames, out fetched) == VSConstants.S_OK && fetched == 1) { IVsWindowFrame windowFrame = windowFrames[0]; object data; ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out data)); IntPtr ptr = Marshal.GetIUnknownForObject(data); try { if(ptr == docData) { ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID.VSFPROPID_OwnerCaption, caption)); } } finally { if(ptr != IntPtr.Zero) { Marshal.Release(ptr); } } } } /// <summary> /// Rename document in the running document table from oldName to newName. /// </summary> /// <param name="provider">The service provider.</param> /// <param name="oldName">Full path to the old name of the document.</param> /// <param name="newName">Full path to the new name of the document.</param> /// <param name="newItemId">The new item id of the document</param> public static void RenameDocument(IServiceProvider site, string oldName, string newName, uint newItemId) { if(site == null) { throw new ArgumentNullException("site"); } if(String.IsNullOrEmpty(oldName)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "oldName"); } if(String.IsNullOrEmpty(newName)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "newName"); } if(newItemId == VSConstants.VSITEMID_NIL) { throw new ArgumentNullException("newItemId"); } IVsRunningDocumentTable pRDT = site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; IVsUIShellOpenDocument doc = site.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if(pRDT == null || doc == null) return; IVsHierarchy pIVsHierarchy; uint itemId; IntPtr docData; uint uiVsDocCookie; ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie)); if(docData != IntPtr.Zero) { try { IntPtr pUnk = Marshal.GetIUnknownForObject(pIVsHierarchy); Guid iid = typeof(IVsHierarchy).GUID; IntPtr pHier; Marshal.QueryInterface(pUnk, ref iid, out pHier); try { ErrorHandler.ThrowOnFailure(pRDT.RenameDocument(oldName, newName, pHier, newItemId)); } finally { if(pHier != IntPtr.Zero) Marshal.Release(pHier); if(pUnk != IntPtr.Zero) Marshal.Release(pUnk); } } finally { Marshal.Release(docData); } } } #endregion } }
using System; using System.Diagnostics; namespace Lucene.Net.Codecs.Lucene40 { using Lucene.Net.Support; using AtomicReader = Lucene.Net.Index.AtomicReader; using Bits = Lucene.Net.Util.Bits; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; /// <summary> /// Copyright 2004 The Apache Software 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. /// </summary> using Document = Documents.Document; using FieldInfo = Lucene.Net.Index.FieldInfo; using FieldInfos = Lucene.Net.Index.FieldInfos; using IndexableField = Lucene.Net.Index.IndexableField; using IndexFileNames = Lucene.Net.Index.IndexFileNames; using IndexInput = Lucene.Net.Store.IndexInput; using IndexOutput = Lucene.Net.Store.IndexOutput; using IOContext = Lucene.Net.Store.IOContext; using IOUtils = Lucene.Net.Util.IOUtils; using MergeState = Lucene.Net.Index.MergeState; using SegmentReader = Lucene.Net.Index.SegmentReader; /// <summary> /// Class responsible for writing stored document fields. /// <p/> /// It uses &lt;segment&gt;.fdt and &lt;segment&gt;.fdx; files. /// </summary> /// <seealso cref= Lucene40StoredFieldsFormat /// @lucene.experimental </seealso> public sealed class Lucene40StoredFieldsWriter : StoredFieldsWriter { // NOTE: bit 0 is free here! You can steal it! internal static readonly int FIELD_IS_BINARY = 1 << 1; // the old bit 1 << 2 was compressed, is now left out private const int _NUMERIC_BIT_SHIFT = 3; internal static readonly int FIELD_IS_NUMERIC_MASK = 0x07 << _NUMERIC_BIT_SHIFT; internal const int FIELD_IS_NUMERIC_INT = 1 << _NUMERIC_BIT_SHIFT; internal const int FIELD_IS_NUMERIC_LONG = 2 << _NUMERIC_BIT_SHIFT; internal const int FIELD_IS_NUMERIC_FLOAT = 3 << _NUMERIC_BIT_SHIFT; internal const int FIELD_IS_NUMERIC_DOUBLE = 4 << _NUMERIC_BIT_SHIFT; // the next possible bits are: 1 << 6; 1 << 7 // currently unused: static final int FIELD_IS_NUMERIC_SHORT = 5 << _NUMERIC_BIT_SHIFT; // currently unused: static final int FIELD_IS_NUMERIC_BYTE = 6 << _NUMERIC_BIT_SHIFT; internal const string CODEC_NAME_IDX = "Lucene40StoredFieldsIndex"; internal const string CODEC_NAME_DAT = "Lucene40StoredFieldsData"; internal const int VERSION_START = 0; internal const int VERSION_CURRENT = VERSION_START; internal static readonly long HEADER_LENGTH_IDX = CodecUtil.HeaderLength(CODEC_NAME_IDX); internal static readonly long HEADER_LENGTH_DAT = CodecUtil.HeaderLength(CODEC_NAME_DAT); /// <summary> /// Extension of stored fields file </summary> public const string FIELDS_EXTENSION = "fdt"; /// <summary> /// Extension of stored fields index file </summary> public const string FIELDS_INDEX_EXTENSION = "fdx"; private readonly Directory Directory; private readonly string Segment; private IndexOutput FieldsStream; private IndexOutput IndexStream; /// <summary> /// Sole constructor. </summary> public Lucene40StoredFieldsWriter(Directory directory, string segment, IOContext context) { Debug.Assert(directory != null); this.Directory = directory; this.Segment = segment; bool success = false; try { FieldsStream = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, "", FIELDS_EXTENSION), context); IndexStream = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, "", FIELDS_INDEX_EXTENSION), context); CodecUtil.WriteHeader(FieldsStream, CODEC_NAME_DAT, VERSION_CURRENT); CodecUtil.WriteHeader(IndexStream, CODEC_NAME_IDX, VERSION_CURRENT); Debug.Assert(HEADER_LENGTH_DAT == FieldsStream.FilePointer); Debug.Assert(HEADER_LENGTH_IDX == IndexStream.FilePointer); success = true; } finally { if (!success) { Abort(); } } } // Writes the contents of buffer into the fields stream // and adds a new entry for this document into the index // stream. this assumes the buffer was already written // in the correct fields format. public override void StartDocument(int numStoredFields) { IndexStream.WriteLong(FieldsStream.FilePointer); FieldsStream.WriteVInt(numStoredFields); } protected override void Dispose(bool disposing) { if (disposing) { try { IOUtils.Close(FieldsStream, IndexStream); } finally { FieldsStream = IndexStream = null; } } } public override void Abort() { try { Dispose(); } catch (Exception) { } IOUtils.DeleteFilesIgnoringExceptions(Directory, IndexFileNames.SegmentFileName(Segment, "", FIELDS_EXTENSION), IndexFileNames.SegmentFileName(Segment, "", FIELDS_INDEX_EXTENSION)); } public override void WriteField(FieldInfo info, IndexableField field) { FieldsStream.WriteVInt(info.Number); int bits = 0; BytesRef bytes; string @string; // TODO: maybe a field should serialize itself? // this way we don't bake into indexer all these // specific encodings for different fields? and apps // can customize... object number = (object)field.NumericValue; if (number != null) { if (number is sbyte || number is short || number is int) { bits |= FIELD_IS_NUMERIC_INT; } else if (number is long) { bits |= FIELD_IS_NUMERIC_LONG; } else if (number is float) { bits |= FIELD_IS_NUMERIC_FLOAT; } else if (number is double) { bits |= FIELD_IS_NUMERIC_DOUBLE; } else { throw new System.ArgumentException("cannot store numeric type " + number.GetType()); } @string = null; bytes = null; } else { bytes = field.BinaryValue(); if (bytes != null) { bits |= FIELD_IS_BINARY; @string = null; } else { @string = field.StringValue; if (@string == null) { throw new System.ArgumentException("field " + field.Name() + " is stored but does not have binaryValue, stringValue nor numericValue"); } } } FieldsStream.WriteByte((byte)(sbyte)bits); if (bytes != null) { FieldsStream.WriteVInt(bytes.Length); FieldsStream.WriteBytes(bytes.Bytes, bytes.Offset, bytes.Length); } else if (@string != null) { FieldsStream.WriteString(field.StringValue); } else { if (number is sbyte || number is short || number is int) { FieldsStream.WriteInt((int)number); } else if (number is long) { FieldsStream.WriteLong((long)number); } else if (number is float) { FieldsStream.WriteInt(Number.FloatToIntBits((float)number)); } else if (number is double) { FieldsStream.WriteLong(BitConverter.DoubleToInt64Bits((double)number)); } else { throw new InvalidOperationException("Cannot get here"); } } } /// <summary> /// Bulk write a contiguous series of documents. The /// lengths array is the length (in bytes) of each raw /// document. The stream IndexInput is the /// fieldsStream from which we should bulk-copy all /// bytes. /// </summary> public void AddRawDocuments(IndexInput stream, int[] lengths, int numDocs) { long position = FieldsStream.FilePointer; long start = position; for (int i = 0; i < numDocs; i++) { IndexStream.WriteLong(position); position += lengths[i]; } FieldsStream.CopyBytes(stream, position - start); Debug.Assert(FieldsStream.FilePointer == position); } public override void Finish(FieldInfos fis, int numDocs) { if (HEADER_LENGTH_IDX + ((long)numDocs) * 8 != IndexStream.FilePointer) // this is most likely a bug in Sun JRE 1.6.0_04/_05; // we detect that the bug has struck, here, and // throw an exception to prevent the corruption from // entering the index. See LUCENE-1282 for // details. { throw new Exception("fdx size mismatch: docCount is " + numDocs + " but fdx file size is " + IndexStream.FilePointer + " file=" + IndexStream.ToString() + "; now aborting this merge to prevent index corruption"); } } public override int Merge(MergeState mergeState) { int docCount = 0; // Used for bulk-reading raw bytes for stored fields int[] rawDocLengths = new int[MAX_RAW_MERGE_DOCS]; int idx = 0; foreach (AtomicReader reader in mergeState.Readers) { SegmentReader matchingSegmentReader = mergeState.MatchingSegmentReaders[idx++]; Lucene40StoredFieldsReader matchingFieldsReader = null; if (matchingSegmentReader != null) { StoredFieldsReader fieldsReader = matchingSegmentReader.FieldsReader; // we can only bulk-copy if the matching reader is also a Lucene40FieldsReader if (fieldsReader != null && fieldsReader is Lucene40StoredFieldsReader) { matchingFieldsReader = (Lucene40StoredFieldsReader)fieldsReader; } } if (reader.LiveDocs != null) { docCount += CopyFieldsWithDeletions(mergeState, reader, matchingFieldsReader, rawDocLengths); } else { docCount += CopyFieldsNoDeletions(mergeState, reader, matchingFieldsReader, rawDocLengths); } } Finish(mergeState.FieldInfos, docCount); return docCount; } /// <summary> /// Maximum number of contiguous documents to bulk-copy /// when merging stored fields /// </summary> private const int MAX_RAW_MERGE_DOCS = 4192; private int CopyFieldsWithDeletions(MergeState mergeState, AtomicReader reader, Lucene40StoredFieldsReader matchingFieldsReader, int[] rawDocLengths) { int docCount = 0; int maxDoc = reader.MaxDoc; Bits liveDocs = reader.LiveDocs; Debug.Assert(liveDocs != null); if (matchingFieldsReader != null) { // We can bulk-copy because the fieldInfos are "congruent" for (int j = 0; j < maxDoc; ) { if (!liveDocs.Get(j)) { // skip deleted docs ++j; continue; } // We can optimize this case (doing a bulk byte copy) since the field // numbers are identical int start = j, numDocs = 0; do { j++; numDocs++; if (j >= maxDoc) { break; } if (!liveDocs.Get(j)) { j++; break; } } while (numDocs < MAX_RAW_MERGE_DOCS); IndexInput stream = matchingFieldsReader.RawDocs(rawDocLengths, start, numDocs); AddRawDocuments(stream, rawDocLengths, numDocs); docCount += numDocs; mergeState.checkAbort.Work(300 * numDocs); } } else { for (int j = 0; j < maxDoc; j++) { if (!liveDocs.Get(j)) { // skip deleted docs continue; } // TODO: this could be more efficient using // FieldVisitor instead of loading/writing entire // doc; ie we just have to renumber the field number // on the fly? // NOTE: it's very important to first assign to doc then pass it to // fieldsWriter.addDocument; see LUCENE-1282 Document doc = reader.Document(j); AddDocument(doc, mergeState.FieldInfos); docCount++; mergeState.checkAbort.Work(300); } } return docCount; } private int CopyFieldsNoDeletions(MergeState mergeState, AtomicReader reader, Lucene40StoredFieldsReader matchingFieldsReader, int[] rawDocLengths) { int maxDoc = reader.MaxDoc; int docCount = 0; if (matchingFieldsReader != null) { // We can bulk-copy because the fieldInfos are "congruent" while (docCount < maxDoc) { int len = Math.Min(MAX_RAW_MERGE_DOCS, maxDoc - docCount); IndexInput stream = matchingFieldsReader.RawDocs(rawDocLengths, docCount, len); AddRawDocuments(stream, rawDocLengths, len); docCount += len; mergeState.checkAbort.Work(300 * len); } } else { for (; docCount < maxDoc; docCount++) { // NOTE: it's very important to first assign to doc then pass it to // fieldsWriter.addDocument; see LUCENE-1282 Document doc = reader.Document(docCount); AddDocument(doc, mergeState.FieldInfos); mergeState.checkAbort.Work(300); } } return docCount; } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using Scriban.Parsing; using Scriban.Runtime; using Scriban.Syntax; namespace Scriban.Functions { /// <summary> /// Array functions available through the object 'array' in scriban. /// </summary> #if SCRIBAN_PUBLIC public #else internal #endif partial class ArrayFunctions : ScriptObject { /// <summary> /// Adds a value to the input list. /// </summary> /// <param name="list">The input list</param> /// <param name="value">The value to add at the end of the list</param> /// <returns>A new list with the value added</returns> /// <remarks> /// ```scriban-html /// {{ [1, 2, 3] | array.add 4 }} /// ``` /// ```html /// [1, 2, 3, 4] /// ``` /// </remarks> public static IEnumerable Add(IEnumerable list, object value) { if (list == null) { return new ScriptRange { value }; } return list is IList ? (IEnumerable)new ScriptArray(list) {value} : new ScriptRange(list) {value}; } /// <summary> /// Concatenates two lists. /// </summary> /// <param name="list1">The 1st input list</param> /// <param name="list2">The 2nd input list</param> /// <returns>The concatenation of the two input lists</returns> /// <remarks> /// ```scriban-html /// {{ [1, 2, 3] | array.add_range [4, 5] }} /// ``` /// ```html /// [1, 2, 3, 4, 5] /// ``` /// </remarks> public static IEnumerable AddRange(IEnumerable list1, IEnumerable list2) { return Concat(list1, list2); } /// <summary> /// Removes any non-null values from the input list. /// </summary> /// <param name="list">An input list</param> /// <returns>Returns a list with null value removed</returns> /// <remarks> /// ```scriban-html /// {{ [1, null, 3] | array.compact }} /// ``` /// ```html /// [1, 3] /// ``` /// </remarks> public static IEnumerable Compact(IEnumerable list) { return ScriptRange.Compact(list); } /// <summary> /// Concatenates two lists. /// </summary> /// <param name="list1">The 1st input list</param> /// <param name="list2">The 2nd input list</param> /// <returns>The concatenation of the two input lists</returns> /// <remarks> /// ```scriban-html /// {{ [1, 2, 3] | array.concat [4, 5] }} /// ``` /// ```html /// [1, 2, 3, 4, 5] /// ``` /// </remarks> public static IEnumerable Concat(IEnumerable list1, IEnumerable list2) { return ScriptRange.Concat(list1, list2); } /// <summary> /// Loops through a group of strings and outputs them in the order that they were passed as parameters. Each time cycle is called, the next string that was passed as a parameter is output. /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="list">An input list</param> /// <param name="group">The group used. Default is `null`</param> /// <returns>Returns a list with null value removed</returns> /// <remarks> /// ```scriban-html /// {{ array.cycle ['one', 'two', 'three'] }} /// {{ array.cycle ['one', 'two', 'three'] }} /// {{ array.cycle ['one', 'two', 'three'] }} /// {{ array.cycle ['one', 'two', 'three'] }} /// ``` /// ```html /// one /// two /// three /// one /// ``` /// `cycle` accepts a parameter called cycle group in cases where you need multiple cycle blocks in one template. /// If no name is supplied for the cycle group, then it is assumed that multiple calls with the same parameters are one group. /// </remarks> public static object Cycle(TemplateContext context, SourceSpan span, IList list, object group = null) { if (list == null) { return null; } var strGroup = group == null ? Join(context, span, list, ",") : context.ObjectToString(@group); // We create a cycle variable that is dependent on the exact AST context. // So we allow to have multiple cycle running in the same loop var cycleKey = new CycleKey(strGroup); object cycleValue; var currentTags = context.Tags; if (!currentTags.TryGetValue(cycleKey, out cycleValue) || !(cycleValue is int)) { cycleValue = 0; } var cycleIndex = (int) cycleValue; cycleIndex = list.Count == 0 ? 0 : cycleIndex % list.Count; object result = null; if (list.Count > 0) { result = list[cycleIndex]; cycleIndex++; } currentTags[cycleKey] = cycleIndex; return result; } /// <summary> /// Applies the specified function to each element of the input. /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="list">An input list</param> /// <param name="function">The function to apply to each item in the list</param> /// <returns>Returns a list with each item being transformed by the function.</returns> /// <remarks> /// ```scriban-html /// {{ [" a", " 5", "6 "] | array.each @string.strip }} /// ``` /// ```html /// ["a", "5", "6"] /// ``` /// </remarks> public static ScriptRange Each(TemplateContext context, SourceSpan span, IEnumerable list, object function) { return ApplyFunction(context, span, list, function, EachProcessor); } private static IEnumerable EachInternal(TemplateContext context, SourceSpan span, IEnumerable list, IScriptCustomFunction function, Type destType) { var arg = new ScriptArray(1); foreach (var item in list) { var itemToTransform = context.ToObject(span, item, destType); arg[0] = itemToTransform; var itemTransformed = ScriptFunctionCall.Call(context, context.CurrentNode, function, arg); yield return itemTransformed; } } private static readonly ListProcessor EachProcessor = EachInternal; /// <summary> /// Filters the input list according the supplied filter function. /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="list">An input list</param> /// <param name="function">The function used to test each elemement of the list</param> /// <returns>Returns a new list which contains only those elements which match the filter function.</returns> /// <remarks> /// ```scriban-html /// {{["", "200", "","400"] | array.filter @string.empty}} /// ``` /// ```html /// ["", ""] /// ``` /// </remarks> public static ScriptRange Filter(TemplateContext context, SourceSpan span, IEnumerable list, object function) { return ApplyFunction(context, span, list, function, FilterProcessor); } static IEnumerable FilterInternal(TemplateContext context, SourceSpan span, IEnumerable list, IScriptCustomFunction function, Type destType) { var arg = new ScriptArray(1); foreach (var item in list) { var itemToTransform = context.ToObject(span, item, destType); arg[0] = itemToTransform; var itemTransformed = ScriptFunctionCall.Call(context, context.CurrentNode, function, arg); if (context.ToBool(span,itemTransformed)) yield return itemToTransform; } } private static readonly ListProcessor FilterProcessor = FilterInternal; /// <summary> /// Returns the first element of the input `list`. /// </summary> /// <param name="list">The input list</param> /// <returns>The first element of the input `list`.</returns> /// <remarks> /// ```scriban-html /// {{ [4, 5, 6] | array.first }} /// ``` /// ```html /// 4 /// ``` /// </remarks> public static object First(IEnumerable list) { if (list == null) { return null; } var realList = list as IList; if (realList != null) { return realList.Count > 0 ? realList[0] : null; } foreach (var item in list) { return item; } return null; } /// <summary> /// Inserts a `value` at the specified index in the input `list`. /// </summary> /// <param name="list">The input list</param> /// <param name="index">The index in the list where to insert the element</param> /// <param name="value">The value to insert</param> /// <returns>A new list with the element inserted.</returns> /// <remarks> /// ```scriban-html /// {{ ["a", "b", "c"] | array.insert_at 2 "Yo" }} /// ``` /// ```html /// ["a", "b", "Yo", "c"] /// ``` /// </remarks> public static IEnumerable InsertAt(IEnumerable list, int index, object value) { if (index < 0) { index = 0; } var array = list == null ? new ScriptArray() : new ScriptArray(list); // Make sure that the list has already inserted elements before the index for (int i = array.Count; i < index; i++) { array.Add(null); } array.Insert(index, value); return array; } /// <summary> /// Joins the element of a list separated by a delimiter string and return the concatenated string. /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="list">The input list</param> /// <param name="delimiter">The delimiter string to use to separate elements in the output string</param> /// <param name="function">An optional function that will receive the string representation of the item to join and can transform the text before joining.</param> /// <returns>A new list with the element inserted.</returns> /// <remarks> /// ```scriban-html /// {{ [1, 2, 3] | array.join "|" }} /// ``` /// ```html /// 1|2|3 /// ``` /// </remarks> public static string Join(TemplateContext context, SourceSpan span, IEnumerable list, string delimiter, object function = null) { if (list == null) { return string.Empty; } var scriptingFunction = function as IScriptCustomFunction; if (function != null && scriptingFunction == null) { throw new ArgumentException($"The parameter `{function}` is not a function. Maybe prefix it with @?", nameof(function)); } var text = new StringBuilder(); bool afterFirst = false; var arg = new ScriptArray(1); foreach (var obj in list) { if (afterFirst) { text.Append(delimiter); } var item = context.ObjectToString(obj); if (scriptingFunction != null) { arg[0] = item; var result = ScriptFunctionCall.Call(context, context.CurrentNode, scriptingFunction, arg); item = context.ObjectToString(result); } text.Append(item); afterFirst = true; } return text.ToString(); } /// <summary> /// Returns the last element of the input `list`. /// </summary> /// <param name="list">The input list</param> /// <returns>The last element of the input `list`.</returns> /// <remarks> /// ```scriban-html /// {{ [4, 5, 6] | array.last }} /// ``` /// ```html /// 6 /// ``` /// </remarks> public static object Last(IEnumerable list) { if (list == null) { return null; } var readList = list as IList; if (readList != null) { return readList.Count > 0 ? readList[readList.Count - 1] : null; } // Slow path, go through the whole list return list.Cast<object>().LastOrDefault(); } /// <summary> /// Returns a limited number of elments from the input list /// </summary> /// <param name="list">The input list</param> /// <param name="count">The number of elements to return from the input list</param> /// <remarks> /// ```scriban-html /// {{ [4, 5, 6] | array.limit 2 }} /// ``` /// ```html /// [4, 5] /// ``` /// </remarks> public static IEnumerable Limit(IEnumerable list, int count) { return ScriptRange.Limit(list, count); } /// <summary> /// Accepts an array element's attribute as a parameter and creates an array out of each array element's value. /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="list">The input list</param> /// <param name="member">The member to extract the value from</param> /// <remarks> /// ```scriban-html /// {{ /// products = [{title: "orange", type: "fruit"}, {title: "computer", type: "electronics"}, {title: "sofa", type: "furniture"}] /// products | array.map "type" | array.uniq | array.sort }} /// ``` /// ```html /// ["electronics", "fruit", "furniture"] /// ``` /// </remarks> public static IEnumerable Map(TemplateContext context, SourceSpan span, object list, string member) { return new ScriptRange(MapImpl(context, span, list, member)); } private static IEnumerable MapImpl(TemplateContext context, SourceSpan span, object list, string member) { if (list == null || member == null) { yield break; } var enumerable = list as IEnumerable; var realList = enumerable?.Cast<object>().ToList() ?? new List<object>(1) { list }; if (realList.Count == 0) { yield break; } foreach (var item in realList) { var itemAccessor = context.GetMemberAccessor(item); if (itemAccessor.HasMember(context, span, item, member)) { itemAccessor.TryGetValue(context, span, item, member, out object value); yield return value; } } } /// <summary> /// Returns the remaining of the list after the specified offset /// </summary> /// <param name="list">The input list</param> /// <param name="index">The index of a list to return elements</param> /// <remarks> /// ```scriban-html /// {{ [4, 5, 6, 7, 8] | array.offset 2 }} /// ``` /// ```html /// [6, 7, 8] /// ``` /// </remarks> public static IEnumerable Offset(IEnumerable list, int index) { return ScriptRange.Offset(list, index); } /// <summary> /// Removes an element at the specified `index` from the input `list` /// </summary> /// <param name="list">The input list</param> /// <param name="index">The index of a list to return elements</param> /// <returns>A new list with the element removed. If index is negative, remove at the end of the list.</returns> /// <remarks> /// ```scriban-html /// {{ [4, 5, 6, 7, 8] | array.remove_at 2 }} /// ``` /// ```html /// [4, 5, 7, 8] /// ``` /// If the `index` is negative, removes at the end of the list (notice that we need to put -1 in parenthesis to avoid confusing the parser with a binary `-` operation): /// ```scriban-html /// {{ [4, 5, 6, 7, 8] | array.remove_at (-1) }} /// ``` /// ```html /// [4, 5, 6, 7] /// ``` /// </remarks> public static IList RemoveAt(IList list, int index) { if (list == null) { return new ScriptArray(); } list = new ScriptArray(list); // If index is negative, start from the end if (index < 0) { index = list.Count + index; } if (index >= 0 && index < list.Count) { list.RemoveAt(index); } return list; } /// <summary> /// Reverses the input `list` /// </summary> /// <param name="list">The input list</param> /// <returns>A new list in reversed order.</returns> /// <remarks> /// ```scriban-html /// {{ [4, 5, 6, 7] | array.reverse }} /// ``` /// ```html /// [7, 6, 5, 4] /// ``` /// </remarks> public static IEnumerable Reverse(IEnumerable list) { return ScriptRange.Reverse(list); } /// <summary> /// Returns the number of elements in the input `list` /// </summary> /// <param name="list">The input list</param> /// <returns>A number of elements in the input `list`.</returns> /// <remarks> /// ```scriban-html /// {{ [4, 5, 6] | array.size }} /// ``` /// ```html /// 3 /// ``` /// </remarks> public static int Size(IEnumerable list) { if (list == null) { return 0; } var collection = list as ICollection; if (collection != null) { return collection.Count; } // Slow path, go through the whole list return list.Cast<object>().Count(); } /// <summary> /// Sorts the elements of the input `list` according to the value of each element or the value of the specified `member` of each element /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="list">The input list</param> /// <param name="member">The member name to sort according to its value. Null by default, meaning that the element's value are used instead.</param> /// <returns>A list sorted according to the value of each element or the value of the specified `member` of each element.</returns> /// <remarks> /// Sorts by element's value: /// ```scriban-html /// {{ [10, 2, 6] | array.sort }} /// ``` /// ```html /// [2, 6, 10] /// ``` /// Sorts by elements member's value: /// ```scriban-html /// {{ /// products = [{title: "orange", type: "fruit"}, {title: "computer", type: "electronics"}, {title: "sofa", type: "furniture"}] /// products | array.sort "title" | array.map "title" /// }} /// ``` /// ```html /// ["computer", "orange", "sofa"] /// ``` /// </remarks> public static IEnumerable Sort(TemplateContext context, SourceSpan span, object list, string member = null) { if (list == null) { return new ScriptRange(); } var enumerable = list as IEnumerable; if (enumerable == null) { return new ScriptArray(1) {list}; } var realList = enumerable.Cast<object>().ToList(); if (realList.Count == 0) return new ScriptArray(); if (string.IsNullOrEmpty(member)) { realList.Sort(); } else { realList.Sort((a, b) => { var leftAccessor = context.GetMemberAccessor(a); var rightAccessor = context.GetMemberAccessor(b); object leftValue = null; object rightValue = null; if (!leftAccessor.TryGetValue(context, span, a, member, out leftValue)) { context.TryGetMember?.Invoke(context, span, a, member, out leftValue); } if (!rightAccessor.TryGetValue(context, span, b, member, out rightValue)) { context.TryGetMember?.Invoke(context, span, b, member, out rightValue); } return Comparer<object>.Default.Compare(leftValue, rightValue); }); } return new ScriptArray(realList); } /// <summary> /// Returns the unique elements of the input `list`. /// </summary> /// <param name="list">The input list</param> /// <returns>A list of unique elements of the input `list`.</returns> /// <remarks> /// ```scriban-html /// {{ [1, 1, 4, 5, 8, 8] | array.uniq }} /// ``` /// ```html /// [1, 4, 5, 8] /// ``` /// </remarks> public static IEnumerable Uniq(IEnumerable list) { return ScriptRange.Uniq(list); } /// <summary> /// Returns if an `list` contains an specifique element /// </summary> /// <param name="list">the input list</param> /// <param name="item">the input item</param> /// <returns>**true** if element is in `list`; otherwise **false**</returns> /// <remarks> /// ```scriban-html /// {{ [1, 2, 3, 4] | array.contains 4 }} /// ``` /// ```html /// true /// ``` /// </remarks> public static bool Contains(IEnumerable list, object item) { foreach (var element in list) if (element == item || (element != null && element.Equals(item))) return true; return false; } /// <summary> /// Delegate type for function used to process a list /// </summary> private delegate IEnumerable ListProcessor(TemplateContext context, SourceSpan span, IEnumerable list, IScriptCustomFunction function, Type destType); /// <summary> /// Attempts to apply a Scriban function to a list and returns the results as a ScriptRange /// </summary> /// <remarks> /// Encapsulates a common approach to parameter checking for any method that will take a Scriban function and apply it to a list /// </remarks> private static ScriptRange ApplyFunction(TemplateContext context, SourceSpan span, IEnumerable list, object function, ListProcessor impl) { if (list == null) return null; if (function == null) return new ScriptRange(list); var scriptingFunction = function as IScriptCustomFunction; if (scriptingFunction == null) { throw new ArgumentException($"The parameter `{function}` is not a function. Maybe prefix it with @?", nameof(function)); } return new ScriptRange(impl(context, span, list, scriptingFunction, scriptingFunction.GetParameterInfo(0).ParameterType)); } private class CycleKey : IEquatable<CycleKey> { public readonly string Group; public CycleKey(string @group) { Group = @group; } public bool Equals(CycleKey other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return string.Equals(Group, other.Group); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((CycleKey) obj); } public override int GetHashCode() { return (Group != null ? Group.GetHashCode() : 0); } public override string ToString() { return $"cycle {Group}"; } } } }
// 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.AcceptanceTestsHttp { using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for HttpRedirects. /// </summary> public static partial class HttpRedirectsExtensions { /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static HttpRedirectsHead300Headers Head300(this IHttpRedirects operations) { return operations.Head300Async().GetAwaiter().GetResult(); } /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HttpRedirectsHead300Headers> Head300Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Head300WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IList<string> Get300(this IHttpRedirects operations) { return operations.Get300Async().GetAwaiter().GetResult(); } /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<string>> Get300Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get300WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static HttpRedirectsHead301Headers Head301(this IHttpRedirects operations) { return operations.Head301Async().GetAwaiter().GetResult(); } /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HttpRedirectsHead301Headers> Head301Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Head301WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static HttpRedirectsGet301Headers Get301(this IHttpRedirects operations) { return operations.Get301Async().GetAwaiter().GetResult(); } /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HttpRedirectsGet301Headers> Get301Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get301WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Put true Boolean value in request returns 301. This request should not be /// automatically redirected, but should return the received 301 to the caller /// for evaluation /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static HttpRedirectsPut301Headers Put301(this IHttpRedirects operations, bool? booleanValue = default(bool?)) { return operations.Put301Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Put true Boolean value in request returns 301. This request should not be /// automatically redirected, but should return the received 301 to the caller /// for evaluation /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HttpRedirectsPut301Headers> Put301Async(this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Put301WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static HttpRedirectsHead302Headers Head302(this IHttpRedirects operations) { return operations.Head302Async().GetAwaiter().GetResult(); } /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HttpRedirectsHead302Headers> Head302Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Head302WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static HttpRedirectsGet302Headers Get302(this IHttpRedirects operations) { return operations.Get302Async().GetAwaiter().GetResult(); } /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HttpRedirectsGet302Headers> Get302Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get302WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Patch true Boolean value in request returns 302. This request should not /// be automatically redirected, but should return the received 302 to the /// caller for evaluation /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static HttpRedirectsPatch302Headers Patch302(this IHttpRedirects operations, bool? booleanValue = default(bool?)) { return operations.Patch302Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Patch true Boolean value in request returns 302. This request should not /// be automatically redirected, but should return the received 302 to the /// caller for evaluation /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HttpRedirectsPatch302Headers> Patch302Async(this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Patch302WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Post true Boolean value in request returns 303. This request should be /// automatically redirected usign a get, ultimately returning a 200 status /// code /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static HttpRedirectsPost303Headers Post303(this IHttpRedirects operations, bool? booleanValue = default(bool?)) { return operations.Post303Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Post true Boolean value in request returns 303. This request should be /// automatically redirected usign a get, ultimately returning a 200 status /// code /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HttpRedirectsPost303Headers> Post303Async(this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Post303WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Redirect with 307, resulting in a 200 success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static HttpRedirectsHead307Headers Head307(this IHttpRedirects operations) { return operations.Head307Async().GetAwaiter().GetResult(); } /// <summary> /// Redirect with 307, resulting in a 200 success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HttpRedirectsHead307Headers> Head307Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Head307WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Redirect get with 307, resulting in a 200 success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static HttpRedirectsGet307Headers Get307(this IHttpRedirects operations) { return operations.Get307Async().GetAwaiter().GetResult(); } /// <summary> /// Redirect get with 307, resulting in a 200 success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HttpRedirectsGet307Headers> Get307Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get307WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Put redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static HttpRedirectsPut307Headers Put307(this IHttpRedirects operations, bool? booleanValue = default(bool?)) { return operations.Put307Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Put redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HttpRedirectsPut307Headers> Put307Async(this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Put307WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Patch redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static HttpRedirectsPatch307Headers Patch307(this IHttpRedirects operations, bool? booleanValue = default(bool?)) { return operations.Patch307Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Patch redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HttpRedirectsPatch307Headers> Patch307Async(this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Patch307WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Post redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static HttpRedirectsPost307Headers Post307(this IHttpRedirects operations, bool? booleanValue = default(bool?)) { return operations.Post307Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Post redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HttpRedirectsPost307Headers> Post307Async(this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Post307WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Delete redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static HttpRedirectsDelete307Headers Delete307(this IHttpRedirects operations, bool? booleanValue = default(bool?)) { return operations.Delete307Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Delete redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HttpRedirectsDelete307Headers> Delete307Async(this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Delete307WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } } }
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry and contributors // 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 YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; namespace YamlDotNet.Serialization { /// <summary> /// Writes objects to YAML. /// </summary> public sealed class Serializer { internal IList<IYamlTypeConverter> Converters { get; private set; } private readonly SerializationOptions options; private readonly INamingConvention namingConvention; private readonly ITypeResolver typeResolver; /// <summary> /// /// </summary> /// <param name="options">Options that control how the serialization is to be performed.</param> /// <param name="namingConvention">Naming strategy to use for serialized property names</param> public Serializer(SerializationOptions options = SerializationOptions.None, INamingConvention namingConvention = null) { this.options = options; this.namingConvention = namingConvention ?? new NullNamingConvention(); Converters = new List<IYamlTypeConverter>(); foreach (IYamlTypeConverter yamlTypeConverter in Utilities.YamlTypeConverters.GetBuiltInConverters(IsOptionSet(SerializationOptions.JsonCompatible))) { Converters.Add(yamlTypeConverter); } typeResolver = IsOptionSet(SerializationOptions.DefaultToStaticType) ? (ITypeResolver)new StaticTypeResolver() : (ITypeResolver)new DynamicTypeResolver(); } private bool IsOptionSet(SerializationOptions option) { return (options & option) != 0; } /// <summary> /// Registers a type converter to be used to serialize and deserialize specific types. /// </summary> public void RegisterTypeConverter(IYamlTypeConverter converter) { Converters.Insert(0, converter); } /// <summary> /// Serializes the specified object. /// </summary> /// <param name="writer">The <see cref="TextWriter" /> where to serialize the object.</param> /// <param name="graph">The object to serialize.</param> public void Serialize(TextWriter writer, object graph) { Serialize(new Emitter(writer), graph); } /// <summary> /// Serializes the specified object. /// </summary> /// <param name="writer">The <see cref="TextWriter" /> where to serialize the object.</param> /// <param name="graph">The object to serialize.</param> /// <param name="type">The static type of the object to serialize.</param> public void Serialize(TextWriter writer, object graph, Type type) { Serialize(new Emitter(writer), graph, type); } /// <summary> /// Serializes the specified object. /// </summary> /// <param name="emitter">The <see cref="IEmitter" /> where to serialize the object.</param> /// <param name="graph">The object to serialize.</param> public void Serialize(IEmitter emitter, object graph) { if (emitter == null) { throw new ArgumentNullException("emitter"); } EmitDocument(emitter, new ObjectDescriptor(graph, graph != null ? graph.GetType() : typeof(object), typeof(object))); } /// <summary> /// Serializes the specified object. /// </summary> /// <param name="emitter">The <see cref="IEmitter" /> where to serialize the object.</param> /// <param name="graph">The object to serialize.</param> /// <param name="type">The static type of the object to serialize.</param> public void Serialize(IEmitter emitter, object graph, Type type) { if (emitter == null) { throw new ArgumentNullException("emitter"); } if (type == null) { throw new ArgumentNullException("type"); } EmitDocument(emitter, new ObjectDescriptor(graph, type, type)); } private void EmitDocument(IEmitter emitter, IObjectDescriptor graph) { var traversalStrategy = CreateTraversalStrategy(); var eventEmitter = CreateEventEmitter(emitter); var emittingVisitor = CreateEmittingVisitor(emitter, traversalStrategy, eventEmitter, graph); emitter.Emit(new StreamStart()); emitter.Emit(new DocumentStart()); traversalStrategy.Traverse(graph, emittingVisitor); emitter.Emit(new DocumentEnd(true)); emitter.Emit(new StreamEnd()); } private IObjectGraphVisitor CreateEmittingVisitor(IEmitter emitter, IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IObjectDescriptor graph) { IObjectGraphVisitor emittingVisitor = new EmittingObjectGraphVisitor(eventEmitter); emittingVisitor = new CustomSerializationObjectGraphVisitor(emitter, emittingVisitor, Converters); if (!IsOptionSet(SerializationOptions.DisableAliases)) { var anchorAssigner = new AnchorAssigner(); traversalStrategy.Traverse(graph, anchorAssigner); emittingVisitor = new AnchorAssigningObjectGraphVisitor(emittingVisitor, eventEmitter, anchorAssigner); } if (!IsOptionSet(SerializationOptions.EmitDefaults)) { emittingVisitor = new DefaultExclusiveObjectGraphVisitor(emittingVisitor); } return emittingVisitor; } private IEventEmitter CreateEventEmitter(IEmitter emitter) { var writer = new WriterEventEmitter(emitter); if (IsOptionSet(SerializationOptions.JsonCompatible)) { return new JsonEventEmitter(writer); } else { return new TypeAssigningEventEmitter(writer, IsOptionSet(SerializationOptions.Roundtrip)); } } private IObjectGraphTraversalStrategy CreateTraversalStrategy() { ITypeInspector typeDescriptor = new ReadablePropertiesTypeInspector(typeResolver); if (IsOptionSet(SerializationOptions.Roundtrip)) { typeDescriptor = new ReadableAndWritablePropertiesTypeInspector(typeDescriptor); } typeDescriptor = new NamingConventionTypeInspector(typeDescriptor, namingConvention); typeDescriptor = new YamlAttributesTypeInspector(typeDescriptor); if (IsOptionSet(SerializationOptions.DefaultToStaticType)) { typeDescriptor = new CachedTypeInspector(typeDescriptor); } if (IsOptionSet(SerializationOptions.Roundtrip)) { return new RoundtripObjectGraphTraversalStrategy(this, typeDescriptor, typeResolver, 50); } else { return new FullObjectGraphTraversalStrategy(this, typeDescriptor, typeResolver, 50, namingConvention); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using GuidGenerator.Areas.HelpPage.ModelDescriptions; using GuidGenerator.Areas.HelpPage.Models; namespace GuidGenerator.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
#region Copyright notice and license // Copyright 2015-2016, Google 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: // // * 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.Runtime.InteropServices; using System.Threading; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// gpr_timespec from grpc/support/time.h /// </summary> [StructLayout(LayoutKind.Sequential)] internal struct Timespec { const long NanosPerSecond = 1000 * 1000 * 1000; const long NanosPerTick = 100; const long TicksPerSecond = NanosPerSecond / NanosPerTick; static readonly NativeMethods Native = NativeMethods.Get(); static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); public Timespec(long tv_sec, int tv_nsec) : this(tv_sec, tv_nsec, GPRClockType.Realtime) { } public Timespec(long tv_sec, int tv_nsec, GPRClockType clock_type) { this.tv_sec = tv_sec; this.tv_nsec = tv_nsec; this.clock_type = clock_type; } private long tv_sec; private int tv_nsec; private GPRClockType clock_type; /// <summary> /// Timespec a long time in the future. /// </summary> public static Timespec InfFuture { get { return Native.gprsharp_inf_future(GPRClockType.Realtime); } } /// <summary> /// Timespec a long time in the past. /// </summary> public static Timespec InfPast { get { return Native.gprsharp_inf_past(GPRClockType.Realtime); } } /// <summary> /// Return Timespec representing the current time. /// </summary> public static Timespec Now { get { return Native.gprsharp_now(GPRClockType.Realtime); } } /// <summary> /// Seconds since unix epoch. /// </summary> public long TimevalSeconds { get { return tv_sec; } } /// <summary> /// The nanoseconds part of timeval. /// </summary> public int TimevalNanos { get { return tv_nsec; } } /// <summary> /// Converts the timespec to desired clock type. /// </summary> public Timespec ToClockType(GPRClockType targetClock) { return Native.gprsharp_convert_clock_type(this, targetClock); } /// <summary> /// Converts Timespec to DateTime. /// Timespec needs to be of type GPRClockType.Realtime and needs to represent a legal value. /// DateTime has lower resolution (100ns), so rounding can occurs. /// Value are always rounded up to the nearest DateTime value in the future. /// /// For Timespec.InfFuture or if timespec is after the largest representable DateTime, DateTime.MaxValue is returned. /// For Timespec.InfPast or if timespec is before the lowest representable DateTime, DateTime.MinValue is returned. /// /// Unless DateTime.MaxValue or DateTime.MinValue is returned, the resulting DateTime is always in UTC /// (DateTimeKind.Utc) /// </summary> public DateTime ToDateTime() { Preconditions.CheckState(tv_nsec >= 0 && tv_nsec < NanosPerSecond); Preconditions.CheckState(clock_type == GPRClockType.Realtime); // fast path for InfFuture if (this.Equals(InfFuture)) { return DateTime.MaxValue; } // fast path for InfPast if (this.Equals(InfPast)) { return DateTime.MinValue; } try { // convert nanos to ticks, round up to the nearest tick long ticksFromNanos = tv_nsec / NanosPerTick + ((tv_nsec % NanosPerTick != 0) ? 1 : 0); long ticksTotal = checked(tv_sec * TicksPerSecond + ticksFromNanos); return UnixEpoch.AddTicks(ticksTotal); } catch (OverflowException) { // ticks out of long range return tv_sec > 0 ? DateTime.MaxValue : DateTime.MinValue; } catch (ArgumentOutOfRangeException) { // resulting date time would be larger than MaxValue return tv_sec > 0 ? DateTime.MaxValue : DateTime.MinValue; } } /// <summary> /// Creates DateTime to Timespec. /// DateTime has to be in UTC (DateTimeKind.Utc) unless it's DateTime.MaxValue or DateTime.MinValue. /// For DateTime.MaxValue of date time after the largest representable Timespec, Timespec.InfFuture is returned. /// For DateTime.MinValue of date time before the lowest representable Timespec, Timespec.InfPast is returned. /// </summary> /// <returns>The date time.</returns> /// <param name="dateTime">Date time.</param> public static Timespec FromDateTime(DateTime dateTime) { if (dateTime == DateTime.MaxValue) { return Timespec.InfFuture; } if (dateTime == DateTime.MinValue) { return Timespec.InfPast; } Preconditions.CheckArgument(dateTime.Kind == DateTimeKind.Utc, "dateTime needs of kind DateTimeKind.Utc or be equal to DateTime.MaxValue or DateTime.MinValue."); try { TimeSpan timeSpan = dateTime - UnixEpoch; long ticks = timeSpan.Ticks; long seconds = ticks / TicksPerSecond; int nanos = (int)((ticks % TicksPerSecond) * NanosPerTick); if (nanos < 0) { // correct the result based on C# modulo semantics for negative dividend seconds--; nanos += (int)NanosPerSecond; } return new Timespec(seconds, nanos); } catch (ArgumentOutOfRangeException) { return dateTime > UnixEpoch ? Timespec.InfFuture : Timespec.InfPast; } } /// <summary> /// Gets current timestamp using <c>GPRClockType.Precise</c>. /// Only available internally because core needs to be compiled with /// GRPC_TIMERS_RDTSC support for this to use RDTSC. /// </summary> internal static Timespec PreciseNow { get { return Native.gprsharp_now(GPRClockType.Precise); } } internal static int NativeSize { get { return Native.gprsharp_sizeof_timespec(); } } } }
/* * Copyright 2012-2016 The Pkcs11Interop Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <jimrich@jimrich.sk> */ using System; using System.IO; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI80; using Net.Pkcs11Interop.LowLevelAPI80.MechanismParams; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Net.Pkcs11Interop.Tests.LowLevelAPI80 { /// <summary> /// C_EncryptInit, C_Encrypt, C_EncryptUpdate, C_EncryptFinish, C_DecryptInit, C_Decrypt, C_DecryptUpdate and C_DecryptFinish tests. /// </summary> [TestClass] public class _20_EncryptAndDecryptTest { /// <summary> /// C_EncryptInit, C_Encrypt, C_DecryptInit and C_Decrypt test. /// </summary> [TestMethod] public void _01_EncryptAndDecryptSinglePartTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs80); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate symetric key ulong keyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKey(pkcs11, session, ref keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate random initialization vector byte[] iv = new byte[8]; rv = pkcs11.C_GenerateRandom(session, iv, Convert.ToUInt64(iv.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify encryption mechanism with initialization vector as parameter. // Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory. CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv); // Initialize encryption operation rv = pkcs11.C_EncryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); // Get length of encrypted data in first call ulong encryptedDataLen = 0; rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt64(sourceData.Length), null, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(encryptedDataLen > 0); // Allocate array for encrypted data byte[] encryptedData = new byte[encryptedDataLen]; // Get encrypted data in second call rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt64(sourceData.Length), encryptedData, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with encrypted data // Initialize decryption operation rv = pkcs11.C_DecryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Get length of decrypted data in first call ulong decryptedDataLen = 0; rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt64(encryptedData.Length), null, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(decryptedDataLen > 0); // Allocate array for decrypted data byte[] decryptedData = new byte[decryptedDataLen]; // Get decrypted data in second call rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt64(encryptedData.Length), decryptedData, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case) UnmanagedMemory.Free(ref mechanism.Parameter); mechanism.ParameterLen = 0; rv = pkcs11.C_DestroyObject(session, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_EncryptInit, C_EncryptUpdate, C_EncryptFinish, C_DecryptInit, C_DecryptUpdate and C_DecryptFinish test. /// </summary> [TestMethod] public void _02_EncryptAndDecryptMultiPartTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs80); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate symetric key ulong keyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKey(pkcs11, session, ref keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate random initialization vector byte[] iv = new byte[8]; rv = pkcs11.C_GenerateRandom(session, iv, Convert.ToUInt64(iv.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify encryption mechanism with initialization vector as parameter. // Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory. CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); byte[] encryptedData = null; byte[] decryptedData = null; // Multipart encryption functions C_EncryptUpdate and C_EncryptFinal can be used i.e. for encryption of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream()) { // Initialize encryption operation rv = pkcs11.C_EncryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for source data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; // Prepare buffer for encrypted data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] encryptedPart = new byte[8]; ulong encryptedPartLen = Convert.ToUInt64(encryptedPart.Length); // Read input stream with source data int bytesRead = 0; while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0) { // Encrypt each individual source data part encryptedPartLen = Convert.ToUInt64(encryptedPart.Length); rv = pkcs11.C_EncryptUpdate(session, part, Convert.ToUInt64(bytesRead), encryptedPart, ref encryptedPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append encrypted data part to the output stream outputStream.Write(encryptedPart, 0, Convert.ToInt32(encryptedPartLen)); } // Get the length of last encrypted data part in first call byte[] lastEncryptedPart = null; ulong lastEncryptedPartLen = 0; rv = pkcs11.C_EncryptFinal(session, null, ref lastEncryptedPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Allocate array for the last encrypted data part lastEncryptedPart = new byte[lastEncryptedPartLen]; // Get the last encrypted data part in second call rv = pkcs11.C_EncryptFinal(session, lastEncryptedPart, ref lastEncryptedPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append the last encrypted data part to the output stream outputStream.Write(lastEncryptedPart, 0, Convert.ToInt32(lastEncryptedPartLen)); // Read whole output stream to the byte array so we can compare results more easily encryptedData = outputStream.ToArray(); } // Do something interesting with encrypted data // Multipart decryption functions C_DecryptUpdate and C_DecryptFinal can be used i.e. for decryption of streamed data using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream()) { // Initialize decryption operation rv = pkcs11.C_DecryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for encrypted data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] encryptedPart = new byte[8]; // Prepare buffer for decrypted data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; ulong partLen = Convert.ToUInt64(part.Length); // Read input stream with encrypted data int bytesRead = 0; while ((bytesRead = inputStream.Read(encryptedPart, 0, encryptedPart.Length)) > 0) { // Decrypt each individual encrypted data part partLen = Convert.ToUInt64(part.Length); rv = pkcs11.C_DecryptUpdate(session, encryptedPart, Convert.ToUInt64(bytesRead), part, ref partLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append decrypted data part to the output stream outputStream.Write(part, 0, Convert.ToInt32(partLen)); } // Get the length of last decrypted data part in first call byte[] lastPart = null; ulong lastPartLen = 0; rv = pkcs11.C_DecryptFinal(session, null, ref lastPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Allocate array for the last decrypted data part lastPart = new byte[lastPartLen]; // Get the last decrypted data part in second call rv = pkcs11.C_DecryptFinal(session, lastPart, ref lastPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append the last decrypted data part to the output stream outputStream.Write(lastPart, 0, Convert.ToInt32(lastPartLen)); // Read whole output stream to the byte array so we can compare results more easily decryptedData = outputStream.ToArray(); } // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case) UnmanagedMemory.Free(ref mechanism.Parameter); mechanism.ParameterLen = 0; rv = pkcs11.C_DestroyObject(session, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_EncryptInit, C_Encrypt, C_DecryptInit and C_Decrypt test with CKM_RSA_PKCS_OAEP mechanism. /// </summary> [TestMethod] public void _03_EncryptAndDecryptSinglePartOaepTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs80); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate asymetric key pair ulong pubKeyId = CK.CK_INVALID_HANDLE; ulong privKeyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKeyPair(pkcs11, session, ref pubKeyId, ref privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify mechanism parameters CK_RSA_PKCS_OAEP_PARAMS mechanismParams = new CK_RSA_PKCS_OAEP_PARAMS(); mechanismParams.HashAlg = (ulong)CKM.CKM_SHA_1; mechanismParams.Mgf = (ulong)CKG.CKG_MGF1_SHA1; mechanismParams.Source = (ulong)CKZ.CKZ_DATA_SPECIFIED; mechanismParams.SourceData = IntPtr.Zero; mechanismParams.SourceDataLen = 0; // Specify encryption mechanism with parameters // Note that CkmUtils.CreateMechanism() automaticaly copies mechanismParams into newly allocated unmanaged memory. CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_RSA_PKCS_OAEP, mechanismParams); // Initialize encryption operation rv = pkcs11.C_EncryptInit(session, ref mechanism, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Get length of encrypted data in first call ulong encryptedDataLen = 0; rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt64(sourceData.Length), null, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(encryptedDataLen > 0); // Allocate array for encrypted data byte[] encryptedData = new byte[encryptedDataLen]; // Get encrypted data in second call rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt64(sourceData.Length), encryptedData, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with encrypted data // Initialize decryption operation rv = pkcs11.C_DecryptInit(session, ref mechanism, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Get length of decrypted data in first call ulong decryptedDataLen = 0; rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt64(encryptedData.Length), null, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(decryptedDataLen > 0); // Allocate array for decrypted data byte[] decryptedData = new byte[decryptedDataLen]; // Get decrypted data in second call rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt64(encryptedData.Length), decryptedData, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Array may need to be shrinked if (decryptedData.Length != Convert.ToInt32(decryptedDataLen)) Array.Resize(ref decryptedData, Convert.ToInt32(decryptedDataLen)); // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter UnmanagedMemory.Free(ref mechanism.Parameter); mechanism.ParameterLen = 0; rv = pkcs11.C_DestroyObject(session, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_DestroyObject(session, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } } }
namespace WebBaseSystem.Web.Areas.HelpPage { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator simpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return this.GenerateObject(type, new Dictionary<Type, object>()); } 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); } } [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 this.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 class SimpleTypeObjectGenerator { private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); private long index = 0; public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++this.index); } [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(bool), 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(short), index => (short)(index % short.MaxValue) }, { typeof(int), index => (int)(index % int.MaxValue) }, { typeof(long), index => (long)index }, { typeof(object), index => new object() }, { typeof(sbyte), index => (sbyte)64 }, { typeof(float), index => (float)(index + 0.1) }, { typeof(string), index => { return string.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(ushort), index => (ushort)(index % ushort.MaxValue) }, { typeof(uint), index => (uint)(index % uint.MaxValue) }, { typeof(ulong), index => (ulong)index }, { typeof(Uri), index => { return new Uri(string.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } } } }
//----------------------------------------------------------------------------- // CurveEditor.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.ComponentModel; using System.ComponentModel.Design; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using Microsoft.Xna.Framework; namespace Xna.Tools { public partial class CurveEditor : Form { public CurveEditor() { InitializeComponent(); if (Site != null) Site.Container.Add(curveControl); } #region Internal Methods internal void UpdateCurveItems(IList newItems, IList selection) { disableUIEvents++; curveListView.BeginUpdate(); ArrayList oldItems = new ArrayList(curveListView.Items); curveListView.Items.Clear(); // Add new items. foreach (ListViewItem item in newItems) { curveListView.Items.Add(item); if (!oldItems.Contains(item)) curveControl.Curves.Add(CurveFileInfo.GetCurve(item)); } // Remove items from Curve control that not exist new items. foreach (ListViewItem item in oldItems) { if (!curveListView.Items.Contains(item)) curveControl.Curves.Remove(CurveFileInfo.GetCurve(item)); } ApplySelection(selection); curveListView.EndUpdate(); disableUIEvents--; } internal void ApplySelection(IList selection) { disableUIEvents++; curveListView.BeginUpdate(); // Update selection curveListView.SelectedItems.Clear(); foreach (ListViewItem item in selection) item.Selected = true; curveListView.EndUpdate(); disableUIEvents--; } #endregion protected override void OnFormClosing(FormClosingEventArgs e) { foreach ( ListViewItem item in curveListView.Items ) { EditCurve curve = CurveFileInfo.GetCurve(item); if ( curve.Dirty ) { DialogResult dr = MessageBox.Show( String.Format( CurveEditorResources.SaveMessage, curve.Name ), CurveEditorResources.CurveEditorTitle, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation); if ( dr == DialogResult.Yes) dr = SaveCurve(item, false); if (dr == DialogResult.Cancel) { e.Cancel = true; break; } } } base.OnFormClosing(e); } #region Event handle methods private void curveListView_AfterLabelEdit(object sender, LabelEditEventArgs e) { if (disableUIEvents > 0) return; // Label edit has been canceled. if (String.IsNullOrEmpty(e.Label)) return; // commandHistory.BeginRecordCommands(); curveControl.BeginUpdate(); string newName = EnsureUniqueName(e.Label); e.CancelEdit = String.Compare(newName, e.Label) != 0; curveListView.Items[e.Item].Text = newName; EditCurve curve = CurveFileInfo.GetCurve(curveListView.Items[e.Item]); curve.Name = newName; curveControl.EndUpdate(); commandHistory.EndRecordCommands(); } private void CurveEditor_Load(object sender, EventArgs e) { commandHistory = CommandHistory.EnsureHasService(Site); } private void curveListView_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete) RemoveSelectedCurves(); } private void newToolStripMenuItem_Click(object sender, EventArgs e) { CreateCurve(); } private void openToolStripMenuItem_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() != DialogResult.OK) return; foreach (string filename in openFileDialog1.FileNames) { string name = EnsureUniqueName(Path.GetFileNameWithoutExtension(filename)); EditCurve editCurve = EditCurve.LoadFromFile(filename, name, NextCurveColor(), commandHistory); ListViewItem item = CreateCurve(editCurve, name); CurveFileInfo.AssignFilename(item, filename); } } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { SaveCurves(false); } private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) { SaveCurves(true); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Close(); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { using (HelpAbout about = new HelpAbout()) { about.ShowDialog(); } } private void curveListView_SelectedIndexChanged(object sender, EventArgs e) { if (disableUIEvents > 0) return; UpdateCurveEditables(); curveControl.Invalidate(true); } private void curveListView_ItemChecked(object sender, ItemCheckedEventArgs e) { if (disableUIEvents > 0) return; CurveFileInfo.GetCurve(e.Item).Visible = e.Item.Checked; curveControl.Invalidate(true); } private void editCurve_StateChanged(object sender, EventArgs e) { disableUIEvents++; curveListView.BeginUpdate(); EditCurve curve = sender as EditCurve; ListViewItem item = idToItemMap[curve.Id]; item.Text = curve.Name; disableUIEvents--; curveListView.EndUpdate(); } #endregion #region Private methods private System.Drawing.Color NextCurveColor() { System.Drawing.Color result = curveColors[curveColorIndex++]; if (curveColorIndex >= curveColors.Length) curveColorIndex = 0; return result; } private ListViewItem CreateCurve(EditCurve editCurve, string name) { editCurve.Id = GenerateUniqueCurveId(); editCurve.StateChanged += new EventHandler(editCurve_StateChanged); ListViewItem item = new ListViewItem(name); item.Checked = true; CurveFileInfo.AssignCurve(item, editCurve); idToItemMap.Add(editCurve.Id, item); ArrayList oldItems = new ArrayList(curveListView.Items); ArrayList oldSelection = new ArrayList(curveListView.SelectedItems); ArrayList newItems = new ArrayList(curveListView.Items); ListViewItem[] newSelection = { item }; newItems.Add(item); //curveListView.Items.Add(item); //curveListView.SelectedItems.Clear(); //item.Selected = true; commandHistory.BeginRecordCommands(); commandHistory.Do( new CurveAddRemoveCommand(this, oldItems, newItems, oldSelection, newSelection)); UpdateCurveEditables(); commandHistory.EndRecordCommands(); return item; } private ListViewItem CreateCurve() { string name = EnsureUniqueName("Curve"); Curve curve = new Curve(); curve.Keys.Add(new CurveKey(0, 0)); EditCurve editCurve = new EditCurve(name, NextCurveColor(), curve, commandHistory); editCurve.Dirty = true; return CreateCurve(editCurve, name); } private void UpdateCurveEditables() { UpdateCurves(delegate(ListViewItem item, EditCurve curve) { curve.Editable = item.Selected; }); } private void RemoveSelectedCurves() { commandHistory.BeginRecordCommands(); ArrayList newItems = new ArrayList(); ArrayList newSelection = new ArrayList(); foreach (ListViewItem item in curveListView.Items) { if (!item.Selected) { newItems.Add(item); if (newSelection.Count == 0 )newSelection.Add(item); } } ArrayList oldItems = new ArrayList(curveListView.Items); ArrayList oldSelection = new ArrayList(curveListView.SelectedItems); commandHistory.Do( new CurveAddRemoveCommand(this, oldItems, newItems, oldSelection, newSelection)); UpdateCurveEditables(); commandHistory.EndRecordCommands(); } private string EnsureUniqueName(string candidateName) { string name = String.IsNullOrEmpty(candidateName) ? "Empty" : candidateName; int num = 1; bool found = false; do { found = false; foreach (ListViewItem item in curveListView.Items) { int result = String.Compare( item.Text, name, true, CultureInfo.InvariantCulture); if (result == 0) { found = true; name = String.Format("{0}#{1}", candidateName, num++); break; } } } while (found); return name; } /// <summary> /// Update curves. /// </summary> /// <param name="callback"></param> private void UpdateCurves(UpdateCurveDelegate callback) { curveControl.BeginUpdate(); foreach (ListViewItem item in curveListView.Items) callback(item, CurveFileInfo.GetCurve(item)); curveControl.EndUpdate(); } private DialogResult SaveCurve(ListViewItem item, bool saveAs) { string filename = CurveFileInfo.GetFilename(item); if (String.IsNullOrEmpty(filename) || saveAs) { saveFileDialog1.Title = saveAs ? "Save Curve As" : "Save Curve"; saveFileDialog1.FileName = Path.ChangeExtension(item.Text, ".xml"); DialogResult dr = saveFileDialog1.ShowDialog(); if (dr == DialogResult.OK) { filename = saveFileDialog1.FileName; CurveFileInfo.AssignFilename(item, filename); } if (dr == DialogResult.Cancel) return dr; } // Save to file. if (!String.IsNullOrEmpty(filename)) CurveFileInfo.Save(item, filename); return DialogResult.OK; } private void SaveCurves(bool saveAs) { // Save current curves. foreach (ListViewItem item in curveListView.SelectedItems) { if (SaveCurve(item, saveAs) == DialogResult.Cancel) break; } } /// <summary> /// Generate Unique Id for EditCurve /// We need to assign unique Id for each EditCurve for undo/redo. /// </summary> /// <returns></returns> private long GenerateUniqueCurveId() { return curveId++; } delegate void UpdateCurveDelegate(ListViewItem item, EditCurve curve); #endregion private long curveId; private CommandHistory commandHistory; private Dictionary<long, ListViewItem> idToItemMap = new Dictionary<long, ListViewItem>(); private int disableUIEvents; private System.Drawing.Color[] curveColors = { System.Drawing.Color.Red, System.Drawing.Color.Green, System.Drawing.Color.Blue }; private int curveColorIndex; class CurveFileInfo { public EditCurve Curve; public string Filename; public static void AssignCurve( ListViewItem item, EditCurve curve ) { CurveFileInfo cfi = EnsureFileInfo(item); cfi.Curve = curve; } public static void AssignFilename(ListViewItem item, string filename) { CurveFileInfo cfi = EnsureFileInfo(item); cfi.Filename = filename; } public static EditCurve GetCurve(ListViewItem item) { return EnsureFileInfo(item).Curve; } public static string GetFilename(ListViewItem item) { return EnsureFileInfo(item).Filename; } public static void Save(ListViewItem item, string filename) { GetCurve(item).Save(filename); } private static CurveFileInfo EnsureFileInfo(ListViewItem item) { if (item.Tag == null) item.Tag = new CurveFileInfo(); return item.Tag as CurveFileInfo; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace System.Globalization { internal partial class CultureData { // ICU constants const int ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY = 100; // max size of keyword or value const int ICU_ULOC_FULLNAME_CAPACITY = 157; // max size of locale name const string ICU_COLLATION_KEYWORD = "@collation="; /// <summary> /// This method uses the sRealName field (which is initialized by the constructor before this is called) to /// initialize the rest of the state of CultureData based on the underlying OS globalization library. /// </summary> private unsafe bool InitCultureData() { Debug.Assert(_sRealName != null); Debug.Assert(!GlobalizationMode.Invariant); string alternateSortName = string.Empty; string realNameBuffer = _sRealName; // Basic validation if (realNameBuffer.Contains('@')) { return false; // don't allow ICU variants to come in directly } // Replace _ (alternate sort) with @collation= for ICU int index = realNameBuffer.IndexOf('_'); if (index > 0) { if (index >= (realNameBuffer.Length - 1) // must have characters after _ || realNameBuffer.Substring(index + 1).Contains('_')) // only one _ allowed { return false; // fail } alternateSortName = realNameBuffer.Substring(index + 1); realNameBuffer = realNameBuffer.Substring(0, index) + ICU_COLLATION_KEYWORD + alternateSortName; } // Get the locale name from ICU if (!GetLocaleName(realNameBuffer, out _sWindowsName)) { return false; // fail } // Replace the ICU collation keyword with an _ index = _sWindowsName.IndexOf(ICU_COLLATION_KEYWORD, StringComparison.Ordinal); if (index >= 0) { _sName = _sWindowsName.Substring(0, index) + "_" + alternateSortName; } else { _sName = _sWindowsName; } _sRealName = _sName; _iLanguage = this.ILANGUAGE; if (_iLanguage == 0) { _iLanguage = CultureInfo.LOCALE_CUSTOM_UNSPECIFIED; } _bNeutral = (this.SISO3166CTRYNAME.Length == 0); _sSpecificCulture = _bNeutral ? LocaleData.GetSpecificCultureName(_sRealName) : _sRealName; // Remove the sort from sName unless custom culture if (index>0 && !_bNeutral && !IsCustomCultureId(_iLanguage)) { _sName = _sWindowsName.Substring(0, index); } return true; } internal static bool GetLocaleName(string localeName, out string windowsName) { // Get the locale name from ICU StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY); if (!Interop.Globalization.GetLocaleName(localeName, sb, sb.Capacity)) { StringBuilderCache.Release(sb); windowsName = null; return false; // fail } // Success - use the locale name returned which may be different than realNameBuffer (casing) windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls return true; } internal static bool GetDefaultLocaleName(out string windowsName) { // Get the default (system) locale name from ICU StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY); if (!Interop.Globalization.GetDefaultLocaleName(sb, sb.Capacity)) { StringBuilderCache.Release(sb); windowsName = null; return false; // fail } // Success - use the locale name returned which may be different than realNameBuffer (casing) windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls return true; } private string GetLocaleInfo(LocaleStringData type) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already"); return GetLocaleInfo(_sWindowsName, type); } // For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the // "windows" name, which can be specific for downlevel (< windows 7) os's. private string GetLocaleInfo(string localeName, LocaleStringData type) { Debug.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null"); switch (type) { case LocaleStringData.NegativeInfinitySymbol: // not an equivalent in ICU; prefix the PositiveInfinitySymbol with NegativeSign return GetLocaleInfo(localeName, LocaleStringData.NegativeSign) + GetLocaleInfo(localeName, LocaleStringData.PositiveInfinitySymbol); } StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY); bool result = Interop.Globalization.GetLocaleInfoString(localeName, (uint)type, sb, sb.Capacity); if (!result) { // Failed, just use empty string StringBuilderCache.Release(sb); Debug.Fail("[CultureData.GetLocaleInfo(LocaleStringData)] Failed"); return string.Empty; } return StringBuilderCache.GetStringAndRelease(sb); } private int GetLocaleInfo(LocaleNumberData type) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already"); switch (type) { case LocaleNumberData.CalendarType: // returning 0 will cause the first supported calendar to be returned, which is the preferred calendar return 0; } int value = 0; bool result = Interop.Globalization.GetLocaleInfoInt(_sWindowsName, (uint)type, ref value); if (!result) { // Failed, just use 0 Debug.Fail("[CultureData.GetLocaleInfo(LocaleNumberData)] failed"); } return value; } private int[] GetLocaleInfo(LocaleGroupingData type) { Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already"); int primaryGroupingSize = 0; int secondaryGroupingSize = 0; bool result = Interop.Globalization.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize); if (!result) { Debug.Fail("[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed"); } if (secondaryGroupingSize == 0) { return new int[] { primaryGroupingSize }; } return new int[] { primaryGroupingSize, secondaryGroupingSize }; } private string GetTimeFormatString() { return GetTimeFormatString(false); } private string GetTimeFormatString(bool shortFormat) { Debug.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already"); StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY); bool result = Interop.Globalization.GetLocaleTimeFormat(_sWindowsName, shortFormat, sb, sb.Capacity); if (!result) { // Failed, just use empty string StringBuilderCache.Release(sb); Debug.Fail("[CultureData.GetTimeFormatString(bool shortFormat)] Failed"); return string.Empty; } return ConvertIcuTimeFormatString(StringBuilderCache.GetStringAndRelease(sb)); } private int GetFirstDayOfWeek() { return this.GetLocaleInfo(LocaleNumberData.FirstDayOfWeek); } private string[] GetTimeFormats() { string format = GetTimeFormatString(false); return new string[] { format }; } private string[] GetShortTimeFormats() { string format = GetTimeFormatString(true); return new string[] { format }; } private static CultureData GetCultureDataFromRegionName(string regionName) { // no support to lookup by region name, other than the hard-coded list in CultureData return null; } private static string GetLanguageDisplayName(string cultureName) { return new CultureInfo(cultureName)._cultureData.GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName); } private static string GetRegionDisplayName(string isoCountryCode) { // use the fallback which is to return NativeName return null; } private static CultureInfo GetUserDefaultCulture() { return CultureInfo.GetUserDefaultCulture(); } private static string ConvertIcuTimeFormatString(string icuFormatString) { StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY); bool amPmAdded = false; for (int i = 0; i < icuFormatString.Length; i++) { switch(icuFormatString[i]) { case ':': case '.': case 'H': case 'h': case 'm': case 's': sb.Append(icuFormatString[i]); break; case ' ': case '\u00A0': // Convert nonbreaking spaces into regular spaces sb.Append(' '); break; case 'a': // AM/PM if (!amPmAdded) { amPmAdded = true; sb.Append("tt"); } break; } } return StringBuilderCache.GetStringAndRelease(sb); } private static string LCIDToLocaleName(int culture) { Debug.Assert(!GlobalizationMode.Invariant); return LocaleData.LCIDToLocaleName(culture); } private static int LocaleNameToLCID(string cultureName) { Debug.Assert(!GlobalizationMode.Invariant); int lcid = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.Lcid); return lcid == -1 ? CultureInfo.LOCALE_CUSTOM_UNSPECIFIED : lcid; } private static int GetAnsiCodePage(string cultureName) { int ansiCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.AnsiCodePage); return ansiCodePage == -1 ? CultureData.Invariant.IDEFAULTANSICODEPAGE : ansiCodePage; } private static int GetOemCodePage(string cultureName) { int oemCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.OemCodePage); return oemCodePage == -1 ? CultureData.Invariant.IDEFAULTOEMCODEPAGE : oemCodePage; } private static int GetMacCodePage(string cultureName) { int macCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.MacCodePage); return macCodePage == -1 ? CultureData.Invariant.IDEFAULTMACCODEPAGE : macCodePage; } private static int GetEbcdicCodePage(string cultureName) { int ebcdicCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.EbcdicCodePage); return ebcdicCodePage == -1 ? CultureData.Invariant.IDEFAULTEBCDICCODEPAGE : ebcdicCodePage; } private static int GetGeoId(string cultureName) { int geoId = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.GeoId); return geoId == -1 ? CultureData.Invariant.IGEOID : geoId; } private static int GetDigitSubstitution(string cultureName) { int digitSubstitution = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.DigitSubstitution); return digitSubstitution == -1 ? (int) DigitShapes.None : digitSubstitution; } private static string GetThreeLetterWindowsLanguageName(string cultureName) { string langName = LocaleData.GetThreeLetterWindowsLangageName(cultureName); return langName == null ? "ZZZ" /* default lang name */ : langName; } private static CultureInfo[] EnumCultures(CultureTypes types) { Debug.Assert(!GlobalizationMode.Invariant); if ((types & (CultureTypes.NeutralCultures | CultureTypes.SpecificCultures)) == 0) { return Array.Empty<CultureInfo>(); } int bufferLength = Interop.Globalization.GetLocales(null, 0); if (bufferLength <= 0) { return Array.Empty<CultureInfo>(); } char [] chars = new char[bufferLength]; bufferLength = Interop.Globalization.GetLocales(chars, bufferLength); if (bufferLength <= 0) { return Array.Empty<CultureInfo>(); } bool enumNeutrals = (types & CultureTypes.NeutralCultures) != 0; bool enumSpecificss = (types & CultureTypes.SpecificCultures) != 0; List<CultureInfo> list = new List<CultureInfo>(); if (enumNeutrals) { list.Add(CultureInfo.InvariantCulture); } int index = 0; while (index < bufferLength) { int length = (int) chars[index++]; if (index + length <= bufferLength) { CultureInfo ci = CultureInfo.GetCultureInfo(new string(chars, index, length)); if ((enumNeutrals && ci.IsNeutralCulture) || (enumSpecificss && !ci.IsNeutralCulture)) { list.Add(ci); } } index += length; } return list.ToArray(); } private static string GetConsoleFallbackName(string cultureName) { return LocaleData.GetConsoleUICulture(cultureName); } internal bool IsFramework // not applicable on Linux based systems { get { return false; } } internal bool IsWin32Installed // not applicable on Linux based systems { get { return false; } } internal bool IsReplacementCulture // not applicable on Linux based systems { get { 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.IO; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Net.Security { public enum EncryptionPolicy { // Prohibit null ciphers (current system defaults) RequireEncryption = 0, // Add null ciphers to current system defaults AllowNoEncryption, // Request null ciphers only NoEncryption } // A user delegate used to verify remote SSL certificate. public delegate bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors); // A user delegate used to select local SSL certificate. public delegate X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers); // Internal versions of the above delegates. internal delegate bool RemoteCertValidationCallback(string host, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors); internal delegate X509Certificate LocalCertSelectionCallback(string targetHost, X509CertificateCollection localCertificates, X509Certificate2 remoteCertificate, string[] acceptableIssuers); public class SslStream : AuthenticatedStream { private SslState _sslState; private RemoteCertificateValidationCallback _userCertificateValidationCallback; private LocalCertificateSelectionCallback _userCertificateSelectionCallback; private object _remoteCertificateOrBytes; public SslStream(Stream innerStream) : this(innerStream, false, null, null) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen) : this(innerStream, leaveInnerStreamOpen, null, null, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback) : this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, null, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback) : this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy) : base(innerStream, leaveInnerStreamOpen) { if (encryptionPolicy != EncryptionPolicy.RequireEncryption && encryptionPolicy != EncryptionPolicy.AllowNoEncryption && encryptionPolicy != EncryptionPolicy.NoEncryption) { throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(encryptionPolicy)); } _userCertificateValidationCallback = userCertificateValidationCallback; _userCertificateSelectionCallback = userCertificateSelectionCallback; RemoteCertValidationCallback _userCertValidationCallbackWrapper = new RemoteCertValidationCallback(UserCertValidationCallbackWrapper); LocalCertSelectionCallback _userCertSelectionCallbackWrapper = userCertificateSelectionCallback == null ? null : new LocalCertSelectionCallback(UserCertSelectionCallbackWrapper); _sslState = new SslState(innerStream, _userCertValidationCallbackWrapper, _userCertSelectionCallbackWrapper, encryptionPolicy); } private bool UserCertValidationCallbackWrapper(string hostName, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { _remoteCertificateOrBytes = certificate == null ? null : certificate.RawData; if (_userCertificateValidationCallback == null) { if (!_sslState.RemoteCertRequired) { sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNotAvailable; } return (sslPolicyErrors == SslPolicyErrors.None); } else { return _userCertificateValidationCallback(this, certificate, chain, sslPolicyErrors); } } private X509Certificate UserCertSelectionCallbackWrapper(string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) { return _userCertificateSelectionCallback(this, targetHost, localCertificates, remoteCertificate, acceptableIssuers); } // // Client side auth. // public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient(targetHost, new X509CertificateCollection(), SecurityProtocol.SystemDefaultSecurityProtocols, false, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState) { SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols); _sslState.ValidateCreateContext(false, targetHost, enabledSslProtocols, null, clientCertificates, true, checkCertificateRevocation); LazyAsyncResult result = new LazyAsyncResult(_sslState, asyncState, asyncCallback); _sslState.ProcessAuthentication(result); return result; } public virtual void EndAuthenticateAsClient(IAsyncResult asyncResult) { _sslState.EndProcessAuthentication(asyncResult); } // // Server side auth. // public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsServer(serverCertificate, false, SecurityProtocol.SystemDefaultSecurityProtocols, false, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState) { SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols); _sslState.ValidateCreateContext(true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired, checkCertificateRevocation); LazyAsyncResult result = new LazyAsyncResult(_sslState, asyncState, asyncCallback); _sslState.ProcessAuthentication(result); return result; } public virtual void EndAuthenticateAsServer(IAsyncResult asyncResult) { _sslState.EndProcessAuthentication(asyncResult); } internal virtual IAsyncResult BeginShutdown(AsyncCallback asyncCallback, object asyncState) { return _sslState.BeginShutdown(asyncCallback, asyncState); } internal virtual void EndShutdown(IAsyncResult asyncResult) { _sslState.EndShutdown(asyncResult); } public TransportContext TransportContext { get { return new SslStreamContext(this); } } internal ChannelBinding GetChannelBinding(ChannelBindingKind kind) { return _sslState.GetChannelBinding(kind); } #region Synchronous methods public virtual void AuthenticateAsClient(string targetHost) { AuthenticateAsClient(targetHost, new X509CertificateCollection(), SecurityProtocol.SystemDefaultSecurityProtocols, false); } public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation) { AuthenticateAsClient(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); } public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols); _sslState.ValidateCreateContext(false, targetHost, enabledSslProtocols, null, clientCertificates, true, checkCertificateRevocation); _sslState.ProcessAuthentication(null); } public virtual void AuthenticateAsServer(X509Certificate serverCertificate) { AuthenticateAsServer(serverCertificate, false, SecurityProtocol.SystemDefaultSecurityProtocols, false); } public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { AuthenticateAsServer(serverCertificate, clientCertificateRequired, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); } public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols); _sslState.ValidateCreateContext(true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired, checkCertificateRevocation); _sslState.ProcessAuthentication(null); } #endregion #region Task-based async public methods public virtual Task AuthenticateAsClientAsync(string targetHost) { return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, targetHost, null); } public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation) { return AuthenticateAsClientAsync(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); } public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, callback, state), EndAuthenticateAsClient, null); } public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate) { return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, serverCertificate, null); } public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { return AuthenticateAsServerAsync(serverCertificate, clientCertificateRequired, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); } public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, callback, state), EndAuthenticateAsServer, null); } public virtual Task ShutdownAsync() { return Task.Factory.FromAsync( (callback, state) => BeginShutdown(callback, state), EndShutdown, null); } #endregion public override bool IsAuthenticated { get { return _sslState.IsAuthenticated; } } public override bool IsMutuallyAuthenticated { get { return _sslState.IsMutuallyAuthenticated; } } public override bool IsEncrypted { get { return IsAuthenticated; } } public override bool IsSigned { get { return IsAuthenticated; } } public override bool IsServer { get { return _sslState.IsServer; } } public virtual SslProtocols SslProtocol { get { return _sslState.SslProtocol; } } public virtual bool CheckCertRevocationStatus { get { return _sslState.CheckCertRevocationStatus; } } public virtual X509Certificate LocalCertificate { get { return _sslState.LocalCertificate; } } public virtual X509Certificate RemoteCertificate { get { _sslState.CheckThrow(true); object chkCertificateOrBytes = _remoteCertificateOrBytes; if (chkCertificateOrBytes != null && chkCertificateOrBytes.GetType() == typeof(byte[])) { return (X509Certificate)(_remoteCertificateOrBytes = new X509Certificate2((byte[])chkCertificateOrBytes)); } else { return chkCertificateOrBytes as X509Certificate; } } } public virtual CipherAlgorithmType CipherAlgorithm { get { return _sslState.CipherAlgorithm; } } public virtual int CipherStrength { get { return _sslState.CipherStrength; } } public virtual HashAlgorithmType HashAlgorithm { get { return _sslState.HashAlgorithm; } } public virtual int HashStrength { get { return _sslState.HashStrength; } } public virtual ExchangeAlgorithmType KeyExchangeAlgorithm { get { return _sslState.KeyExchangeAlgorithm; } } public virtual int KeyExchangeStrength { get { return _sslState.KeyExchangeStrength; } } // // Stream contract implementation. // public override bool CanSeek { get { return false; } } public override bool CanRead { get { return _sslState.IsAuthenticated && InnerStream.CanRead; } } public override bool CanTimeout { get { return InnerStream.CanTimeout; } } public override bool CanWrite { get { return _sslState.IsAuthenticated && InnerStream.CanWrite && !_sslState.IsShutdown; } } public override int ReadTimeout { get { return InnerStream.ReadTimeout; } set { InnerStream.ReadTimeout = value; } } public override int WriteTimeout { get { return InnerStream.WriteTimeout; } set { InnerStream.WriteTimeout = value; } } public override long Length { get { return InnerStream.Length; } } public override long Position { get { return InnerStream.Position; } set { throw new NotSupportedException(SR.net_noseek); } } public override void SetLength(long value) { InnerStream.SetLength(value); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.net_noseek); } public override void Flush() { _sslState.Flush(); } public override Task FlushAsync(CancellationToken cancellationToken) { return _sslState.FlushAsync(cancellationToken); } protected override void Dispose(bool disposing) { try { _sslState.Close(); } finally { base.Dispose(disposing); } } public override int ReadByte() { return _sslState.SecureStream.ReadByte(); } public override int Read(byte[] buffer, int offset, int count) { return _sslState.SecureStream.Read(buffer, offset, count); } public void Write(byte[] buffer) { _sslState.SecureStream.Write(buffer, 0, buffer.Length); } public override void Write(byte[] buffer, int offset, int count) { _sslState.SecureStream.Write(buffer, offset, count); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { return _sslState.SecureStream.BeginRead(buffer, offset, count, asyncCallback, asyncState); } public override int EndRead(IAsyncResult asyncResult) { return _sslState.SecureStream.EndRead(asyncResult); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { return _sslState.SecureStream.BeginWrite(buffer, offset, count, asyncCallback, asyncState); } public override void EndWrite(IAsyncResult asyncResult) { _sslState.SecureStream.EndWrite(asyncResult); } } }
// 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.Globalization; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// The pattern matcher is thread-safe. However, it maintains an internal cache of /// information as it is used. Therefore, you should not keep it around forever and should get /// and release the matcher appropriately once you no longer need it. /// Also, while the pattern matcher is culture aware, it uses the culture specified in the /// constructor. /// </summary> internal sealed partial class PatternMatcher : IDisposable { private static readonly char[] s_dotCharacterArray = { '.' }; private readonly object _gate = new object(); private readonly bool _allowFuzzyMatching; private readonly bool _invalidPattern; private readonly Segment _fullPatternSegment; private readonly Segment[] _dotSeparatedSegments; private readonly Dictionary<string, StringBreaks> _stringToWordSpans = new Dictionary<string, StringBreaks>(); private readonly Func<string, StringBreaks> _breakIntoWordSpans = StringBreaker.BreakIntoWordParts; // PERF: Cache the culture's compareInfo to avoid the overhead of asking for them repeatedly in inner loops private readonly CompareInfo _compareInfo; /// <summary> /// Construct a new PatternMatcher using the calling thread's culture for string searching and comparison. /// </summary> public PatternMatcher( string pattern, bool verbatimIdentifierPrefixIsWordCharacter = false, bool allowFuzzyMatching = false) : this(pattern, CultureInfo.CurrentCulture, verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching) { } /// <summary> /// Construct a new PatternMatcher using the specified culture. /// </summary> /// <param name="pattern">The pattern to make the pattern matcher for.</param> /// <param name="culture">The culture to use for string searching and comparison.</param> /// <param name="verbatimIdentifierPrefixIsWordCharacter">Whether to consider "@" as a word character</param> /// <param name="allowFuzzyMatching">Whether or not close matches should count as matches.</param> public PatternMatcher( string pattern, CultureInfo culture, bool verbatimIdentifierPrefixIsWordCharacter, bool allowFuzzyMatching) { pattern = pattern.Trim(); _compareInfo = culture.CompareInfo; _allowFuzzyMatching = allowFuzzyMatching; _fullPatternSegment = new Segment(pattern, verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching); if (pattern.IndexOf('.') < 0) { // PERF: Avoid string.Split allocations when the pattern doesn't contain a dot. _dotSeparatedSegments = pattern.Length > 0 ? new Segment[1] { _fullPatternSegment } : Array.Empty<Segment>(); } else { _dotSeparatedSegments = pattern.Split(s_dotCharacterArray, StringSplitOptions.RemoveEmptyEntries) .Select(text => new Segment(text.Trim(), verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching)) .ToArray(); } _invalidPattern = _dotSeparatedSegments.Length == 0 || _dotSeparatedSegments.Any(s => s.IsInvalid); } public void Dispose() { _fullPatternSegment.Dispose(); foreach (var segment in _dotSeparatedSegments) { segment.Dispose(); } } public bool IsDottedPattern => _dotSeparatedSegments.Length > 1; private bool SkipMatch(string candidate) { return _invalidPattern || string.IsNullOrWhiteSpace(candidate); } public IEnumerable<PatternMatch> GetMatches(string candidate) { return GetMatches(candidate, includeMatchSpans: false); } /// <summary> /// Determines if a given candidate string matches under a multiple word query text, as you /// would find in features like Navigate To. /// </summary> /// <param name="candidate">The word being tested.</param> /// <param name="includeMatchSpans">Whether or not the matched spans should be included with results</param> /// <returns>If this was a match, a set of match types that occurred while matching the /// patterns. If it was not a match, it returns null.</returns> public IEnumerable<PatternMatch> GetMatches(string candidate, bool includeMatchSpans) { if (SkipMatch(candidate)) { return null; } return MatchSegment(candidate, includeMatchSpans, _fullPatternSegment, fuzzyMatch: true) ?? MatchSegment(candidate, includeMatchSpans, _fullPatternSegment, fuzzyMatch: false); } public IEnumerable<PatternMatch> GetMatchesForLastSegmentOfPattern(string candidate) { if (SkipMatch(candidate)) { return null; } return MatchSegment(candidate, includeMatchSpans: false, segment: _dotSeparatedSegments.Last(), fuzzyMatch: false) ?? MatchSegment(candidate, includeMatchSpans: false, segment: _dotSeparatedSegments.Last(), fuzzyMatch: true); } public IEnumerable<PatternMatch> GetMatches(string candidate, string dottedContainer) { return GetMatches(candidate, dottedContainer, includeMatchSpans: false); } /// <summary> /// Matches a pattern against a candidate, and an optional dotted container for the /// candidate. If the container is provided, and the pattern itself contains dots, then /// the pattern will be tested against the candidate and container. Specifically, /// the part of the pattern after the last dot will be tested against the candidate. If /// a match occurs there, then the remaining dot-separated portions of the pattern will /// be tested against every successive portion of the container from right to left. /// /// i.e. if you have a pattern of "Con.WL" and the candidate is "WriteLine" with a /// dotted container of "System.Console", then "WL" will be tested against "WriteLine". /// With a match found there, "Con" will then be tested against "Console". /// </summary> public IEnumerable<PatternMatch> GetMatches( string candidate, string dottedContainer, bool includeMatchSpans) { return GetMatches(candidate, dottedContainer, includeMatchSpans, fuzzyMatch: false) ?? GetMatches(candidate, dottedContainer, includeMatchSpans, fuzzyMatch: true); } private IEnumerable<PatternMatch> GetMatches( string candidate, string dottedContainer, bool includeMatchSpans, bool fuzzyMatch) { if (fuzzyMatch && !_allowFuzzyMatching) { return null; } if (SkipMatch(candidate)) { return null; } // First, check that the last part of the dot separated pattern matches the name of the // candidate. If not, then there's no point in proceeding and doing the more // expensive work. var candidateMatch = MatchSegment(candidate, includeMatchSpans, _dotSeparatedSegments.Last(), fuzzyMatch); if (candidateMatch == null) { return null; } dottedContainer = dottedContainer ?? string.Empty; var containerParts = dottedContainer.Split(s_dotCharacterArray, StringSplitOptions.RemoveEmptyEntries); // -1 because the last part was checked against the name, and only the rest // of the parts are checked against the container. var relevantDotSeparatedSegmentLength = _dotSeparatedSegments.Length - 1; if (relevantDotSeparatedSegmentLength > containerParts.Length) { // There weren't enough container parts to match against the pattern parts. // So this definitely doesn't match. return null; } // So far so good. Now break up the container for the candidate and check if all // the dotted parts match up correctly. var totalMatch = new List<PatternMatch>(); // Don't need to check the last segment. We did that as the very first bail out step. for (int i = 0, j = containerParts.Length - relevantDotSeparatedSegmentLength; i < relevantDotSeparatedSegmentLength; i++, j++) { var segment = _dotSeparatedSegments[i]; var containerName = containerParts[j]; var containerMatch = MatchSegment(containerName, includeMatchSpans, segment, fuzzyMatch); if (containerMatch == null) { // This container didn't match the pattern piece. So there's no match at all. return null; } totalMatch.AddRange(containerMatch); } totalMatch.AddRange(candidateMatch); // Success, this symbol's full name matched against the dotted name the user was asking // about. return totalMatch; } /// <summary> /// Determines if a given candidate string matches under a multiple word query text, as you /// would find in features like Navigate To. /// </summary> /// <remarks> /// PERF: This is slightly faster and uses less memory than <see cref="GetMatches(string, bool)"/> /// so, unless you need to know the full set of matches, use this version. /// </remarks> /// <param name="candidate">The word being tested.</param> /// <param name="inludeMatchSpans">Whether or not the matched spans should be included with results</param> /// <returns>If this was a match, the first element of the set of match types that occurred while matching the /// patterns. If it was not a match, it returns null.</returns> public PatternMatch? GetFirstMatch(string candidate, bool inludeMatchSpans = false) { if (SkipMatch(candidate)) { return null; } PatternMatch[] ignored; return MatchSegment(candidate, inludeMatchSpans, _fullPatternSegment, wantAllMatches: false, allMatches: out ignored, fuzzyMatch: false) ?? MatchSegment(candidate, inludeMatchSpans, _fullPatternSegment, wantAllMatches: false, allMatches: out ignored, fuzzyMatch: true); } private StringBreaks GetWordSpans(string word) { lock (_gate) { return _stringToWordSpans.GetOrAdd(word, _breakIntoWordSpans); } } internal PatternMatch? MatchSingleWordPattern_ForTestingOnly(string candidate) { return MatchTextChunk(candidate, includeMatchSpans: true, chunk: _fullPatternSegment.TotalTextChunk, punctuationStripped: false, fuzzyMatch: false); } private static bool ContainsUpperCaseLetter(string pattern) { // Expansion of "foreach(char ch in pattern)" to avoid a CharEnumerator allocation for (int i = 0; i < pattern.Length; i++) { if (char.IsUpper(pattern[i])) { return true; } } return false; } private PatternMatch? MatchTextChunk( string candidate, bool includeMatchSpans, TextChunk chunk, bool punctuationStripped, bool fuzzyMatch) { int caseInsensitiveIndex = _compareInfo.IndexOf(candidate, chunk.Text, CompareOptions.IgnoreCase); if (caseInsensitiveIndex == 0) { if (chunk.Text.Length == candidate.Length) { // a) Check if the part matches the candidate entirely, in an case insensitive or // sensitive manner. If it does, return that there was an exact match. return new PatternMatch( PatternMatchKind.Exact, punctuationStripped, isCaseSensitive: candidate == chunk.Text, matchedSpan: GetMatchedSpan(includeMatchSpans, 0, candidate.Length)); } else { // b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive // manner. If it does, return that there was a prefix match. return new PatternMatch( PatternMatchKind.Prefix, punctuationStripped, isCaseSensitive: _compareInfo.IsPrefix(candidate, chunk.Text), matchedSpan: GetMatchedSpan(includeMatchSpans, 0, chunk.Text.Length)); } } var isLowercase = !ContainsUpperCaseLetter(chunk.Text); if (isLowercase) { if (caseInsensitiveIndex > 0) { // c) If the part is entirely lowercase, then check if it is contained anywhere in the // candidate in a case insensitive manner. If so, return that there was a substring // match. // // Note: We only have a substring match if the lowercase part is prefix match of some // word part. That way we don't match something like 'Class' when the user types 'a'. // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). var wordSpans = GetWordSpans(candidate); for (int i = 0; i < wordSpans.Count; i++) { var span = wordSpans[i]; if (PartStartsWith(candidate, span, chunk.Text, CompareOptions.IgnoreCase)) { return new PatternMatch(PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: PartStartsWith(candidate, span, chunk.Text, CompareOptions.None), matchedSpan: GetMatchedSpan(includeMatchSpans, span.Start, chunk.Text.Length)); } } } } else { // d) If the part was not entirely lowercase, then check if it is contained in the // candidate in a case *sensitive* manner. If so, return that there was a substring // match. var caseSensitiveIndex = _compareInfo.IndexOf(candidate, chunk.Text); if (caseSensitiveIndex > 0) { return new PatternMatch( PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: true, matchedSpan: GetMatchedSpan(includeMatchSpans, caseSensitiveIndex, chunk.Text.Length)); } } if (!isLowercase) { // e) If the part was not entirely lowercase, then attempt a camel cased match as well. if (chunk.CharacterSpans.Count > 0) { var candidateParts = GetWordSpans(candidate); List<TextSpan> matchedSpans; var camelCaseWeight = TryCamelCaseMatch(candidate, includeMatchSpans, candidateParts, chunk, CompareOptions.None, out matchedSpans); if (camelCaseWeight.HasValue) { return new PatternMatch( PatternMatchKind.CamelCase, punctuationStripped, isCaseSensitive: true, camelCaseWeight: camelCaseWeight, matchedSpans: GetMatchedSpans(includeMatchSpans, matchedSpans)); } camelCaseWeight = TryCamelCaseMatch(candidate, includeMatchSpans, candidateParts, chunk, CompareOptions.IgnoreCase, out matchedSpans); if (camelCaseWeight.HasValue) { return new PatternMatch( PatternMatchKind.CamelCase, punctuationStripped, isCaseSensitive: false, camelCaseWeight: camelCaseWeight, matchedSpans: GetMatchedSpans(includeMatchSpans, matchedSpans)); } } } if (isLowercase) { // f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? // We could check every character boundary start of the candidate for the pattern. However, that's // an m * n operation in the worst case. Instead, find the first instance of the pattern // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to // filter the list based on a substring that starts on a capital letter and also with a lowercase one. // (Pattern: fogbar, Candidate: quuxfogbarFogBar). if (chunk.Text.Length < candidate.Length) { if (caseInsensitiveIndex != -1 && char.IsUpper(candidate[caseInsensitiveIndex])) { return new PatternMatch( PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: false, matchedSpan: GetMatchedSpan(includeMatchSpans, caseInsensitiveIndex, chunk.Text.Length)); } } } if (fuzzyMatch) { if (chunk.SimilarityChecker.AreSimilar(candidate)) { return new PatternMatch( PatternMatchKind.Fuzzy, punctuationStripped, isCaseSensitive: false, matchedSpan: null); } } return null; } private TextSpan[] GetMatchedSpans(bool includeMatchSpans, List<TextSpan> matchedSpans) { return includeMatchSpans ? new NormalizedTextSpanCollection(matchedSpans).ToArray() : null; } private static TextSpan? GetMatchedSpan(bool includeMatchSpans, int start, int length) { return includeMatchSpans ? new TextSpan(start, length) : (TextSpan?)null; } private static bool ContainsSpaceOrAsterisk(string text) { for (int i = 0; i < text.Length; i++) { char ch = text[i]; if (ch == ' ' || ch == '*') { return true; } } return false; } private IEnumerable<PatternMatch> MatchSegment( string candidate, bool includeMatchSpans, Segment segment, bool fuzzyMatch) { if (fuzzyMatch && !_allowFuzzyMatching) { return null; } PatternMatch[] matches; var singleMatch = MatchSegment(candidate, includeMatchSpans, segment, wantAllMatches: true, fuzzyMatch: fuzzyMatch, allMatches: out matches); if (singleMatch.HasValue) { return SpecializedCollections.SingletonEnumerable(singleMatch.Value); } return matches; } /// <summary> /// Internal helper for MatchPatternInternal /// </summary> /// <remarks> /// PERF: Designed to minimize allocations in common cases. /// If there's no match, then null is returned. /// If there's a single match, or the caller only wants the first match, then it is returned (as a Nullable) /// If there are multiple matches, and the caller wants them all, then a List is allocated. /// </remarks> /// <param name="candidate">The word being tested.</param> /// <param name="segment">The segment of the pattern to check against the candidate.</param> /// <param name="wantAllMatches">Does the caller want all matches or just the first?</param> /// <param name="fuzzyMatch">If a fuzzy match should be performed</param> /// <param name="allMatches">If <paramref name="wantAllMatches"/> is true, and there's more than one match, then the list of all matches.</param> /// <param name="includeMatchSpans">Whether or not the matched spans should be included with results</param> /// <returns>If there's only one match, then the return value is that match. Otherwise it is null.</returns> private PatternMatch? MatchSegment( string candidate, bool includeMatchSpans, Segment segment, bool wantAllMatches, bool fuzzyMatch, out PatternMatch[] allMatches) { allMatches = null; if (fuzzyMatch && !_allowFuzzyMatching) { return null; } // First check if the segment matches as is. This is also useful if the segment contains // characters we would normally strip when splitting into parts that we also may want to // match in the candidate. For example if the segment is "@int" and the candidate is // "@int", then that will show up as an exact match here. // // Note: if the segment contains a space or an asterisk then we must assume that it's a // multi-word segment. if (!ContainsSpaceOrAsterisk(segment.TotalTextChunk.Text)) { var match = MatchTextChunk(candidate, includeMatchSpans, segment.TotalTextChunk, punctuationStripped: false, fuzzyMatch: fuzzyMatch); if (match != null) { return match; } } // The logic for pattern matching is now as follows: // // 1) Break the segment passed in into words. Breaking is rather simple and a // good way to think about it that if gives you all the individual alphanumeric words // of the pattern. // // 2) For each word try to match the word against the candidate value. // // 3) Matching is as follows: // // a) Check if the word matches the candidate entirely, in an case insensitive or // sensitive manner. If it does, return that there was an exact match. // // b) Check if the word is a prefix of the candidate, in a case insensitive or // sensitive manner. If it does, return that there was a prefix match. // // c) If the word is entirely lowercase, then check if it is contained anywhere in the // candidate in a case insensitive manner. If so, return that there was a substring // match. // // Note: We only have a substring match if the lowercase part is prefix match of // some word part. That way we don't match something like 'Class' when the user // types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with // 'a'). // // d) If the word was not entirely lowercase, then check if it is contained in the // candidate in a case *sensitive* manner. If so, return that there was a substring // match. // // e) If the word was not entirely lowercase, then attempt a camel cased match as // well. // // f) The word is all lower case. Is it a case insensitive substring of the candidate starting // on a part boundary of the candidate? // // Only if all words have some sort of match is the pattern considered matched. var subWordTextChunks = segment.SubWordTextChunks; PatternMatch[] matches = null; for (int i = 0; i < subWordTextChunks.Length; i++) { var subWordTextChunk = subWordTextChunks[i]; // Try to match the candidate with this word var result = MatchTextChunk(candidate, includeMatchSpans, subWordTextChunk, punctuationStripped: true, fuzzyMatch: fuzzyMatch); if (result == null) { return null; } if (!wantAllMatches || subWordTextChunks.Length == 1) { // Stop at the first word return result; } matches = matches ?? new PatternMatch[subWordTextChunks.Length]; matches[i] = result.Value; } allMatches = matches; return null; } private static bool IsWordChar(char ch, bool verbatimIdentifierPrefixIsWordCharacter) { return char.IsLetterOrDigit(ch) || ch == '_' || (verbatimIdentifierPrefixIsWordCharacter && ch == '@'); } /// <summary> /// Do the two 'parts' match? i.e. Does the candidate part start with the pattern part? /// </summary> /// <param name="candidate">The candidate text</param> /// <param name="candidatePart">The span within the <paramref name="candidate"/> text</param> /// <param name="pattern">The pattern text</param> /// <param name="patternPart">The span within the <paramref name="pattern"/> text</param> /// <param name="compareOptions">Options for doing the comparison (case sensitive or not)</param> /// <returns>True if the span identified by <paramref name="candidatePart"/> within <paramref name="candidate"/> starts with /// the span identified by <paramref name="patternPart"/> within <paramref name="pattern"/>.</returns> private bool PartStartsWith(string candidate, TextSpan candidatePart, string pattern, TextSpan patternPart, CompareOptions compareOptions) { if (patternPart.Length > candidatePart.Length) { // Pattern part is longer than the candidate part. There can never be a match. return false; } return _compareInfo.Compare(candidate, candidatePart.Start, patternPart.Length, pattern, patternPart.Start, patternPart.Length, compareOptions) == 0; } /// <summary> /// Does the given part start with the given pattern? /// </summary> /// <param name="candidate">The candidate text</param> /// <param name="candidatePart">The span within the <paramref name="candidate"/> text</param> /// <param name="pattern">The pattern text</param> /// <param name="compareOptions">Options for doing the comparison (case sensitive or not)</param> /// <returns>True if the span identified by <paramref name="candidatePart"/> within <paramref name="candidate"/> starts with <paramref name="pattern"/></returns> private bool PartStartsWith(string candidate, TextSpan candidatePart, string pattern, CompareOptions compareOptions) { return PartStartsWith(candidate, candidatePart, pattern, new TextSpan(0, pattern.Length), compareOptions); } private int? TryCamelCaseMatch( string candidate, bool includeMatchedSpans, StringBreaks candidateParts, TextChunk chunk, CompareOptions compareOption, out List<TextSpan> matchedSpans) { matchedSpans = null; var chunkCharacterSpans = chunk.CharacterSpans; // Note: we may have more pattern parts than candidate parts. This is because multiple // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U // and I will both match in UI. int currentCandidate = 0; int currentChunkSpan = 0; int? firstMatch = null; bool? contiguous = null; while (true) { // Let's consider our termination cases if (currentChunkSpan == chunkCharacterSpans.Count) { Contract.Requires(firstMatch.HasValue); Contract.Requires(contiguous.HasValue); // We did match! We shall assign a weight to this int weight = 0; // Was this contiguous? if (contiguous.Value) { weight += 1; } // Did we start at the beginning of the candidate? if (firstMatch.Value == 0) { weight += 2; } return weight; } else if (currentCandidate == candidateParts.Count) { // No match, since we still have more of the pattern to hit matchedSpans = null; return null; } var candidatePart = candidateParts[currentCandidate]; bool gotOneMatchThisCandidate = false; // Consider the case of matching SiUI against SimpleUIElement. The candidate parts // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to // still keep matching pattern parts against that candidate part. for (; currentChunkSpan < chunkCharacterSpans.Count; currentChunkSpan++) { var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; if (gotOneMatchThisCandidate) { // We've already gotten one pattern part match in this candidate. We will // only continue trying to consume pattern parts if the last part and this // part are both upper case. if (!char.IsUpper(chunk.Text[chunkCharacterSpans[currentChunkSpan - 1].Start]) || !char.IsUpper(chunk.Text[chunkCharacterSpans[currentChunkSpan].Start])) { break; } } if (!PartStartsWith(candidate, candidatePart, chunk.Text, chunkCharacterSpan, compareOption)) { break; } if (includeMatchedSpans) { matchedSpans = matchedSpans ?? new List<TextSpan>(); matchedSpans.Add(new TextSpan(candidatePart.Start, chunkCharacterSpan.Length)); } gotOneMatchThisCandidate = true; firstMatch = firstMatch ?? currentCandidate; // If we were contiguous, then keep that value. If we weren't, then keep that // value. If we don't know, then set the value to 'true' as an initial match is // obviously contiguous. contiguous = contiguous ?? true; candidatePart = new TextSpan(candidatePart.Start + chunkCharacterSpan.Length, candidatePart.Length - chunkCharacterSpan.Length); } // Check if we matched anything at all. If we didn't, then we need to unset the // contiguous bit if we currently had it set. // If we haven't set the bit yet, then that means we haven't matched anything so // far, and we don't want to change that. if (!gotOneMatchThisCandidate && contiguous.HasValue) { contiguous = false; } // Move onto the next candidate. currentCandidate++; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Lab3.Areas.HelpPage.ModelDescriptions; using Lab3.Areas.HelpPage.Models; namespace Lab3.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
#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.Collections.Generic; using System.ComponentModel; #if HAVE_DYNAMIC using System.Dynamic; #endif using System.Diagnostics; using System.Globalization; using System.IO; using System.Security; using Microsoft.Identity.Json.Linq; using Microsoft.Identity.Json.Utilities; using System.Runtime.Serialization; #if !HAVE_LINQ using Microsoft.Identity.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Microsoft.Identity.Json.Serialization { internal class JsonSerializerInternalWriter : JsonSerializerInternalBase { private Type _rootType; private int _rootLevel; private readonly List<object> _serializeStack = new List<object>(); public JsonSerializerInternalWriter(JsonSerializer serializer) : base(serializer) { } public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { if (jsonWriter == null) { throw new ArgumentNullException(nameof(jsonWriter)); } _rootType = objectType; _rootLevel = _serializeStack.Count + 1; JsonContract contract = GetContractSafe(value); try { if (ShouldWriteReference(value, null, contract, null, null)) { WriteReference(jsonWriter, value); } else { SerializeValue(jsonWriter, value, contract, null, null, null); } } catch (Exception ex) { if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex)) { HandleError(jsonWriter, 0); } else { // clear context in case serializer is being used inside a converter // if the converter wraps the error then not clearing the context will cause this error: // "Current error context error is different to requested error." ClearErrorContext(); throw; } } finally { // clear root contract to ensure that if level was > 1 then it won't // accidentally be used for non root values _rootType = null; } } private JsonSerializerProxy GetInternalSerializer() { if (InternalSerializer == null) { InternalSerializer = new JsonSerializerProxy(this); } return InternalSerializer; } private JsonContract GetContractSafe(object value) { if (value == null) { return null; } return Serializer._contractResolver.ResolveContract(value.GetType()); } private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { if (contract.TypeCode == PrimitiveTypeCode.Bytes) { // if type name handling is enabled then wrap the base64 byte string in an object with the type name bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty); if (includeTypeDetails) { writer.WriteStartObject(); WriteTypeProperty(writer, contract.CreatedType); writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false); JsonWriter.WriteValue(writer, contract.TypeCode, value); writer.WriteEndObject(); return; } } JsonWriter.WriteValue(writer, contract.TypeCode, value); } private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { if (value == null) { writer.WriteNull(); return; } JsonConverter converter = member?.Converter ?? containerProperty?.ItemConverter ?? containerContract?.ItemConverter ?? valueContract.Converter ?? Serializer.GetMatchingConverter(valueContract.UnderlyingType) ?? valueContract.InternalConverter; if (converter != null && converter.CanWrite) { SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty); return; } switch (valueContract.ContractType) { case JsonContractType.Object: SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty); break; case JsonContractType.Array: JsonArrayContract arrayContract = (JsonArrayContract)valueContract; if (!arrayContract.IsMultidimensionalArray) { SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty); } else { SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty); } break; case JsonContractType.Primitive: SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty); break; case JsonContractType.String: SerializeString(writer, value, (JsonStringContract)valueContract); break; case JsonContractType.Dictionary: JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract; SerializeDictionary(writer, (value is IDictionary dictionary) ? dictionary : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty); break; #if HAVE_DYNAMIC case JsonContractType.Dynamic: SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty); break; #endif #if HAVE_BINARY_SERIALIZATION case JsonContractType.Serializable: SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty); break; #endif case JsonContractType.Linq: ((JToken)value).WriteTo(writer, Serializer.Converters.ToArray()); break; } } private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty) { bool? isReference = null; // value could be coming from a dictionary or array and not have a property if (property != null) { isReference = property.IsReference; } if (isReference == null && containerProperty != null) { isReference = containerProperty.ItemIsReference; } if (isReference == null && collectionContract != null) { isReference = collectionContract.ItemIsReference; } if (isReference == null) { isReference = contract.IsReference; } return isReference; } private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (value == null) { return false; } if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String) { return false; } bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty); if (isReference == null) { if (valueContract.ContractType == JsonContractType.Array) { isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays); } else { isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects); } } if (!isReference.GetValueOrDefault()) { return false; } return Serializer.GetReferenceResolver().IsReferenced(this, value); } private bool ShouldWriteProperty(object memberValue, JsonObjectContract containerContract, JsonProperty property) { if (memberValue == null && ResolvedNullValueHandling(containerContract, property) == NullValueHandling.Ignore) { return false; } if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore) && MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue())) { return false; } return true; } private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty) { if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String) { return true; } ReferenceLoopHandling? referenceLoopHandling = null; if (property != null) { referenceLoopHandling = property.ReferenceLoopHandling; } if (referenceLoopHandling == null && containerProperty != null) { referenceLoopHandling = containerProperty.ItemReferenceLoopHandling; } if (referenceLoopHandling == null && containerContract != null) { referenceLoopHandling = containerContract.ItemReferenceLoopHandling; } bool exists = (Serializer._equalityComparer != null) ? _serializeStack.Contains(value, Serializer._equalityComparer) : _serializeStack.Contains(value); if (exists) { string message = "Self referencing loop detected"; if (property != null) { message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName); } message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()); switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling)) { case ReferenceLoopHandling.Error: throw JsonSerializationException.Create(null, writer.ContainerPath, message, null); case ReferenceLoopHandling.Ignore: if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null); } return false; case ReferenceLoopHandling.Serialize: if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null); } return true; } } return true; } private void WriteReference(JsonWriter writer, object value) { string reference = GetReference(writer, value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null); } writer.WriteStartObject(); writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false); writer.WriteValue(reference); writer.WriteEndObject(); } private string GetReference(JsonWriter writer, object value) { try { string reference = Serializer.GetReferenceResolver().GetReference(this, value); return reference; } catch (Exception ex) { throw JsonSerializationException.Create(null, writer.ContainerPath, "Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex); } } internal static bool TryConvertToString(object value, Type type, out string s) { #if HAVE_TYPE_DESCRIPTOR if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out TypeConverter converter)) { s = converter.ConvertToInvariantString(value); return true; } #endif #if DOTNET || PORTABLE if (value is Guid || value is Uri || value is TimeSpan) { s = value.ToString(); return true; } #endif type = value as Type; if (type != null) { s = type.AssemblyQualifiedName; return true; } s = null; return false; } private void SerializeString(JsonWriter writer, object value, JsonStringContract contract) { OnSerializing(writer, contract, value); TryConvertToString(value, contract.UnderlyingType, out string s); writer.WriteValue(s); OnSerialized(writer, contract, value); } private void OnSerializing(JsonWriter writer, JsonContract contract, object value) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); } contract.InvokeOnSerializing(value, Serializer._context); } private void OnSerialized(JsonWriter writer, JsonContract contract, object value) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); } contract.InvokeOnSerialized(value, Serializer._context); } private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, value); _serializeStack.Add(value); WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty); int initialDepth = writer.Top; for (int index = 0; index < contract.Properties.Count; index++) { JsonProperty property = contract.Properties[index]; try { if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue)) { continue; } property.WritePropertyName(writer); SerializeValue(writer, memberValue, memberContract, property, contract, member); } catch (Exception ex) { if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex)) { HandleError(writer, initialDepth); } else { throw; } } } IEnumerable<KeyValuePair<object, object>> extensionData = contract.ExtensionDataGetter?.Invoke(value); if (extensionData != null) { foreach (KeyValuePair<object, object> e in extensionData) { JsonContract keyContract = GetContractSafe(e.Key); JsonContract valueContract = GetContractSafe(e.Value); string propertyName = GetPropertyName(writer, e.Key, keyContract, out _); propertyName = (contract.ExtensionDataNameResolver != null) ? contract.ExtensionDataNameResolver(propertyName) : propertyName; if (ShouldWriteReference(e.Value, null, valueContract, contract, member)) { writer.WritePropertyName(propertyName); WriteReference(writer, e.Value); } else { if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member)) { continue; } writer.WritePropertyName(propertyName); SerializeValue(writer, e.Value, valueContract, null, contract, member); } } } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, value); } private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue) { if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value)) { if (property.PropertyContract == null) { property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); } memberValue = property.ValueProvider.GetValue(value); memberContract = property.PropertyContract.IsSealed ? property.PropertyContract : GetContractSafe(memberValue); if (ShouldWriteProperty(memberValue, contract as JsonObjectContract, property)) { if (ShouldWriteReference(memberValue, property, memberContract, contract, member)) { property.WritePropertyName(writer); WriteReference(writer, memberValue); return false; } if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member)) { return false; } if (memberValue == null) { JsonObjectContract objectContract = contract as JsonObjectContract; Required resolvedRequired = property._required ?? objectContract?.ItemRequired ?? Required.Default; if (resolvedRequired == Required.Always) { throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null); } if (resolvedRequired == Required.DisallowNull) { throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a non-null value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null); } } return true; } } memberContract = null; memberValue = null; return false; } private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { writer.WriteStartObject(); bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects); // don't make readonly fields that aren't creator parameters the referenced value because they can't be deserialized to if (isReference && (member == null || member.Writable || HasCreatorParameter(collectionContract, member))) { WriteReferenceIdProperty(writer, contract.UnderlyingType, value); } if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty)) { WriteTypeProperty(writer, contract.UnderlyingType); } } private bool HasCreatorParameter(JsonContainerContract contract, JsonProperty property) { if (!(contract is JsonObjectContract objectContract)) { return false; } return objectContract.CreatorParameters.Contains(property.PropertyName); } private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value) { string reference = GetReference(writer, value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null); } writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false); writer.WriteValue(reference); } private void WriteTypeProperty(JsonWriter writer, Type type) { string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormatHandling, Serializer._serializationBinder); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null); } writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false); writer.WriteValue(typeName); } private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag) { return (value & flag) == flag; } private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag) { return (value & flag) == flag; } private bool HasFlag(TypeNameHandling value, TypeNameHandling flag) { return (value & flag) == flag; } private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty)) { WriteReference(writer, value); } else { if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty)) { return; } _serializeStack.Add(value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null); } converter.WriteJson(writer, value, GetInternalSerializer()); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null); } _serializeStack.RemoveAt(_serializeStack.Count - 1); } } private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { object underlyingList = values is IWrappedCollection wrappedCollection ? wrappedCollection.UnderlyingCollection : values; OnSerializing(writer, contract, underlyingList); _serializeStack.Add(underlyingList); bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty); writer.WriteStartArray(); int initialDepth = writer.Top; int index = 0; // note that an error in the IEnumerable won't be caught foreach (object value in values) { try { JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { WriteReference(writer, value); } else { if (CheckForCircularReference(writer, value, null, valueContract, contract, member)) { SerializeValue(writer, value, valueContract, null, contract, member); } } } catch (Exception ex) { if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex)) { HandleError(writer, initialDepth); } else { throw; } } finally { index++; } } writer.WriteEndArray(); if (hasWrittenMetadataObject) { writer.WriteEndObject(); } _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, underlyingList); } private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, values); _serializeStack.Add(values); bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty); SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, CollectionUtils.ArrayEmpty<int>()); if (hasWrittenMetadataObject) { writer.WriteEndObject(); } _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, values); } private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices) { int dimension = indices.Length; int[] newIndices = new int[dimension + 1]; for (int i = 0; i < dimension; i++) { newIndices[i] = indices[i]; } writer.WriteStartArray(); for (int i = values.GetLowerBound(dimension); i <= values.GetUpperBound(dimension); i++) { newIndices[dimension] = i; bool isTopLevel = newIndices.Length == values.Rank; if (isTopLevel) { object value = values.GetValue(newIndices); try { JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { WriteReference(writer, value); } else { if (CheckForCircularReference(writer, value, null, valueContract, contract, member)) { SerializeValue(writer, value, valueContract, null, contract, member); } } } catch (Exception ex) { if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex)) { HandleError(writer, initialDepth + 1); } else { throw; } } } else { SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices); } } writer.WriteEndArray(); } private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays); // don't make readonly fields that aren't creator parameters the referenced value because they can't be deserialized to isReference = isReference && (member == null || member.Writable || HasCreatorParameter(containerContract, member)); bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty); bool writeMetadataObject = isReference || includeTypeDetails; if (writeMetadataObject) { writer.WriteStartObject(); if (isReference) { WriteReferenceIdProperty(writer, contract.UnderlyingType, values); } if (includeTypeDetails) { WriteTypeProperty(writer, values.GetType()); } writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false); } if (contract.ItemContract == null) { contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object)); } return writeMetadataObject; } #if HAVE_BINARY_SERIALIZATION #if HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE [SecuritySafeCritical] #endif private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (!JsonTypeReflector.FullyTrusted) { string message = @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine + @"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine; message = message.FormatWith(CultureInfo.InvariantCulture, value.GetType()); throw JsonSerializationException.Create(null, writer.ContainerPath, message, null); } OnSerializing(writer, contract, value); _serializeStack.Add(value); WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty); SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter()); value.GetObjectData(serializationInfo, Serializer._context); foreach (SerializationEntry serializationEntry in serializationInfo) { JsonContract valueContract = GetContractSafe(serializationEntry.Value); if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member)) { writer.WritePropertyName(serializationEntry.Name); WriteReference(writer, serializationEntry.Value); } else if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member)) { writer.WritePropertyName(serializationEntry.Name); SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member); } } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, value); } #endif #if HAVE_DYNAMIC private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, value); _serializeStack.Add(value); WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty); int initialDepth = writer.Top; for (int index = 0; index < contract.Properties.Count; index++) { JsonProperty property = contract.Properties[index]; // only write non-dynamic properties that have an explicit attribute if (property.HasMemberAttribute) { try { if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue)) { continue; } property.WritePropertyName(writer); SerializeValue(writer, memberValue, memberContract, property, contract, member); } catch (Exception ex) { if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex)) { HandleError(writer, initialDepth); } else { throw; } } } } foreach (string memberName in value.GetDynamicMemberNames()) { if (contract.TryGetMember(value, memberName, out object memberValue)) { try { JsonContract valueContract = GetContractSafe(memberValue); if (!ShouldWriteDynamicProperty(memberValue)) { continue; } if (CheckForCircularReference(writer, memberValue, null, valueContract, contract, member)) { string resolvedPropertyName = (contract.PropertyNameResolver != null) ? contract.PropertyNameResolver(memberName) : memberName; writer.WritePropertyName(resolvedPropertyName); SerializeValue(writer, memberValue, valueContract, null, contract, member); } } catch (Exception ex) { if (IsErrorHandled(value, contract, memberName, null, writer.ContainerPath, ex)) { HandleError(writer, initialDepth); } else { throw; } } } } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, value); } #endif private bool ShouldWriteDynamicProperty(object memberValue) { if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null) { return false; } if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) && (memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType())))) { return false; } return true; } private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { TypeNameHandling resolvedTypeNameHandling = member?.TypeNameHandling ?? containerProperty?.ItemTypeNameHandling ?? containerContract?.ItemTypeNameHandling ?? Serializer._typeNameHandling; if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag)) { return true; } // instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default) if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto)) { if (member != null) { if (contract.NonNullableUnderlyingType != member.PropertyContract.CreatedType) { return true; } } else if (containerContract != null) { if (containerContract.ItemContract == null || contract.NonNullableUnderlyingType != containerContract.ItemContract.CreatedType) { return true; } } else if (_rootType != null && _serializeStack.Count == _rootLevel) { JsonContract rootContract = Serializer._contractResolver.ResolveContract(_rootType); if (contract.NonNullableUnderlyingType != rootContract.CreatedType) { return true; } } } return false; } private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { object underlyingDictionary = values is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : values; OnSerializing(writer, contract, underlyingDictionary); _serializeStack.Add(underlyingDictionary); WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty); if (contract.ItemContract == null) { contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object)); } if (contract.KeyContract == null) { contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object)); } int initialDepth = writer.Top; // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations. IDictionaryEnumerator e = values.GetEnumerator(); try { while (e.MoveNext()) { DictionaryEntry entry = e.Entry; string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out bool escape); propertyName = (contract.DictionaryKeyResolver != null) ? contract.DictionaryKeyResolver(propertyName) : propertyName; try { object value = entry.Value; JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { writer.WritePropertyName(propertyName, escape); WriteReference(writer, value); } else { if (!CheckForCircularReference(writer, value, null, valueContract, contract, member)) { continue; } writer.WritePropertyName(propertyName, escape); SerializeValue(writer, value, valueContract, null, contract, member); } } catch (Exception ex) { if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex)) { HandleError(writer, initialDepth); } else { throw; } } } } finally { (e as IDisposable)?.Dispose(); } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, underlyingDictionary); } private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape) { if (contract.ContractType == JsonContractType.Primitive) { JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract; switch (primitiveContract.TypeCode) { case PrimitiveTypeCode.DateTime: case PrimitiveTypeCode.DateTimeNullable: { DateTime dt = DateTimeUtils.EnsureDateTime((DateTime)name, writer.DateTimeZoneHandling); escape = false; StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); DateTimeUtils.WriteDateTimeString(sw, dt, writer.DateFormatHandling, writer.DateFormatString, writer.Culture); return sw.ToString(); } #if HAVE_DATE_TIME_OFFSET case PrimitiveTypeCode.DateTimeOffset: case PrimitiveTypeCode.DateTimeOffsetNullable: { escape = false; StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture); return sw.ToString(); } #endif case PrimitiveTypeCode.Double: case PrimitiveTypeCode.DoubleNullable: { double d = (double)name; escape = false; return d.ToString("R", CultureInfo.InvariantCulture); } case PrimitiveTypeCode.Single: case PrimitiveTypeCode.SingleNullable: { float f = (float)name; escape = false; return f.ToString("R", CultureInfo.InvariantCulture); } default: { escape = true; if (primitiveContract.IsEnum && EnumUtils.TryToString(primitiveContract.NonNullableUnderlyingType, name, null, out string enumName)) { return enumName; } return Convert.ToString(name, CultureInfo.InvariantCulture); } } } else if (TryConvertToString(name, name.GetType(), out string propertyName)) { escape = true; return propertyName; } else { escape = true; return name.ToString(); } } private void HandleError(JsonWriter writer, int initialDepth) { ClearErrorContext(); if (writer.WriteState == WriteState.Property) { writer.WriteNull(); } while (writer.Top > initialDepth) { writer.WriteEnd(); } } private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target) { if (property.ShouldSerialize == null) { return true; } bool shouldSerialize = property.ShouldSerialize(target); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null); } return shouldSerialize; } private bool IsSpecified(JsonWriter writer, JsonProperty property, object target) { if (property.GetIsSpecified == null) { return true; } bool isSpecified = property.GetIsSpecified(target); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null); } return isSpecified; } } }
/* * FileCodeGroup.cs - Implementation of the * "System.Security.Policy.FileCodeGroup" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Security.Policy { #if CONFIG_POLICY_OBJECTS using System.Collections; using System.Security.Permissions; [Serializable] public sealed class FileCodeGroup : CodeGroup { // Internal state. private FileIOPermissionAccess access; // Constructors. internal FileCodeGroup() {} public FileCodeGroup(IMembershipCondition membershipCondition, FileIOPermissionAccess access) : base(membershipCondition, null) { this.access = access; } // Properties. public override String AttributeString { get { return null; } } public override String MergeLogic { get { return "Union"; } } public override String PermissionSetName { get { return String.Format(_("Format_FileIOPermSetName"), access.ToString()); } } // Make a copy of this code group. public override CodeGroup Copy() { FileCodeGroup group; group = new FileCodeGroup(MembershipCondition, access); group.Name = Name; group.Description = Description; IList children = Children; if(children != null) { foreach(CodeGroup child in children) { group.AddChild(child); } } return group; } // Create the XML form of this code group. protected override void CreateXml (SecurityElement element, PolicyLevel level) { element.AddAttribute("Access", access.ToString()); } // Compare two code groups for equality. public override bool Equals(Object obj) { FileCodeGroup cg = (obj as FileCodeGroup); if(cg != null) { if(!base.Equals(cg)) { return false; } return (cg.access == access); } else { return false; } } // Get the hash code for this instance. public override int GetHashCode() { return base.GetHashCode(); } // Make a policy from url information. private PolicyStatement MakePolicy(UrlParser url) { if(String.Compare(url.Scheme, "file", true) != 0) { return null; } PermissionSet permSet = new PermissionSet (PermissionState.None); permSet.AddPermission(new FileIOPermission(access, url.Rest)); return new PolicyStatement (permSet, PolicyStatementAttribute.Nothing); } // Resolve the policy for this code group. public override PolicyStatement Resolve(Evidence evidence) { PolicyStatement stmt; PolicyStatement childStmt; IEnumerator e; Site site; UrlParser url; // Validate the parameter. if(evidence == null) { throw new ArgumentNullException("evidence"); } // Check the membership condition. if(!MembershipCondition.Check(evidence)) { return null; } // Scan the host evidence for a policy and site. stmt = null; site = null; e = evidence.GetHostEnumerator(); while(e.MoveNext()) { if(e.Current is Url) { url = ((Url)(e.Current)).parser; stmt = MakePolicy(url); } else if(e.Current is Site && site == null) { site = (Site)(e.Current); } } // Create a default policy statement if necessary. if(stmt == null) { stmt = new PolicyStatement (new PermissionSet(PermissionState.None), PolicyStatementAttribute.Nothing); } // Modify the policy statement from this code group. foreach(CodeGroup group in Children) { childStmt = group.Resolve(evidence); if(childStmt != null) { if((stmt.Attributes & PolicyStatementAttribute.Exclusive) != 0 && (childStmt.Attributes & PolicyStatementAttribute.Exclusive) != 0) { throw new PolicyException(_("Security_Exclusive")); } } stmt.PermissionSetNoCopy = stmt.PermissionSetNoCopy.Union (childStmt.PermissionSetNoCopy); stmt.Attributes |= childStmt.Attributes; } return stmt; } // Resolve code groups that match specific evidence. public override CodeGroup ResolveMatchingCodeGroups(Evidence evidence) { FileCodeGroup newGroup; CodeGroup child; // Validate the parameter. if(evidence == null) { throw new ArgumentNullException("evidence"); } // Check the membership condition. if(!MembershipCondition.Check(evidence)) { return null; } // Clone this group, except for the children. newGroup = new FileCodeGroup(MembershipCondition, access); newGroup.Name = Name; newGroup.Description = Description; // Resolve and add the children. foreach(CodeGroup group in Children) { child = group.ResolveMatchingCodeGroups(evidence); if(child != null) { newGroup.AddChild(child); } } // Return the result. return newGroup; } // Parse the XML form of this code group. protected override void ParseXml (SecurityElement element, PolicyLevel level) { String value = element.Attribute("Access"); if(value != null) { access = (FileIOPermissionAccess) Enum.Parse(typeof(FileIOPermissionAccess), value); } else { access = FileIOPermissionAccess.NoAccess; } } }; // class FileCodeGroup #endif // CONFIG_POLICY_OBJECTS }; // namespace System.Security.Policy
#region Header /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Copyright (c) 2007-2008 James Nies and NArrange contributors. * All rights reserved. * * This program and the accompanying materials are made available under * the terms of the Common Public License v1.0 which accompanies this * distribution. * * 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. * * 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. * *<author>James Nies</author> *<contributor>Justin Dearing</contributor> *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #endregion Header namespace NArrange.VisualBasic { using System; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Text; using System.Threading; using NArrange.Core; using NArrange.Core.CodeElements; using NArrange.Core.Configuration; /// <summary> /// Visits a tree of code elements for writing VB code. /// </summary> internal sealed class VBWriteVisitor : CodeWriteVisitor { #region Constructors /// <summary> /// Creates a new VBWriteVisitor. /// </summary> /// <param name="writer">Text writer.</param> /// <param name="configuration">Code configuration.</param> public VBWriteVisitor(TextWriter writer, CodeConfiguration configuration) : base(writer, configuration) { } #endregion Constructors #region Methods /// <summary> /// Processes an attribute element. /// </summary> /// <param name="element">Attribute code element.</param> public override void VisitAttributeElement(AttributeElement element) { this.WriteComments(element.HeaderComments); // HACK: Create an explicit element type for Option (or compiler directive) if (element[VBExtendedProperties.Option] is bool && (bool)element[VBExtendedProperties.Option]) { WriteIndented(element.BodyText); } else { bool nested = element.Parent is AttributeElement; if (!nested) { WriteIndented(VBSymbol.BeginAttribute.ToString()); } if (!string.IsNullOrEmpty(element.Target)) { Writer.Write(element.Target); Writer.Write(VBSymbol.LineDelimiter); Writer.Write(' '); } Writer.Write(element.Name); if (!string.IsNullOrEmpty(element.BodyText)) { Writer.Write(VBSymbol.BeginParameterList); Writer.Write(element.BodyText); Writer.Write(VBSymbol.EndParameterList); } // // Nested list of attributes? // foreach (ICodeElement childElement in element.Children) { AttributeElement childAttribute = childElement as AttributeElement; if (childAttribute != null) { Writer.Write(", _"); Writer.WriteLine(); WriteIndented(string.Empty); childAttribute.Accept(this); } } if (!nested) { Writer.Write(VBSymbol.EndAttribute); if (element.Parent is TextCodeElement) { Writer.Write(" _"); } } if (!nested && element.Parent != null) { Writer.WriteLine(); } } } /// <summary> /// Writes a comment line. /// </summary> /// <param name="comment">The comment.</param> public override void VisitCommentElement(CommentElement comment) { if (comment.Type == CommentType.Block) { throw new InvalidOperationException("Block comments are not supported by VB."); } else { StringBuilder builder = new StringBuilder(DefaultBlockLength); if (comment.Type == CommentType.XmlLine) { builder.Append("'''"); } else { builder.Append("'"); } builder.Append(FormatCommentText(comment)); WriteIndented(builder.ToString()); } } /// <summary> /// Writes a condition directive element. /// </summary> /// <param name="element">Condition directive code element.</param> public override void VisitConditionDirectiveElement(ConditionDirectiveElement element) { const string ConditionFormat = "{0}{1} {2}"; ConditionDirectiveElement conditionDirective = element; this.WriteIndentedLine( string.Format( CultureInfo.InvariantCulture, ConditionFormat, VBSymbol.Preprocessor, VBKeyword.If, element.ConditionExpression)); if (element.Children.Count == 0) { Writer.WriteLine(); } WriteChildren(element); if (element.Children.Count > 0) { Writer.WriteLine(); } while (conditionDirective.ElseCondition != null) { conditionDirective = conditionDirective.ElseCondition; if (conditionDirective.ElseCondition == null) { this.WriteIndentedLine(VBSymbol.Preprocessor + VBKeyword.Else); } else { this.WriteIndentedLine( string.Format( CultureInfo.InvariantCulture, ConditionFormat, VBSymbol.Preprocessor, VBKeyword.ElseIf, conditionDirective.ConditionExpression)); } if (conditionDirective.Children.Count == 0) { Writer.WriteLine(); } WriteChildren(conditionDirective); if (conditionDirective.Children.Count > 0) { Writer.WriteLine(); } } this.WriteIndented(VBSymbol.Preprocessor + VBKeyword.End + " " + VBKeyword.If); } /// <summary> /// Processes a constructor element. /// </summary> /// <param name="element">Constructor code element.</param> public override void VisitConstructorElement(ConstructorElement element) { this.WriteComments(element.HeaderComments); this.WriteAttributes(element); WriteAccess(element.Access); WriteMemberAttributes( element.MemberModifiers, element[VBExtendedProperties.Overloads] is bool && (bool)element[VBExtendedProperties.Overloads]); Writer.Write(VBKeyword.Sub); Writer.Write(' '); Writer.Write(element.Name); WriteParameterList(element.Parameters); if (!string.IsNullOrEmpty(element.Reference)) { TabCount++; Writer.WriteLine(); WriteIndented(element.Reference); TabCount--; } WriteBody(element); } /// <summary> /// Processes a delegate element. /// </summary> /// <param name="element">Delegate code element.</param> public override void VisitDelegateElement(DelegateElement element) { this.WriteComments(element.HeaderComments); this.WriteAttributes(element); WriteAccess(element.Access); WriteMemberAttributes( element.MemberModifiers, element[VBExtendedProperties.Overloads] is bool && (bool)element[VBExtendedProperties.Overloads]); Writer.Write(VBKeyword.Delegate); Writer.Write(' '); WriteMethodType(element.Type); Writer.Write(element.Name); WriteTypeParameters(element); WriteParameterList(element.Parameters); WriteReturnType(element.Type); } /// <summary> /// Processes an event element. /// </summary> /// <param name="element">Event code element.</param> public override void VisitEventElement(EventElement element) { this.WriteComments(element.HeaderComments); this.WriteAttributes(element); WriteAccess(element.Access); WriteMemberAttributes( element.MemberModifiers, element[VBExtendedProperties.Overloads] is bool && (bool)element[VBExtendedProperties.Overloads]); bool isCustom = false; if (element.BodyText != null && element.BodyText.Trim().Length > 0) { isCustom = true; Writer.Write(VBKeyword.Custom); Writer.Write(' '); } Writer.Write(VBKeyword.Event); Writer.Write(' '); Writer.Write(element.Name); if (element.Parameters != null) { WriteParameterList(element.Parameters); } WriteReturnType(element.Type); WriteImplements(element.Implements); if (isCustom) { WriteBody(element); } } /// <summary> /// Processes a field element. /// </summary> /// <param name="element">Field code element.</param> public override void VisitFieldElement(FieldElement element) { this.WriteComments(element.HeaderComments); this.WriteAttributes(element); WriteAccess(element.Access); WriteMemberAttributes( element.MemberModifiers, element[VBExtendedProperties.Overloads] is bool && (bool)element[VBExtendedProperties.Overloads]); if (element[VBExtendedProperties.Dim] is bool && (bool)element[VBExtendedProperties.Dim]) { if (element.Access != CodeAccess.None) { Writer.Write(' '); } Writer.Write(VBKeyword.Dim); Writer.Write(' '); } if (element[VBExtendedProperties.WithEvents] is bool && (bool)element[VBExtendedProperties.WithEvents]) { Writer.Write(' '); Writer.Write(VBKeyword.WithEvents); Writer.Write(' '); } Writer.Write(element.Name); if (!string.IsNullOrEmpty(element.Type)) { WriteReturnType(element.Type); if (!string.IsNullOrEmpty(element.InitialValue)) { Writer.Write(' '); Writer.Write(VBSymbol.Assignment); Writer.Write(' '); Writer.Write(element.InitialValue); } } else if (!string.IsNullOrEmpty(element.InitialValue)) { Writer.Write(' '); if (element.InitialValue.StartsWith(VBKeyword.New + " ")) { Writer.Write(VBKeyword.As); } else { Writer.Write(VBSymbol.Assignment); } Writer.Write(' '); Writer.Write(element.InitialValue); } if (element.TrailingComment != null) { Writer.Write(' '); int tabCountTemp = this.TabCount; this.TabCount = 0; element.TrailingComment.Accept(this); this.TabCount = tabCountTemp; } } /// <summary> /// Processes a method element. /// </summary> /// <param name="element">Method code element.</param> public override void VisitMethodElement(MethodElement element) { this.WriteComments(element.HeaderComments); this.WriteAttributes(element); if (element.IsPartial) { Writer.Write(VBKeyword.Partial); Writer.Write(' '); } WriteAccess(element.Access); if (element.IsExternal) { Writer.Write(VBKeyword.Declare); Writer.Write(' '); } if (element[VBExtendedProperties.ExternalModifier] != null) { Writer.Write(element[VBExtendedProperties.ExternalModifier].ToString()); Writer.Write(' '); } WriteMemberAttributes( element.MemberModifiers, element[VBExtendedProperties.Overloads] is bool && (bool)element[VBExtendedProperties.Overloads]); if (element.IsOperator) { if (element.OperatorType == OperatorType.Explicit) { Writer.Write(VBKeyword.Narrowing); Writer.Write(' '); } else if (element.OperatorType == OperatorType.Implicit) { Writer.Write(VBKeyword.Widening); Writer.Write(' '); } Writer.Write(VBKeyword.Operator); Writer.Write(' '); } else { WriteMethodType(element.Type); } Writer.Write(element.Name); WriteTypeParameters(element); if (element[VBExtendedProperties.ExternalLibrary] != null) { Writer.Write(' '); Writer.Write(VBKeyword.Lib); Writer.Write(' '); Writer.Write(VBSymbol.BeginString); Writer.Write(element[VBExtendedProperties.ExternalLibrary].ToString()); Writer.Write(VBSymbol.BeginString); Writer.Write(' '); } if (element[VBExtendedProperties.ExternalAlias] != null) { Writer.Write(VBKeyword.Alias); Writer.Write(' '); Writer.Write(VBSymbol.BeginString); Writer.Write(element[VBExtendedProperties.ExternalAlias].ToString()); Writer.Write(VBSymbol.BeginString); Writer.Write(' '); } WriteParameterList(element.Parameters); WriteReturnType(element.Type); WriteImplements(element.Implements); string[] handles = element[VBExtendedProperties.Handles] as string[]; if (handles != null && handles.Length > 0) { Writer.Write(' '); Writer.Write(VBKeyword.Handles); for (int handleIndex = 0; handleIndex < handles.Length; handleIndex++) { string handleReference = handles[handleIndex]; Writer.Write(' '); Writer.Write(handleReference); if (handleIndex < handles.Length - 1) { Writer.Write(VBSymbol.AliasSeparator); } } } if (!element.IsExternal) { WriteBody(element); } } /// <summary> /// Processes a namespace element. /// </summary> /// <param name="element">Namespace code element.</param> public override void VisitNamespaceElement(NamespaceElement element) { this.WriteComments(element.HeaderComments); StringBuilder builder = new StringBuilder(DefaultBlockLength); builder.Append(VBKeyword.Namespace); builder.Append(' '); builder.Append(element.Name); WriteIndented(builder.ToString()); WriteBeginBlock(); WriteBlockChildren(element); WriteEndBlock(element); Writer.WriteLine(); Writer.WriteLine(); } /// <summary> /// Processes a property element. /// </summary> /// <param name="element">Property code element.</param> public override void VisitPropertyElement(PropertyElement element) { this.WriteComments(element.HeaderComments); this.WriteAttributes(element); WriteAccess(element.Access); WriteMemberAttributes( element.MemberModifiers, element[VBExtendedProperties.Overloads] is bool && (bool)element[VBExtendedProperties.Overloads]); if (element[VBExtendedProperties.Default] is bool && (bool)element[VBExtendedProperties.Default]) { Writer.Write(VBKeyword.Default); Writer.Write(' '); } if (element[VBExtendedProperties.AccessModifier] != null && element[VBExtendedProperties.AccessModifier].ToString() != VBKeyword.ReadOnly) { Writer.Write(element[VBExtendedProperties.AccessModifier]); Writer.Write(' '); } Writer.Write(VBKeyword.Property); Writer.Write(' '); Writer.Write(element.Name); Writer.Write(VBSymbol.BeginParameterList); if (element.IndexParameter != null) { Writer.Write(element.IndexParameter.Trim()); } Writer.Write(VBSymbol.EndParameterList); WriteReturnType(element.Type); WriteImplements(element.Implements); WriteBody(element); } /// <summary> /// Processes a type element. /// </summary> /// <param name="element">Type code element.</param> public override void VisitTypeElement(TypeElement element) { this.WriteComments(element.HeaderComments); this.WriteAttributes(element); if (element.Access != CodeAccess.None) { WriteAccess(element.Access); } else { WriteIndented(string.Empty); } if (element.IsNew) { Writer.Write(VBKeyword.Shadows); Writer.Write(' '); } if (element.IsSealed) { Writer.Write(VBKeyword.NotInheritable); Writer.Write(' '); } if (element.IsAbstract) { Writer.Write(VBKeyword.MustInherit); Writer.Write(' '); } if (element.IsPartial) { Writer.Write(VBKeyword.Partial); Writer.Write(' '); } StringBuilder builder = new StringBuilder(DefaultBlockLength); switch (element.Type) { case TypeElementType.Class: builder.Append(VBKeyword.Class); break; case TypeElementType.Enum: builder.Append(VBKeyword.Enumeration); break; case TypeElementType.Interface: builder.Append(VBKeyword.Interface); break; case TypeElementType.Structure: builder.Append(VBKeyword.Structure); break; case TypeElementType.Module: builder.Append(VBKeyword.Module); break; default: throw new ArgumentOutOfRangeException( string.Format( Thread.CurrentThread.CurrentCulture, "Unrecognized type element type {0}", element.Type)); } builder.Append(' '); builder.Append(element.Name); Writer.Write(builder.ToString()); WriteTypeParameters(element); if (element.Interfaces.Count > 0) { if (element.Type == TypeElementType.Enum) { Writer.Write(' '); Writer.Write(VBKeyword.As); Writer.Write(' '); Writer.Write(element.Interfaces[0].Name); } else { TabCount++; Writer.WriteLine(); for (int interfaceIndex = 0; interfaceIndex < element.Interfaces.Count; interfaceIndex++) { InterfaceReference interfaceReference = element.Interfaces[interfaceIndex]; builder = new StringBuilder(); if (interfaceReference.ReferenceType == InterfaceReferenceType.Class) { builder.Append(VBKeyword.Inherits); } else { builder.Append(VBKeyword.Implements); } builder.Append(' '); builder.Append(interfaceReference); WriteIndented(builder.ToString()); if (interfaceIndex < element.Interfaces.Count - 1) { Writer.WriteLine(); } } TabCount--; } } if (element.Type == TypeElementType.Enum) { WriteBody(element); } else { WriteBeginBlock(); WriteBlockChildren(element); WriteEndBlock(element); WriteClosingComment(element, VBSymbol.BeginComment.ToString()); } } /// <summary> /// Processes a using element. /// </summary> /// <param name="element">Using/Import directive code element.</param> public override void VisitUsingElement(UsingElement element) { this.WriteComments(element.HeaderComments); StringBuilder builder = new StringBuilder(DefaultBlockLength); builder.Append(VBKeyword.Imports); builder.Append(' '); builder.Append(element.Name); if (!string.IsNullOrEmpty(element.Redefine)) { builder.Append(" " + VBSymbol.Assignment.ToString() + " "); builder.Append(element.Redefine); } WriteIndented(builder.ToString()); } /// <summary> /// Writes children for a block element. /// </summary> /// <param name="element">Block code element.</param> protected override void WriteBlockChildren(ICodeElement element) { if (element.Children.Count > 0) { Writer.WriteLine(); } base.WriteBlockChildren(element); if (element.Children.Count > 0) { Writer.WriteLine(); } } /// <summary> /// Writes a starting region directive. /// </summary> /// <param name="element">Region element.</param> protected override void WriteRegionBeginDirective(RegionElement element) { StringBuilder builder = new StringBuilder(DefaultBlockLength); builder.Append(VBSymbol.Preprocessor); builder.Append(VBKeyword.Region); builder.Append(" \""); builder.Append(element.Name); builder.Append('"'); WriteIndented(builder.ToString()); } /// <summary> /// Writes an ending region directive. /// </summary> /// <param name="element">Region element.</param> protected override void WriteRegionEndDirective(RegionElement element) { StringBuilder builder = new StringBuilder(DefaultBlockLength); builder.Append(VBSymbol.Preprocessor); builder.Append(VBKeyword.End); builder.Append(' '); builder.Append(VBKeyword.Region); if (Configuration.Formatting.Regions.EndRegionNameEnabled) { builder.Append(" '"); builder.Append(element.Name); } WriteIndented(builder.ToString()); } /// <summary> /// Gets the type parent. /// </summary> /// <param name="element">The element.</param> /// <returns>The Type parent.</returns> private static TypeElement GetTypeParent(ICodeElement element) { TypeElement parentTypeElement = element.Parent as TypeElement; if (parentTypeElement == null && (element.Parent is GroupElement || element.Parent is RegionElement)) { parentTypeElement = GetTypeParent(element.Parent); } return parentTypeElement; } /// <summary> /// Writes the member or type access. /// </summary> /// <param name="codeAccess">The code access.</param> private void WriteAccess(CodeAccess codeAccess) { string accessString = string.Empty; if (codeAccess != CodeAccess.None) { accessString = EnumUtilities.ToString(codeAccess).Replace(",", string.Empty) + " "; accessString = accessString.Replace( EnumUtilities.ToString(CodeAccess.Internal), VBKeyword.Friend); } WriteIndented(accessString); } /// <summary> /// Writes a collection of element attributes. /// </summary> /// <param name="element">The element.</param> private void WriteAttributes(AttributedElement element) { foreach (IAttributeElement attribute in element.Attributes) { attribute.Accept(this); } } /// <summary> /// Writes the begin block. /// </summary> private void WriteBeginBlock() { TabCount++; } /// <summary> /// Writes the code element body text. /// </summary> /// <param name="element">The element.</param> private void WriteBody(TextCodeElement element) { MemberElement memberElement = element as MemberElement; TypeElement parentTypeElement = GetTypeParent(element); bool isAbstract = memberElement != null && (memberElement.MemberModifiers & MemberModifiers.Abstract) == MemberModifiers.Abstract; bool inInterface = memberElement != null && parentTypeElement != null && parentTypeElement.Type == TypeElementType.Interface; if (!(isAbstract || inInterface)) { WriteBeginBlock(); Writer.WriteLine(); if (element.BodyText != null && element.BodyText.Trim().Length > 0) { WriteTextBlock(element.BodyText); Writer.WriteLine(); WriteEndBlock(element); WriteClosingComment(element, VBSymbol.BeginComment.ToString()); } else { WriteEndBlock(element); } } } /// <summary> /// Writes the end block for an element. /// </summary> /// <param name="codeElement">The code element.</param> private void WriteEndBlock(CodeElement codeElement) { TabCount--; MemberElement memberElement = codeElement as MemberElement; string blockName = string.Empty; if (memberElement != null) { if (memberElement.ElementType == ElementType.Method || memberElement.ElementType == ElementType.Constructor) { MethodElement methodElement = memberElement as MethodElement; if (methodElement != null && methodElement.IsOperator) { blockName = VBKeyword.Operator; } else if (memberElement.Type != null) { blockName = VBKeyword.Function; } else { blockName = VBKeyword.Sub; } } } if (string.IsNullOrEmpty(blockName)) { TypeElement typeElement = codeElement as TypeElement; if (typeElement != null) { blockName = EnumUtilities.ToString(typeElement.Type); } if (string.IsNullOrEmpty(blockName)) { blockName = EnumUtilities.ToString(codeElement.ElementType); } } WriteIndented(VBKeyword.End + ' ' + blockName); } /// <summary> /// Writes implements clauses. /// </summary> /// <param name="interfaceReferences">The interface references.</param> private void WriteImplements(ReadOnlyCollection<InterfaceReference> interfaceReferences) { if (interfaceReferences.Count > 0) { Writer.Write(' '); Writer.Write(VBKeyword.Implements); for (int index = 0; index < interfaceReferences.Count; index++) { InterfaceReference interfaceReference = interfaceReferences[index]; Writer.Write(' '); Writer.Write(interfaceReference.Name); if (interfaceReferences.Count > 1 && index < interfaceReferences.Count - 1) { Writer.Write(VBSymbol.AliasSeparator); } } } } /// <summary> /// Writes the member attributes. /// </summary> /// <param name="memberAttributes">The member attributes.</param> /// <param name="overloads">Whether or not the member is overloaded.</param> private void WriteMemberAttributes(MemberModifiers memberAttributes, bool overloads) { if ((memberAttributes & MemberModifiers.New) == MemberModifiers.New) { Writer.Write(VBKeyword.Shadows); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.Constant) == MemberModifiers.Constant) { Writer.Write(VBKeyword.Constant); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.Static) == MemberModifiers.Static) { Writer.Write(VBKeyword.Shared); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.Abstract) == MemberModifiers.Abstract) { Writer.Write(VBKeyword.MustOverride); Writer.Write(' '); } if (overloads) { Writer.Write(VBKeyword.Overloads); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.Override) == MemberModifiers.Override) { Writer.Write(VBKeyword.Overrides); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.ReadOnly) == MemberModifiers.ReadOnly) { Writer.Write(VBKeyword.ReadOnly); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.Sealed) == MemberModifiers.Sealed) { Writer.Write(VBKeyword.NotOverridable); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.Virtual) == MemberModifiers.Virtual) { Writer.Write(VBKeyword.Overridable); Writer.Write(' '); } } /// <summary> /// Writes the type of the method. /// </summary> /// <param name="returnType">The method return type.</param> private void WriteMethodType(string returnType) { if (returnType == null) { Writer.Write(VBKeyword.Sub); } else { Writer.Write(VBKeyword.Function); } Writer.Write(' '); } /// <summary> /// Writes the parameter list. /// </summary> /// <param name="paramList">The param list.</param> private void WriteParameterList(string paramList) { Writer.Write(VBSymbol.BeginParameterList); TabCount++; if (paramList != null) { if (paramList.Length > 0 && paramList[0] == VBSymbol.LineContinuation) { Writer.Write(' '); } string[] paramLines = paramList.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); for (int paramLineIndex = 0; paramLineIndex < paramLines.Length; paramLineIndex++) { string paramLine = paramLines[paramLineIndex]; if (paramLineIndex > 0) { Writer.WriteLine(); WriteIndented(paramLine.Trim()); } else { Writer.Write(paramLine); } } } Writer.Write(VBSymbol.EndParameterList); TabCount--; } /// <summary> /// Writes a member return type. /// </summary> /// <param name="returnType">The member return type.</param> private void WriteReturnType(string returnType) { if (!string.IsNullOrEmpty(returnType)) { Writer.Write(' '); Writer.Write(VBKeyword.As); Writer.Write(' '); Writer.Write(returnType); } } /// <summary> /// Writes the type parameter constraints. /// </summary> /// <param name="typeParameter">The type parameter.</param> private void WriteTypeParameterConstraints(TypeParameter typeParameter) { if (typeParameter.Constraints.Count > 0) { Writer.Write(' '); Writer.Write(VBKeyword.As); Writer.Write(' '); if (typeParameter.Constraints.Count > 1) { Writer.Write(VBSymbol.BeginTypeConstraintList); } for (int constraintIndex = 0; constraintIndex < typeParameter.Constraints.Count; constraintIndex++) { string constraint = typeParameter.Constraints[constraintIndex]; Writer.Write(constraint); if (constraintIndex < typeParameter.Constraints.Count - 1) { Writer.Write(VBSymbol.AliasSeparator); Writer.Write(' '); } } if (typeParameter.Constraints.Count > 1) { Writer.Write(VBSymbol.EndTypeConstraintList); } } } /// <summary> /// Writes the type parameters. /// </summary> /// <param name="genericElement">The generic element.</param> private void WriteTypeParameters(IGenericElement genericElement) { if (genericElement.TypeParameters.Count > 0) { Writer.Write(VBSymbol.BeginParameterList); Writer.Write(VBKeyword.Of); Writer.Write(' '); for (int parameterIndex = 0; parameterIndex < genericElement.TypeParameters.Count; parameterIndex++) { TypeParameter typeParameter = genericElement.TypeParameters[parameterIndex]; Writer.Write(typeParameter.Name); WriteTypeParameterConstraints(typeParameter); if (parameterIndex < genericElement.TypeParameters.Count - 1) { Writer.Write(VBSymbol.AliasSeparator); Writer.Write(' '); } } Writer.Write(VBSymbol.EndParameterList); } } #endregion Methods } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Authentication; using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using RedditSharp.Extensions; namespace RedditSharp.Things { public class Post : VotableThing { private const string CommentUrl = "/api/comment"; private const string RemoveUrl = "/api/remove"; private const string DelUrl = "/api/del"; private const string GetCommentsUrl = "/comments/{0}.json"; private const string ApproveUrl = "/api/approve"; private const string EditUserTextUrl = "/api/editusertext"; private const string HideUrl = "/api/hide"; private const string UnhideUrl = "/api/unhide"; private const string SetFlairUrl = "/r/{0}/api/flair"; private const string MarkNSFWUrl = "/api/marknsfw"; private const string UnmarkNSFWUrl = "/api/unmarknsfw"; private const string ContestModeUrl = "/api/set_contest_mode"; private const string StickyModeUrl = "/api/set_subreddit_sticky"; private const string IgnoreReportsUrl = "/api/ignore_reports"; private const string UnIgnoreReportsUrl = "/api/unignore_reports"; [JsonIgnore] private Reddit Reddit { get; set; } [JsonIgnore] private IWebAgent WebAgent { get; set; } /// <summary> /// Initialize /// </summary> /// <param name="reddit"></param> /// <param name="post"></param> /// <param name="webAgent"></param> /// <returns></returns> public async Task<Post> InitAsync(Reddit reddit, JToken post, IWebAgent webAgent) { await CommonInitAsync(reddit, post, webAgent); await JsonConvert.PopulateObjectAsync(post["data"].ToString(), this, reddit.JsonSerializerSettings); return this; } public Post Init(Reddit reddit, JToken post, IWebAgent webAgent) { CommonInit(reddit, post, webAgent); JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings); return this; } private void CommonInit(Reddit reddit, JToken post, IWebAgent webAgent) { base.Init(reddit, webAgent, post); Reddit = reddit; WebAgent = webAgent; } private async Task CommonInitAsync(Reddit reddit, JToken post, IWebAgent webAgent) { await base.InitAsync(reddit, webAgent, post); Reddit = reddit; WebAgent = webAgent; } [JsonProperty("author")] public string AuthorName { get; set; } [JsonIgnore] public RedditUser Author { get { return Reddit.GetUser(AuthorName); } } public Comment[] Comments { get { return ListComments().ToArray(); } } [JsonProperty("approved_by")] public string ApprovedBy { get; set; } [JsonProperty("author_flair_css_class")] public string AuthorFlairCssClass { get; set; } [JsonProperty("author_flair_text")] public string AuthorFlairText { get; set; } [JsonProperty("banned_by")] public string BannedBy { get; set; } [JsonProperty("domain")] public string Domain { get; set; } [JsonProperty("edited")] public bool Edited { get; set; } [JsonProperty("is_self")] public bool IsSelfPost { get; set; } [JsonProperty("link_flair_css_class")] public string LinkFlairCssClass { get; set; } [JsonProperty("link_flair_text")] public string LinkFlairText { get; set; } [JsonProperty("num_comments")] public int CommentCount { get; set; } [JsonProperty("over_18")] public bool NSFW { get; set; } [JsonProperty("permalink")] [JsonConverter(typeof(UrlParser))] public Uri Permalink { get; set; } [JsonProperty("selftext")] public string SelfText { get; set; } [JsonProperty("selftext_html")] public string SelfTextHtml { get; set; } [JsonProperty("thumbnail")] [JsonConverter(typeof(UrlParser))] public Uri Thumbnail { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("subreddit")] public string SubredditName { get; set; } [JsonProperty("archived")] public bool IsArchived { get; set; } [JsonProperty("stickied")] public bool IsStickied { get; set; } [JsonIgnore] public Subreddit Subreddit { get { return Reddit.GetSubreddit("/r/" + SubredditName); } } [JsonProperty("url")] [JsonConverter(typeof(UrlParser))] public Uri Url { get; set; } [JsonProperty("num_reports")] public int? Reports { get; set; } public Comment Comment(string message) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(CommentUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { text = message, thing_id = FullName, uh = Reddit.User.Modhash, api_type = "json" }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JObject.Parse(data); if (json["json"]["ratelimit"] != null) throw new RateLimitException(TimeSpan.FromSeconds(json["json"]["ratelimit"].ValueOrDefault<double>())); return new Comment().Init(Reddit, json["json"]["data"]["things"][0], WebAgent, this); } private string SimpleAction(string endpoint) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(endpoint); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); return data; } private string SimpleActionToggle(string endpoint, bool value, bool requiresModAction = false) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var modNameList = this.Subreddit.Moderators.Select(b => b.Name).ToList(); if (requiresModAction && !modNameList.Contains(Reddit.User.Name)) throw new AuthenticationException( string.Format( @"User {0} is not a moderator of subreddit {1}.", Reddit.User.Name, this.Subreddit.Name)); var request = WebAgent.CreatePost(endpoint); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, state = value, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); return data; } public void Approve() { var data = SimpleAction(ApproveUrl); } public void Remove() { RemoveImpl(false); } public void RemoveSpam() { RemoveImpl(true); } private void RemoveImpl(bool spam) { var request = WebAgent.CreatePost(RemoveUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, spam = spam, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); } public void Del() { var data = SimpleAction(DelUrl); } public void Hide() { var data = SimpleAction(HideUrl); } public void Unhide() { var data = SimpleAction(UnhideUrl); } public void IgnoreReports() { var data = SimpleAction(IgnoreReportsUrl); } public void UnIgnoreReports() { var data = SimpleAction(UnIgnoreReportsUrl); } public void MarkNSFW() { var data = SimpleAction(MarkNSFWUrl); } public void UnmarkNSFW() { var data = SimpleAction(UnmarkNSFWUrl); } public void ContestMode(bool state) { var data = SimpleActionToggle(ContestModeUrl, state); } public void StickyMode(bool state) { var data = SimpleActionToggle(StickyModeUrl, state, true); } #region Obsolete Getter Methods [Obsolete("Use Comments property instead")] public Comment[] GetComments() { return Comments; } #endregion Obsolete Getter Methods /// <summary> /// Replaces the text in this post with the input text. /// </summary> /// <param name="newText">The text to replace the post's contents</param> public void EditText(string newText) { if (Reddit.User == null) throw new Exception("No user logged in."); if (!IsSelfPost) throw new Exception("Submission to edit is not a self-post."); var request = WebAgent.CreatePost(EditUserTextUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", text = newText, thing_id = FullName, uh = Reddit.User.Modhash }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); JToken json = JToken.Parse(result); if (json["json"].ToString().Contains("\"errors\": []")) SelfText = newText; else throw new Exception("Error editing text."); } public void Update() { JToken post = Reddit.GetToken(this.Url); JsonConvert.PopulateObject(post["data"].ToString(), this, Reddit.JsonSerializerSettings); } /// <summary> /// Sets your claim /// </summary> /// <param name="flairText">Text to set your flair</param> /// <param name="flairClass">class of the flair</param> public void SetFlair(string flairText, string flairClass) { if (Reddit.User == null) throw new Exception("No user logged in."); var request = WebAgent.CreatePost(string.Format(SetFlairUrl, SubredditName)); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", css_class = flairClass, link = FullName, name = Reddit.User.Name, text = flairText, uh = Reddit.User.Modhash }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(result); LinkFlairText = flairText; } public List<Comment> ListComments(int? limit = null) { var url = string.Format(GetCommentsUrl, Id); if (limit.HasValue) { var query = HttpUtility.ParseQueryString(string.Empty); query.Add("limit", limit.Value.ToString()); url = string.Format("{0}?{1}", url, query); } var request = WebAgent.CreateGet(url); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JArray.Parse(data); var postJson = json.Last()["data"]["children"]; var comments = new List<Comment>(); foreach (var comment in postJson) { Comment newComment = new Comment().Init(Reddit, comment, WebAgent, this); if (newComment.Kind == "more") { } else { comments.Add(newComment); } } return comments; } public IEnumerable<Comment> EnumerateComments() { var url = string.Format(GetCommentsUrl, Id); var request = WebAgent.CreateGet(url); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JArray.Parse(data); var postJson = json.Last()["data"]["children"]; More moreComments = null; foreach (var comment in postJson) { Comment newComment = new Comment().Init(Reddit, comment, WebAgent, this); if (newComment.Kind == "more") { moreComments = new More().Init(Reddit, comment, WebAgent); } else { yield return newComment; } } if (moreComments != null) { IEnumerator<Thing> things = moreComments.Things().GetEnumerator(); things.MoveNext(); Thing currentThing = null; while (currentThing != things.Current) { currentThing = things.Current; if (things.Current is Comment) { Comment next = ((Comment)things.Current).PopulateComments(things); yield return next; } if (things.Current is More) { More more = (More)things.Current; if (more.ParentId != FullName) break; things = more.Things().GetEnumerator(); things.MoveNext(); } } } } } }
// <copyright file=OrientedBox.cs // <copyright> // Copyright (c) 2016, University of Stuttgart // 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> // <license>MIT License</license> // <main contributors> // Markus Funk, Thomas Kosch, Sven Mayer // </main contributors> // <co-contributors> // Paul Brombosch, Mai El-Komy, Juana Heusler, // Matthias Hoppe, Robert Konrad, Alexander Martin // </co-contributors> // <patent information> // We are aware that this software implements patterns and ideas, // which might be protected by patents in your country. // Example patents in Germany are: // Patent reference number: DE 103 20 557.8 // Patent reference number: DE 10 2013 220 107.9 // Please make sure when using this software not to violate any existing patents in your country. // </patent information> // <date> 11/2/2016 12:25:57 PM</date> using HciLab.Utilities.Mathematics.Core; using System; using System.ComponentModel; using System.Diagnostics; using System.Runtime.Serialization; using System.Text.RegularExpressions; namespace HciLab.Utilities.Mathematics.Geometry2D { /// <summary> /// Represents an oriented box in 2D space. /// </summary> /// <remarks> /// An oriented box is a box whose faces have normals that are all pairwise orthogonal-i.e., it is an axis aligned box arbitrarily rotated. /// A 2D oriented box is defined by a center point, two orthonormal axes that describe the side /// directions of the box, and their respective positive half-lengths extents. /// </remarks> [Serializable] [TypeConverter(typeof(OrientedBoxConverter))] public struct OrientedBox : ISerializable, ICloneable { #region Private Fields private Vector2 _center; private Vector2 _axis1; private Vector2 _axis2; private float _extent1; private float _extent2; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="OrientedBox"/> class using given center point, axes and extents. /// </summary> /// <param name="center">The center of the box.</param> /// <param name="axis1">The first axis.</param> /// <param name="axis2">The second axis.</param> /// <param name="extent1">The extent on the first axis.</param> /// <param name="extent2">The extent on the second axis.</param> public OrientedBox(Vector2 center, Vector2 axis1, Vector2 axis2, float extent1, float extent2) { _center = center; _axis1 = axis1; _axis2 = axis2; _extent1 = extent1; _extent2 = extent2; } /// <summary> /// Initializes a new instance of the <see cref="OrientedBox"/> class using given center point, axes and extents. /// </summary> /// <param name="center">The center of the box.</param> /// <param name="axes">The axes of the box.</param> /// <param name="extents">The extent values of the box..</param> public OrientedBox(Vector2 center, Vector2[] axes, float[] extents) { Debug.Assert(axes.Length >= 2); Debug.Assert(extents.Length >= 2); _center = center; _axis1 = axes[0]; _axis2 = axes[1]; _extent1 = extents[0]; _extent2 = extents[1]; } /// <summary> /// Initializes a new instance of the <see cref="OrientedBox"/> class using given values from another box instance. /// </summary> /// <param name="box">A <see cref="OrientedBox"/> instance to take values from.</param> public OrientedBox(OrientedBox box) { _center = box.Center; _axis1 = box.Axis1; _axis2 = box.Axis2; _extent1 = box.Extent1; _extent2 = box.Extent2; } /// <summary> /// Initializes a new instance of the <see cref="OrientedBox"/> class with serialized data. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination.</param> private OrientedBox(SerializationInfo info, StreamingContext context) { _center = (Vector2)info.GetValue("Center", typeof(Vector2)); _axis1 = (Vector2)info.GetValue("Axis1", typeof(Vector2)); _axis2 = (Vector2)info.GetValue("Axis2", typeof(Vector2)); _extent1 = info.GetSingle("Extent1"); _extent2 = info.GetSingle("Extent2"); } #endregion #region Public Properties /// <summary> /// Gets or sets the box's center point. /// </summary> public Vector2 Center { get { return _center; } set { _center = value;} } /// <summary> /// Gets or sets the box's first axis. /// </summary> public Vector2 Axis1 { get { return _axis1; } set { _axis1 = value;} } /// <summary> /// Gets or sets the box's second axis. /// </summary> public Vector2 Axis2 { get { return _axis2; } set { _axis2 = value;} } /// <summary> /// Gets or sets the box's first extent. /// </summary> public float Extent1 { get { return _extent1; } set { _extent1 = value;} } /// <summary> /// Gets or sets the box's second extent. /// </summary> public float Extent2 { get { return _extent2; } set { _extent2 = value;} } #endregion #region ICloneable Members /// <summary> /// Creates an exact copy of this <see cref="OrientedBox"/> object. /// </summary> /// <returns>The <see cref="OrientedBox"/> object this method creates, cast as an object.</returns> object ICloneable.Clone() { return new OrientedBox(this); } /// <summary> /// Creates an exact copy of this <see cref="OrientedBox"/> object. /// </summary> /// <returns>The <see cref="OrientedBox"/> object this method creates.</returns> public OrientedBox Clone() { return new OrientedBox(this); } #endregion #region ISerializable Members /// <summary> /// Populates a <see cref="SerializationInfo"/> with the data needed to serialize the target object. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> to populate with data. </param> /// <param name="context">The destination (see <see cref="StreamingContext"/>) for this serialization.</param> //[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)] public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Center", _center, typeof(Vector2)); info.AddValue("Axis1", _axis1, typeof(Vector2)); info.AddValue("Axis2", _axis2, typeof(Vector2)); info.AddValue("Extent1", _extent1, typeof(Vector2)); info.AddValue("Extent2", _extent2, typeof(Vector2)); } #endregion #region Public Static Parse Methods /// <summary> /// Converts the specified string to its <see cref="OrientedBox"/> equivalent. /// </summary> /// <param name="s">A string representation of a <see cref="OrientedBox"/></param> /// <returns>A <see cref="OrientedBox"/> that represents the vector specified by the <paramref name="s"/> parameter.</returns> public static OrientedBox Parse(string s) { Regex r = new Regex(@"OrientedBox\(Center=(?<center>\([^\)]*\)), Axis1=(?<axis1>\([^\)]*\)), Axis2=(?<axis2>\([^\)]*\)), Extent1=(?<extent1>.*), Extent2=(?<extent2>.*)\)", RegexOptions.None); Match m = r.Match(s); if (m.Success) { return new OrientedBox( Vector2.Parse(m.Result("${center}")), Vector2.Parse(m.Result("${axis1}")), Vector2.Parse(m.Result("${axis2}")), float.Parse(m.Result("${extent1}")), float.Parse(m.Result("${extent2}")) ); } else { throw new ParseException("Unsuccessful Match."); } } #endregion #region Public methods /// <summary> /// Computes the box vertices. /// </summary> /// <returns>An array of <see cref="Vector2"/> containing the box vertices.</returns> public Vector2[] ComputeVertices() { Vector2[] vertices = new Vector2[4]; Vector2[] AxisExtents = new Vector2[2] { Axis1*Extent1, Axis2*Extent2 }; vertices[0] = Center - AxisExtents[0] - AxisExtents[1]; vertices[1] = Center + AxisExtents[0] - AxisExtents[1]; vertices[2] = Center + AxisExtents[0] + AxisExtents[1]; vertices[3] = Center - AxisExtents[0] + AxisExtents[1]; return vertices; } #endregion #region Overrides /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A 32-bit signed integer hash code.</returns> public override int GetHashCode() { return _center.GetHashCode() ^ _axis1.GetHashCode() ^ _axis2.GetHashCode() ^ _extent1.GetHashCode() ^ _extent2.GetHashCode(); } /// <summary> /// Returns a value indicating whether this instance is equal to /// the specified object. /// </summary> /// <param name="obj">An object to compare to this instance.</param> /// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="Vector2"/> and has the same values as this instance; otherwise, <see langword="false"/>.</returns> public override bool Equals(object obj) { if (obj is OrientedBox) { OrientedBox b = (OrientedBox)obj; return (_center == b.Center) && (_axis1 == b.Axis1) && (_axis2 == b.Axis2) && (_extent1 == b.Extent1) && (_extent2 == b.Extent2); } return false; } /// <summary> /// Returns a string representation of this object. /// </summary> /// <returns>A string representation of this object.</returns> public override string ToString() { return string.Format( "OrientedBox(Center={0}, Axis1={1}, Axis2={2}, Extent1={3}, Extent2={4})", Center, Axis1, Axis2, Extent1, Extent2); } #endregion #region Comparison Operators /// <summary> /// Tests whether two specified boxes are equal. /// </summary> /// <param name="a">The left-hand box.</param> /// <param name="b">The right-hand box.</param> /// <returns><see langword="true"/> if the two vectors are equal; otherwise, <see langword="false"/>.</returns> public static bool operator==(OrientedBox a, OrientedBox b) { return ValueType.Equals(a,b); } /// <summary> /// Tests whether two specified boxes are not equal. /// </summary> /// <param name="a">The left-hand box.</param> /// <param name="b">The right-hand box.</param> /// <returns><see langword="true"/> if the two boxes are not equal; otherwise, <see langword="false"/>.</returns> public static bool operator!=(OrientedBox a, OrientedBox b) { return ValueType.Equals(a,b); } #endregion } #region OrientedBoxConverter class /// <summary> /// Converts a <see cref="OrientedBox"/> to and from string representation. /// </summary> public class OrientedBoxConverter : ExpandableObjectConverter { /// <summary> /// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="sourceType">A <see cref="Type"/> that represents the type you want to convert from.</param> /// <returns><b>true</b> if this converter can perform the conversion; otherwise, <b>false</b>.</returns> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom (context, sourceType); } /// <summary> /// Returns whether this converter can convert the object to the specified type, using the specified context. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="destinationType">A <see cref="Type"/> that represents the type you want to convert to.</param> /// <returns><b>true</b> if this converter can perform the conversion; otherwise, <b>false</b>.</returns> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(string)) return true; return base.CanConvertTo (context, destinationType); } /// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="culture">A <see cref="System.Globalization.CultureInfo"/> object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param> /// <param name="value">The <see cref="Object"/> to convert.</param> /// <param name="destinationType">The Type to convert the <paramref name="value"/> parameter to.</param> /// <returns>An <see cref="Object"/> that represents the converted value.</returns> public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if ((destinationType == typeof(string)) && (value is OrientedBox)) { OrientedBox box = (OrientedBox)value; return box.ToString(); } return base.ConvertTo (context, culture, value, destinationType); } /// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> to use as the current culture. </param> /// <param name="value">The <see cref="Object"/> to convert.</param> /// <returns>An <see cref="Object"/> that represents the converted value.</returns> /// <exception cref="ParseException">Failed parsing from string.</exception> public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value.GetType() == typeof(string)) { return OrientedBox.Parse((string)value); } return base.ConvertFrom (context, culture, value); } } #endregion }
// Copyright 2017 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 System.Collections; using System.Collections.Generic; using UnityEngine; public class midiComponentInterface : componentInterface { deviceInterface _deviceInterface; public bool input = true; public string connectedDevice = ""; int channel = 0; public GameObject midiPanelPrefab, statusLight; public TextMesh statusText; public sliderNotched channelSlider; midiPanel mainMidiPanel; List<midiPanel> midiPanelList = new List<midiPanel>(); Material statusLightMat; Color connectedColor = new Color32(0x32, 0xA3, 0x23, 0xFF); //A32323FF Color disconnectedColor = new Color32(0xA3, 0x23, 0x23, 0xFF); //A32323FF Color connectingColor = new Color32(0x9A, 0xA3, 0x23, 0xFF); //9AA323FF MIDIdevice curMIDIdevice; void Awake() { _deviceInterface = GetComponentInParent<deviceInterface>(); statusLightMat = statusLight.GetComponent<Renderer>().material; statusLightMat.SetFloat("_EmissionGain", .3f); statusLightMat.SetColor("_TintColor", connectingColor); createMainMidiPanel(); } void createMainMidiPanel() { mainMidiPanel = (Instantiate(midiPanelPrefab, transform, false) as GameObject).GetComponent<midiPanel>(); mainMidiPanel.transform.localPosition = new Vector3(0, 0, .015f); mainMidiPanel.transform.localRotation = Quaternion.identity; mainMidiPanel.transform.localScale = new Vector3(0.15f, .02f, 1.25f); mainMidiPanel.label.text = input ? "[SELECT MIDI INPUT DEVICE]" : "[SELECT MIDI OUTPUT DEVICE]"; mainMidiPanel.buttonID = -1; } public void ConnectByName(string s) { MIDImaster.instance.RefreshDevices(input); int ID = MIDImaster.instance.GetIDbyName(input, s); if (ID == -1) { Debug.Log("FAILED ID BY NAME"); } else { mainMidiPanel.label.text = input ? MIDImaster.instance.inputDevices[ID].name : MIDImaster.instance.outputDevices[ID].name; listopen = false; TryConnect(ID, s); CloseList(); } } void OnDestroy() { if (curMIDIdevice != null) MIDImaster.instance.Disconnect(curMIDIdevice, input, this); } Coroutine _textKillRoutine; IEnumerator TextKillRoutine() { yield return new WaitForSeconds(3); statusText.text = ""; statusText.gameObject.SetActive(false); } void TryConnect(int index, string name) { string s = "Connecting"; MIDIdevice lastMidiDevice = curMIDIdevice; curMIDIdevice = MIDImaster.instance.Connect(this, index, input); statusText.gameObject.SetActive(true); if (lastMidiDevice != curMIDIdevice && lastMidiDevice != null) { MIDImaster.instance.Disconnect(lastMidiDevice, input, this); } if (curMIDIdevice != null) { connectedDevice = name; s = "CONNECTED!"; statusLightMat.SetColor("_TintColor", connectedColor); statusText.text = s; } else { connectedDevice = ""; s = "Connection failed\nDevice may be connected to other software."; statusLightMat.SetColor("_TintColor", disconnectedColor); statusText.text = s; } if (gameObject.activeSelf) { if (_textKillRoutine != null) StopCoroutine(_textKillRoutine); _textKillRoutine = StartCoroutine(TextKillRoutine()); } } void OnDisable() { StopAllCoroutines(); statusText.gameObject.SetActive(false); } void toggleList() { listopen = !listopen; if (listopen) OpenList(); else CloseList(); } void Update() { if (channelSlider != null) channel = channelSlider.switchVal; } bool listopen = false; public override void hit(bool on, int ID = -1) { if (!on) return; if (ID == -1) toggleList(); else { mainMidiPanel.label.text = input ? MIDImaster.instance.inputDevices[ID].name : MIDImaster.instance.outputDevices[ID].name; listopen = false; TryConnect(ID, mainMidiPanel.label.text); CloseList(); } } void CloseList() { for (int i = 0; i < midiPanelList.Count; i++) { Destroy(midiPanelList[i].gameObject); } midiPanelList.Clear(); } void OpenList() { MIDImaster.instance.RefreshDevices(input); int count = input ? MIDImaster.instance.inputDevices.Count : MIDImaster.instance.outputDevices.Count; for (int i = 0; i < count; i++) { midiPanel m = (Instantiate(midiPanelPrefab, transform, false) as GameObject).GetComponent<midiPanel>(); m.transform.localPosition = new Vector3(0, i * .03f + .045f, .015f); m.transform.localRotation = Quaternion.identity; m.transform.localScale = new Vector3(0.15f, .02f, 1.25f); m.label.text = input ? MIDImaster.instance.inputDevices[i].name : MIDImaster.instance.outputDevices[i].name; m.buttonID = i; midiPanelList.Add(m); } if (count == 0) { statusText.gameObject.SetActive(true); statusText.text = "NO MIDI DEVICES FOUND"; if (gameObject.activeSelf) { if (_textKillRoutine != null) StopCoroutine(_textKillRoutine); _textKillRoutine = StartCoroutine(TextKillRoutine()); } listopen = false; CloseList(); } } public void InputNoteOn(Midi.NoteOnMessage msg) { if (channel == 0 || channel == (int)msg.Channel + 1) { _deviceInterface.OnMidiNote((int)msg.Channel + 1, msg.Velocity != 0, (int)msg.Pitch); } } public void InputNoteOff(Midi.NoteOffMessage msg) { if (channel == 0 || channel == (int)msg.Channel + 1) { _deviceInterface.OnMidiNote((int)msg.Channel + 1, false, (int)msg.Pitch); } } public void InputControlChange(Midi.ControlChangeMessage msg) { if (channel == 0 || channel == (int)msg.Channel + 1) { _deviceInterface.OnMidiCC((int)msg.Channel + 1, (int)msg.Control, msg.Value); } } public void OutputNote(bool on, int ID, bool add48 = true) { if (input || curMIDIdevice == null) return; if (add48) ID += 48; MIDImaster.instance.outputNote(curMIDIdevice, on, ID, channel); } public void OutputCC(int val, int ID) { if (input || curMIDIdevice == null) return; MIDImaster.instance.outputCC(curMIDIdevice, val, ID, channel); } }
#region Copyright notice and license // Copyright 2015, Google 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: // // * 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.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Manages server side native call lifecycle. /// </summary> internal class AsyncCallServer<TRequest, TResponse> : AsyncCallBase<TResponse, TRequest> { readonly TaskCompletionSource<object> finishedServersideTcs = new TaskCompletionSource<object>(); readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); readonly Server server; public AsyncCallServer(Func<TResponse, byte[]> serializer, Func<byte[], TRequest> deserializer, Server server) : base(serializer, deserializer) { this.server = GrpcPreconditions.CheckNotNull(server); } public void Initialize(CallSafeHandle call, CompletionQueueSafeHandle completionQueue) { call.Initialize(completionQueue); server.AddCallReference(this); InitializeInternal(call); } /// <summary> /// Only for testing purposes. /// </summary> public void InitializeForTesting(INativeCall call) { server.AddCallReference(this); InitializeInternal(call); } /// <summary> /// Starts a server side call. /// </summary> public Task ServerSideCallAsync() { lock (myLock) { GrpcPreconditions.CheckNotNull(call); started = true; call.StartServerSide(HandleFinishedServerside); return finishedServersideTcs.Task; } } /// <summary> /// Sends a streaming response. Only one pending send action is allowed at any given time. /// </summary> public Task SendMessageAsync(TResponse msg, WriteFlags writeFlags) { return SendMessageInternalAsync(msg, writeFlags); } /// <summary> /// Receives a streaming request. Only one pending read action is allowed at any given time. /// </summary> public Task<TRequest> ReadMessageAsync() { return ReadMessageInternalAsync(); } /// <summary> /// Initiates sending a initial metadata. /// Even though C-core allows sending metadata in parallel to sending messages, we will treat sending metadata as a send message operation /// to make things simpler. /// </summary> public Task SendInitialMetadataAsync(Metadata headers) { lock (myLock) { GrpcPreconditions.CheckNotNull(headers, "metadata"); GrpcPreconditions.CheckState(started); GrpcPreconditions.CheckState(!initialMetadataSent, "Response headers can only be sent once per call."); GrpcPreconditions.CheckState(streamingWritesCounter == 0, "Response headers can only be sent before the first write starts."); var earlyResult = CheckSendAllowedOrEarlyResult(); if (earlyResult != null) { return earlyResult; } using (var metadataArray = MetadataArraySafeHandle.Create(headers)) { call.StartSendInitialMetadata(HandleSendFinished, metadataArray); } this.initialMetadataSent = true; streamingWriteTcs = new TaskCompletionSource<object>(); return streamingWriteTcs.Task; } } /// <summary> /// Sends call result status, indicating we are done with writes. /// Sending a status different from StatusCode.OK will also implicitly cancel the call. /// </summary> public Task SendStatusFromServerAsync(Status status, Metadata trailers, Tuple<TResponse, WriteFlags> optionalWrite) { byte[] payload = optionalWrite != null ? UnsafeSerialize(optionalWrite.Item1) : null; var writeFlags = optionalWrite != null ? optionalWrite.Item2 : default(WriteFlags); lock (myLock) { GrpcPreconditions.CheckState(started); GrpcPreconditions.CheckState(!disposed); GrpcPreconditions.CheckState(!halfcloseRequested, "Can only send status from server once."); using (var metadataArray = MetadataArraySafeHandle.Create(trailers)) { call.StartSendStatusFromServer(HandleSendStatusFromServerFinished, status, metadataArray, !initialMetadataSent, payload, writeFlags); } halfcloseRequested = true; initialMetadataSent = true; sendStatusFromServerTcs = new TaskCompletionSource<object>(); if (optionalWrite != null) { streamingWritesCounter++; } return sendStatusFromServerTcs.Task; } } /// <summary> /// Gets cancellation token that gets cancelled once close completion /// is received and the cancelled flag is set. /// </summary> public CancellationToken CancellationToken { get { return cancellationTokenSource.Token; } } public string Peer { get { return call.GetPeer(); } } protected override bool IsClient { get { return false; } } protected override void OnAfterReleaseResources() { server.RemoveCallReference(this); } protected override Task CheckSendAllowedOrEarlyResult() { GrpcPreconditions.CheckState(!halfcloseRequested, "Response stream has already been completed."); GrpcPreconditions.CheckState(!finished, "Already finished."); GrpcPreconditions.CheckState(streamingWriteTcs == null, "Only one write can be pending at a time"); GrpcPreconditions.CheckState(!disposed); return null; } /// <summary> /// Handles the server side close completion. /// </summary> private void HandleFinishedServerside(bool success, bool cancelled) { // NOTE: because this event is a result of batch containing GRPC_OP_RECV_CLOSE_ON_SERVER, // success will be always set to true. lock (myLock) { finished = true; if (streamingReadTcs == null) { // if there's no pending read, readingDone=true will dispose now. // if there is a pending read, we will dispose once that read finishes. readingDone = true; streamingReadTcs = new TaskCompletionSource<TRequest>(); streamingReadTcs.SetResult(default(TRequest)); } ReleaseResourcesIfPossible(); } if (cancelled) { cancellationTokenSource.Cancel(); } finishedServersideTcs.SetResult(null); } } }
// 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.Automation { 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 WebhookOperations. /// </summary> public static partial class WebhookOperationsExtensions { /// <summary> /// Generates a Uri for use in creating a webhook. /// <see href="http://aka.ms/azureautomationsdk/webhookoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> public static string GenerateUri(this IWebhookOperations operations, string resourceGroupName, string automationAccountName) { return operations.GenerateUriAsync(resourceGroupName, automationAccountName).GetAwaiter().GetResult(); } /// <summary> /// Generates a Uri for use in creating a webhook. /// <see href="http://aka.ms/azureautomationsdk/webhookoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> GenerateUriAsync(this IWebhookOperations operations, string resourceGroupName, string automationAccountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GenerateUriWithHttpMessagesAsync(resourceGroupName, automationAccountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete the webhook by name. /// <see href="http://aka.ms/azureautomationsdk/webhookoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='webhookName'> /// The webhook name. /// </param> public static void Delete(this IWebhookOperations operations, string resourceGroupName, string automationAccountName, string webhookName) { operations.DeleteAsync(resourceGroupName, automationAccountName, webhookName).GetAwaiter().GetResult(); } /// <summary> /// Delete the webhook by name. /// <see href="http://aka.ms/azureautomationsdk/webhookoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='webhookName'> /// The webhook name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IWebhookOperations operations, string resourceGroupName, string automationAccountName, string webhookName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, automationAccountName, webhookName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieve the webhook identified by webhook name. /// <see href="http://aka.ms/azureautomationsdk/webhookoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='webhookName'> /// The webhook name. /// </param> public static Webhook Get(this IWebhookOperations operations, string resourceGroupName, string automationAccountName, string webhookName) { return operations.GetAsync(resourceGroupName, automationAccountName, webhookName).GetAwaiter().GetResult(); } /// <summary> /// Retrieve the webhook identified by webhook name. /// <see href="http://aka.ms/azureautomationsdk/webhookoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='webhookName'> /// The webhook name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Webhook> GetAsync(this IWebhookOperations operations, string resourceGroupName, string automationAccountName, string webhookName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, automationAccountName, webhookName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create the webhook identified by webhook name. /// <see href="http://aka.ms/azureautomationsdk/webhookoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='webhookName'> /// The webhook name. /// </param> /// <param name='parameters'> /// The create or update parameters for webhook. /// </param> public static Webhook CreateOrUpdate(this IWebhookOperations operations, string resourceGroupName, string automationAccountName, string webhookName, WebhookCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, automationAccountName, webhookName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Create the webhook identified by webhook name. /// <see href="http://aka.ms/azureautomationsdk/webhookoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='webhookName'> /// The webhook name. /// </param> /// <param name='parameters'> /// The create or update parameters for webhook. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Webhook> CreateOrUpdateAsync(this IWebhookOperations operations, string resourceGroupName, string automationAccountName, string webhookName, WebhookCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, automationAccountName, webhookName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update the webhook identified by webhook name. /// <see href="http://aka.ms/azureautomationsdk/webhookoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='webhookName'> /// The webhook name. /// </param> /// <param name='parameters'> /// The update parameters for webhook. /// </param> public static Webhook Update(this IWebhookOperations operations, string resourceGroupName, string automationAccountName, string webhookName, WebhookUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, automationAccountName, webhookName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Update the webhook identified by webhook name. /// <see href="http://aka.ms/azureautomationsdk/webhookoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='webhookName'> /// The webhook name. /// </param> /// <param name='parameters'> /// The update parameters for webhook. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Webhook> UpdateAsync(this IWebhookOperations operations, string resourceGroupName, string automationAccountName, string webhookName, WebhookUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, automationAccountName, webhookName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieve a list of webhooks. /// <see href="http://aka.ms/azureautomationsdk/webhookoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='filter'> /// The filter to apply on the operation. /// </param> public static IPage<Webhook> ListByAutomationAccount(this IWebhookOperations operations, string resourceGroupName, string automationAccountName, string filter = default(string)) { return operations.ListByAutomationAccountAsync(resourceGroupName, automationAccountName, filter).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of webhooks. /// <see href="http://aka.ms/azureautomationsdk/webhookoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='filter'> /// The filter to apply on the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Webhook>> ListByAutomationAccountAsync(this IWebhookOperations operations, string resourceGroupName, string automationAccountName, string filter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAutomationAccountWithHttpMessagesAsync(resourceGroupName, automationAccountName, filter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieve a list of webhooks. /// <see href="http://aka.ms/azureautomationsdk/webhookoperations" /> /// </summary> /// <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<Webhook> ListByAutomationAccountNext(this IWebhookOperations operations, string nextPageLink) { return operations.ListByAutomationAccountNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of webhooks. /// <see href="http://aka.ms/azureautomationsdk/webhookoperations" /> /// </summary> /// <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<Webhook>> ListByAutomationAccountNextAsync(this IWebhookOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAutomationAccountNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// 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.Text; using System.Globalization; using System.Xml.Schema; using System.Diagnostics; using System.Collections; using System.Text.RegularExpressions; namespace System.Xml { // ExceptionType enum is used inside XmlConvert to specify which type of exception should be thrown at some of the verification and exception creating methods internal enum ExceptionType { ArgumentException, XmlException, } // Options for serializing and deserializing DateTime public enum XmlDateTimeSerializationMode { Local, Utc, Unspecified, RoundtripKind, } /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert"]/*' /> /// <devdoc> /// Encodes and decodes XML names according to /// the "Encoding of arbitrary Unicode Characters in XML Names" specification. /// </devdoc> public static class XmlConvert { // // Static fields with implicit initialization // private static XmlCharType s_xmlCharType = XmlCharType.Instance; /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.EncodeName"]/*' /> /// <devdoc> /// <para> /// Converts names, such /// as DataTable or /// DataColumn names, that contain characters that are not permitted in /// XML names to valid names.</para> /// </devdoc> public static string EncodeName(string name) { return EncodeName(name, true/*Name_not_NmToken*/, false/*Local?*/); } /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.EncodeNmToken"]/*' /> /// <devdoc> /// <para> Verifies the name is valid /// according to production [7] in the XML spec.</para> /// </devdoc> public static string EncodeNmToken(string name) { return EncodeName(name, false/*Name_not_NmToken*/, false/*Local?*/); } /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.EncodeLocalName"]/*' /> /// <devdoc> /// <para>Converts names, such as DataTable or DataColumn names, that contain /// characters that are not permitted in XML names to valid names.</para> /// </devdoc> public static string EncodeLocalName(string name) { return EncodeName(name, true/*Name_not_NmToken*/, true/*Local?*/); } /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.DecodeName"]/*' /> /// <devdoc> /// <para> /// Transforms an XML name into an object name (such as DataTable or DataColumn).</para> /// </devdoc> public static string DecodeName(string name) { if (name == null || name.Length == 0) return name; StringBuilder bufBld = null; int length = name.Length; int copyPosition = 0; int underscorePos = name.IndexOf('_'); MatchCollection mc = null; IEnumerator en = null; if (underscorePos >= 0) { if (s_decodeCharPattern == null) { s_decodeCharPattern = new Regex("_[Xx]([0-9a-fA-F]{4}|[0-9a-fA-F]{8})_"); } mc = s_decodeCharPattern.Matches(name, underscorePos); en = mc.GetEnumerator(); } else { return name; } int matchPos = -1; if (en != null && en.MoveNext()) { Match m = (Match)en.Current; matchPos = m.Index; } for (int position = 0; position < length - s_encodedCharLength + 1; position++) { if (position == matchPos) { if (en.MoveNext()) { Match m = (Match)en.Current; matchPos = m.Index; } if (bufBld == null) { bufBld = new StringBuilder(length + 20); } bufBld.Append(name, copyPosition, position - copyPosition); if (name[position + 6] != '_') { //_x1234_ Int32 u = FromHex(name[position + 2]) * 0x10000000 + FromHex(name[position + 3]) * 0x1000000 + FromHex(name[position + 4]) * 0x100000 + FromHex(name[position + 5]) * 0x10000 + FromHex(name[position + 6]) * 0x1000 + FromHex(name[position + 7]) * 0x100 + FromHex(name[position + 8]) * 0x10 + FromHex(name[position + 9]); if (u >= 0x00010000) { if (u <= 0x0010ffff) { //convert to two chars copyPosition = position + s_encodedCharLength + 4; char lowChar, highChar; XmlCharType.SplitSurrogateChar(u, out lowChar, out highChar); bufBld.Append(highChar); bufBld.Append(lowChar); } //else bad ucs-4 char dont convert } else { //convert to single char copyPosition = position + s_encodedCharLength + 4; bufBld.Append((char)u); } position += s_encodedCharLength - 1 + 4; //just skip } else { copyPosition = position + s_encodedCharLength; bufBld.Append((char)( FromHex(name[position + 2]) * 0x1000 + FromHex(name[position + 3]) * 0x100 + FromHex(name[position + 4]) * 0x10 + FromHex(name[position + 5]))); position += s_encodedCharLength - 1; } } } if (copyPosition == 0) { return name; } else { if (copyPosition < length) { bufBld.Append(name, copyPosition, length - copyPosition); } return bufBld.ToString(); } } private static string EncodeName(string name, /*Name_not_NmToken*/ bool first, bool local) { if (string.IsNullOrEmpty(name)) { return name; } StringBuilder bufBld = null; int length = name.Length; int copyPosition = 0; int position = 0; int underscorePos = name.IndexOf('_'); MatchCollection mc = null; IEnumerator en = null; if (underscorePos >= 0) { if (s_encodeCharPattern == null) { s_encodeCharPattern = new Regex("(?<=_)[Xx]([0-9a-fA-F]{4}|[0-9a-fA-F]{8})_"); } mc = s_encodeCharPattern.Matches(name, underscorePos); en = mc.GetEnumerator(); } int matchPos = -1; if (en != null && en.MoveNext()) { Match m = (Match)en.Current; matchPos = m.Index - 1; } if (first) { if ((!s_xmlCharType.IsStartNCNameCharXml4e(name[0]) && (local || (!local && name[0] != ':'))) || matchPos == 0) { if (bufBld == null) { bufBld = new StringBuilder(length + 20); } bufBld.Append("_x"); if (length > 1 && XmlCharType.IsHighSurrogate(name[0]) && XmlCharType.IsLowSurrogate(name[1])) { int x = name[0]; int y = name[1]; Int32 u = XmlCharType.CombineSurrogateChar(y, x); bufBld.Append(u.ToString("X8", CultureInfo.InvariantCulture)); position++; copyPosition = 2; } else { bufBld.Append(((Int32)name[0]).ToString("X4", CultureInfo.InvariantCulture)); copyPosition = 1; } bufBld.Append('_'); position++; if (matchPos == 0) if (en.MoveNext()) { Match m = (Match)en.Current; matchPos = m.Index - 1; } } } for (; position < length; position++) { if ((local && !s_xmlCharType.IsNCNameCharXml4e(name[position])) || (!local && !s_xmlCharType.IsNameCharXml4e(name[position])) || (matchPos == position)) { if (bufBld == null) { bufBld = new StringBuilder(length + 20); } if (matchPos == position) if (en.MoveNext()) { Match m = (Match)en.Current; matchPos = m.Index - 1; } bufBld.Append(name, copyPosition, position - copyPosition); bufBld.Append("_x"); if ((length > position + 1) && XmlCharType.IsHighSurrogate(name[position]) && XmlCharType.IsLowSurrogate(name[position + 1])) { int x = name[position]; int y = name[position + 1]; Int32 u = XmlCharType.CombineSurrogateChar(y, x); bufBld.Append(u.ToString("X8", CultureInfo.InvariantCulture)); copyPosition = position + 2; position++; } else { bufBld.Append(((Int32)name[position]).ToString("X4", CultureInfo.InvariantCulture)); copyPosition = position + 1; } bufBld.Append('_'); } } if (copyPosition == 0) { return name; } else { if (copyPosition < length) { bufBld.Append(name, copyPosition, length - copyPosition); } return bufBld.ToString(); } } private static readonly int s_encodedCharLength = 7; // ("_xFFFF_".Length); private static volatile Regex s_encodeCharPattern; private static volatile Regex s_decodeCharPattern; private static int FromHex(char digit) { return (digit <= '9') ? ((int)digit - (int)'0') : (((digit <= 'F') ? ((int)digit - (int)'A') : ((int)digit - (int)'a')) + 10); } internal static byte[] FromBinHexString(string s) { return FromBinHexString(s, true); } internal static byte[] FromBinHexString(string s, bool allowOddCount) { if (s == null) { throw new ArgumentNullException(nameof(s)); } return BinHexDecoder.Decode(s.ToCharArray(), allowOddCount); } internal static string ToBinHexString(byte[] inArray) { if (inArray == null) { throw new ArgumentNullException(nameof(inArray)); } return BinHexEncoder.Encode(inArray, 0, inArray.Length); } // // Verification methods for strings // /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyName"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> public static string VerifyName(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (name.Length == 0) { throw new ArgumentNullException(nameof(name), SR.Xml_EmptyName); } // parse name int endPos = ValidateNames.ParseNameNoNamespaces(name, 0); if (endPos != name.Length) { // did not parse to the end -> there is invalid character at endPos throw CreateInvalidNameCharException(name, endPos, ExceptionType.XmlException); } return name; } internal static string VerifyQName(string name, ExceptionType exceptionType) { if (name == null || name.Length == 0) { throw new ArgumentNullException(nameof(name)); } int colonPosition = -1; int endPos = ValidateNames.ParseQName(name, 0, out colonPosition); if (endPos != name.Length) { throw CreateException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1); } return name; } /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyNCName"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> public static string VerifyNCName(string name) { return VerifyNCName(name, ExceptionType.XmlException); } internal static string VerifyNCName(string name, ExceptionType exceptionType) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (name.Length == 0) { throw new ArgumentNullException(nameof(name), SR.Xml_EmptyLocalName); } int end = ValidateNames.ParseNCName(name, 0); if (end != name.Length) { // If the string is not a valid NCName, then throw or return false throw CreateInvalidNameCharException(name, end, exceptionType); } return name; } /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyNMTOKEN"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> public static string VerifyNMTOKEN(string name) { return VerifyNMTOKEN(name, ExceptionType.XmlException); } internal static string VerifyNMTOKEN(string name, ExceptionType exceptionType) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (name.Length == 0) { throw CreateException(SR.Xml_InvalidNmToken, name, exceptionType); } int endPos = ValidateNames.ParseNmtokenNoNamespaces(name, 0); if (endPos != name.Length) { throw CreateException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1); } return name; } // Verification method for XML characters as defined in XML spec production [2] Char. // Throws XmlException if invalid character is found, otherwise returns the input string. public static string VerifyXmlChars(string content) { if (content == null) { throw new ArgumentNullException(nameof(content)); } VerifyCharData(content, ExceptionType.XmlException); return content; } // Verification method for XML public ID characters as defined in XML spec production [13] PubidChar. // Throws XmlException if invalid character is found, otherwise returns the input string. public static string VerifyPublicId(string publicId) { if (publicId == null) { throw new ArgumentNullException(nameof(publicId)); } // returns the position of invalid character or -1 int pos = s_xmlCharType.IsPublicId(publicId); if (pos != -1) { throw CreateInvalidCharException(publicId, pos, ExceptionType.XmlException); } return publicId; } // Verification method for XML whitespace characters as defined in XML spec production [3] S. // Throws XmlException if invalid character is found, otherwise returns the input string. public static string VerifyWhitespace(string content) { if (content == null) { throw new ArgumentNullException(nameof(content)); } // returns the position of invalid character or -1 int pos = s_xmlCharType.IsOnlyWhitespaceWithPos(content); if (pos != -1) { throw new XmlException(SR.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(content, pos), 0, pos + 1); } return content; } #if XML10_FIFTH_EDITION public static bool IsStartNCNameSurrogatePair(char lowChar, char highChar) { return xmlCharType.IsNCNameSurrogateChar(lowChar, highChar); } #endif #if XML10_FIFTH_EDITION public static bool IsNCNameSurrogatePair(char lowChar, char highChar) { return xmlCharType.IsNCNameSurrogateChar(lowChar, highChar); } #endif // Value convertors: // // String representation of Base types in XML (xsd) sometimes differ from // one common language runtime offer and for all types it has to be locale independent. // o -- means that XmlConvert pass through to common language runtime converter with InvariantInfo FormatInfo // x -- means we doing something special to make a convertion. // // From: To: Bol Chr SBy Byt I16 U16 I32 U32 I64 U64 Sgl Dbl Dec Dat Tim Str uid // ------------------------------------------------------------------------------ // Boolean x // Char o // SByte o // Byte o // Int16 o // UInt16 o // Int32 o // UInt32 o // Int64 o // UInt64 o // Single x // Double x // Decimal o // DateTime x // String x o o o o o o o o o o x x o o x // Guid x // ----------------------------------------------------------------------------- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Boolean value) { return value ? "true" : "false"; } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Char value) { return value.ToString(); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Decimal value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static string ToString(SByte value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString4"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Int16 value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString5"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Int32 value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString15"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Int64 value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString6"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Byte value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString7"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static string ToString(UInt16 value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString8"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static string ToString(UInt32 value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString16"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static string ToString(UInt64 value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString9"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Single value) { if (Single.IsNegativeInfinity(value)) return "-INF"; if (Single.IsPositiveInfinity(value)) return "INF"; if (IsNegativeZero((double)value)) { return ("-0"); } return value.ToString("R", NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString10"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Double value) { if (Double.IsNegativeInfinity(value)) return "-INF"; if (Double.IsPositiveInfinity(value)) return "INF"; if (IsNegativeZero(value)) { return ("-0"); } return value.ToString("R", NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString11"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(TimeSpan value) { return new XsdDuration(value).ToString(); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString14"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption) { switch (dateTimeOption) { case XmlDateTimeSerializationMode.Local: value = SwitchToLocalTime(value); break; case XmlDateTimeSerializationMode.Utc: value = SwitchToUtcTime(value); break; case XmlDateTimeSerializationMode.Unspecified: value = new DateTime(value.Ticks, DateTimeKind.Unspecified); break; case XmlDateTimeSerializationMode.RoundtripKind: break; default: throw new ArgumentException(SR.Format(SR.Sch_InvalidDateTimeOption, dateTimeOption, "dateTimeOption")); } XsdDateTime xsdDateTime = new XsdDateTime(value, XsdDateTimeFlags.DateTime); return xsdDateTime.ToString(); } public static string ToString(DateTimeOffset value) { XsdDateTime xsdDateTime = new XsdDateTime(value); return xsdDateTime.ToString(); } public static string ToString(DateTimeOffset value, string format) { return value.ToString(format, DateTimeFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString15"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Guid value) { return value.ToString(); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToBoolean"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Boolean ToBoolean(string s) { s = TrimString(s); if (s == "1" || s == "true") return true; if (s == "0" || s == "false") return false; throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Boolean")); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToChar"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Char ToChar(string s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (s.Length != 1) { throw new FormatException(SR.XmlConvert_NotOneCharString); } return s[0]; } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDecimal"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Decimal ToDecimal(string s) { return Decimal.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToSByte"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static SByte ToSByte(string s) { return SByte.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt16"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Int16 ToInt16(string s) { return Int16.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt32"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Int32 ToInt32(string s) { return Int32.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt64"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Int64 ToInt64(string s) { return Int64.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToByte"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Byte ToByte(string s) { return Byte.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt16"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static UInt16 ToUInt16(string s) { return UInt16.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt32"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static UInt32 ToUInt32(string s) { return UInt32.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt64"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static UInt64 ToUInt64(string s) { return UInt64.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToSingle"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Single ToSingle(string s) { s = TrimString(s); if (s == "-INF") return Single.NegativeInfinity; if (s == "INF") return Single.PositiveInfinity; float f = Single.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo); if (f == 0 && s[0] == '-') { return -0f; } return f; } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDouble"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Double ToDouble(string s) { s = TrimString(s); if (s == "-INF") return Double.NegativeInfinity; if (s == "INF") return Double.PositiveInfinity; double dVal = Double.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); if (dVal == 0 && s[0] == '-') { return -0d; } return dVal; } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToTimeSpan"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static TimeSpan ToTimeSpan(string s) { XsdDuration duration; TimeSpan timeSpan; try { duration = new XsdDuration(s); } catch (Exception) { // Remap exception for v1 compatibility throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "TimeSpan")); } timeSpan = duration.ToTimeSpan(); return timeSpan; } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDateTime3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static DateTime ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption) { XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd); DateTime dt = (DateTime)xsdDateTime; switch (dateTimeOption) { case XmlDateTimeSerializationMode.Local: dt = SwitchToLocalTime(dt); break; case XmlDateTimeSerializationMode.Utc: dt = SwitchToUtcTime(dt); break; case XmlDateTimeSerializationMode.Unspecified: dt = new DateTime(dt.Ticks, DateTimeKind.Unspecified); break; case XmlDateTimeSerializationMode.RoundtripKind: break; default: throw new ArgumentException(SR.Format(SR.Sch_InvalidDateTimeOption, dateTimeOption, "dateTimeOption")); } return dt; } public static DateTimeOffset ToDateTimeOffset(string s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd); DateTimeOffset dateTimeOffset = (DateTimeOffset)xsdDateTime; return dateTimeOffset; } public static DateTimeOffset ToDateTimeOffset(string s, string format) { if (s == null) { throw new ArgumentNullException(nameof(s)); } return DateTimeOffset.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } public static DateTimeOffset ToDateTimeOffset(string s, string[] formats) { if (s == null) { throw new ArgumentNullException(nameof(s)); } return DateTimeOffset.ParseExact(s, formats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToGuid"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Guid ToGuid(string s) { return new Guid(s); } private static DateTime SwitchToLocalTime(DateTime value) { switch (value.Kind) { case DateTimeKind.Local: return value; case DateTimeKind.Unspecified: return new DateTime(value.Ticks, DateTimeKind.Local); case DateTimeKind.Utc: return value.ToLocalTime(); } return value; } private static DateTime SwitchToUtcTime(DateTime value) { switch (value.Kind) { case DateTimeKind.Utc: return value; case DateTimeKind.Unspecified: return new DateTime(value.Ticks, DateTimeKind.Utc); case DateTimeKind.Local: return value.ToUniversalTime(); } return value; } internal static Uri ToUri(string s) { if (s != null && s.Length > 0) { //string.Empty is a valid uri but not " " s = TrimString(s); if (s.Length == 0 || s.IndexOf("##", StringComparison.Ordinal) != -1) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } } Uri uri; if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri)) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } return uri; } // Compares the given character interval and string and returns true if the characters are identical internal static bool StrEqual(char[] chars, int strPos1, int strLen1, string str2) { if (strLen1 != str2.Length) { return false; } int i = 0; while (i < strLen1 && chars[strPos1 + i] == str2[i]) { i++; } return i == strLen1; } // XML whitespace characters, <spec>http://www.w3.org/TR/REC-xml#NT-S</spec> internal static readonly char[] WhitespaceChars = new char[] { ' ', '\t', '\n', '\r' }; // Trim a string using XML whitespace characters internal static string TrimString(string value) { return value.Trim(WhitespaceChars); } // Trim beginning of a string using XML whitespace characters internal static string TrimStringStart(string value) { return value.TrimStart(WhitespaceChars); } // Trim end of a string using XML whitespace characters internal static string TrimStringEnd(string value) { return value.TrimEnd(WhitespaceChars); } // Split a string into a whitespace-separated list of tokens internal static string[] SplitString(string value) { return value.Split(WhitespaceChars, StringSplitOptions.RemoveEmptyEntries); } internal static string[] SplitString(string value, StringSplitOptions splitStringOptions) { return value.Split(WhitespaceChars, splitStringOptions); } internal static bool IsNegativeZero(double value) { // Simple equals function will report that -0 is equal to +0, so compare bits instead if (value == 0 && DoubleToInt64Bits(value) == DoubleToInt64Bits(-0e0)) { return true; } return false; } #if !SILVERLIGHT_DISABLE_SECURITY [System.Security.SecuritySafeCritical] #endif private static unsafe long DoubleToInt64Bits(double value) { // NOTE: BitConverter.DoubleToInt64Bits is missing in Silverlight return *((long*)&value); } internal static void VerifyCharData(string data, ExceptionType exceptionType) { VerifyCharData(data, exceptionType, exceptionType); } internal static void VerifyCharData(string data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType) { if (data == null || data.Length == 0) { return; } int i = 0; int len = data.Length; for (; ;) { while (i < len && s_xmlCharType.IsCharData(data[i])) { i++; } if (i == len) { return; } char ch = data[i]; if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 == len) { throw CreateException(SR.Xml_InvalidSurrogateMissingLowChar, invSurrogateExceptionType, 0, i + 1); } ch = data[i + 1]; if (XmlCharType.IsLowSurrogate(ch)) { i += 2; continue; } else { throw CreateInvalidSurrogatePairException(data[i + 1], data[i], invSurrogateExceptionType, 0, i + 1); } } throw CreateInvalidCharException(data, i, invCharExceptionType); } } internal static void VerifyCharData(char[] data, int offset, int len, ExceptionType exceptionType) { if (data == null || len == 0) { return; } int i = offset; int endPos = offset + len; for (; ;) { while (i < endPos && s_xmlCharType.IsCharData(data[i])) { i++; } if (i == endPos) { return; } char ch = data[i]; if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 == endPos) { throw CreateException(SR.Xml_InvalidSurrogateMissingLowChar, exceptionType, 0, offset - i + 1); } ch = data[i + 1]; if (XmlCharType.IsLowSurrogate(ch)) { i += 2; continue; } else { throw CreateInvalidSurrogatePairException(data[i + 1], data[i], exceptionType, 0, offset - i + 1); } } throw CreateInvalidCharException(data, len, i, exceptionType); } } internal static Exception CreateException(string res, ExceptionType exceptionType) { return CreateException(res, exceptionType, 0, 0); } internal static Exception CreateException(string res, ExceptionType exceptionType, int lineNo, int linePos) { switch (exceptionType) { case ExceptionType.ArgumentException: return new ArgumentException(res); case ExceptionType.XmlException: default: return new XmlException(res, string.Empty, lineNo, linePos); } } internal static Exception CreateException(string res, string arg, ExceptionType exceptionType) { return CreateException(res, arg, exceptionType, 0, 0); } internal static Exception CreateException(string res, string arg, ExceptionType exceptionType, int lineNo, int linePos) { switch (exceptionType) { case ExceptionType.ArgumentException: return new ArgumentException(SR.Format(res, arg)); case ExceptionType.XmlException: default: return new XmlException(res, arg, lineNo, linePos); } } internal static Exception CreateException(string res, string[] args, ExceptionType exceptionType) { return CreateException(res, args, exceptionType, 0, 0); } internal static Exception CreateException(string res, string[] args, ExceptionType exceptionType, int lineNo, int linePos) { switch (exceptionType) { case ExceptionType.ArgumentException: return new ArgumentException(SR.Format(res, args)); case ExceptionType.XmlException: default: return new XmlException(res, args, lineNo, linePos); } } internal static Exception CreateInvalidSurrogatePairException(char low, char hi) { return CreateInvalidSurrogatePairException(low, hi, ExceptionType.ArgumentException); } internal static Exception CreateInvalidSurrogatePairException(char low, char hi, ExceptionType exceptionType) { return CreateInvalidSurrogatePairException(low, hi, exceptionType, 0, 0); } internal static Exception CreateInvalidSurrogatePairException(char low, char hi, ExceptionType exceptionType, int lineNo, int linePos) { string[] args = new string[] { ((uint)hi).ToString( "X", CultureInfo.InvariantCulture ), ((uint)low).ToString( "X", CultureInfo.InvariantCulture ) }; return CreateException(SR.Xml_InvalidSurrogatePairWithArgs, args, exceptionType, lineNo, linePos); } internal static Exception CreateInvalidHighSurrogateCharException(char hi) { return CreateInvalidHighSurrogateCharException(hi, ExceptionType.ArgumentException); } internal static Exception CreateInvalidHighSurrogateCharException(char hi, ExceptionType exceptionType) { return CreateInvalidHighSurrogateCharException(hi, exceptionType, 0, 0); } internal static Exception CreateInvalidHighSurrogateCharException(char hi, ExceptionType exceptionType, int lineNo, int linePos) { return CreateException(SR.Xml_InvalidSurrogateHighChar, ((uint)hi).ToString("X", CultureInfo.InvariantCulture), exceptionType, lineNo, linePos); } internal static Exception CreateInvalidCharException(char[] data, int length, int invCharPos) { return CreateInvalidCharException(data, length, invCharPos, ExceptionType.ArgumentException); } internal static Exception CreateInvalidCharException(char[] data, int length, int invCharPos, ExceptionType exceptionType) { return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, length, invCharPos), exceptionType, 0, invCharPos + 1); } internal static Exception CreateInvalidCharException(string data, int invCharPos) { return CreateInvalidCharException(data, invCharPos, ExceptionType.ArgumentException); } internal static Exception CreateInvalidCharException(string data, int invCharPos, ExceptionType exceptionType) { return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, invCharPos), exceptionType, 0, invCharPos + 1); } internal static Exception CreateInvalidCharException(char invChar, char nextChar) { return CreateInvalidCharException(invChar, nextChar, ExceptionType.ArgumentException); } internal static Exception CreateInvalidCharException(char invChar, char nextChar, ExceptionType exceptionType) { return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(invChar, nextChar), exceptionType); } internal static Exception CreateInvalidNameCharException(string name, int index, ExceptionType exceptionType) { return CreateException(index == 0 ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, index), exceptionType, 0, index + 1); } internal static ArgumentException CreateInvalidNameArgumentException(string name, string argumentName) { return (name == null) ? new ArgumentNullException(argumentName) : new ArgumentException(SR.Xml_EmptyName, argumentName); } } }
using Android.Graphics; using Android.App; using Android.Content; using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Xml.Serialization; using Plugin.Toasts.Interfaces; using System.Collections.Concurrent; namespace Plugin.Toasts { class NotificationBuilder { public static string PackageName { get; set; } public static IDictionary<string, ManualResetEvent> ResetEvent = new ConcurrentDictionary<string, ManualResetEvent>(); public static IDictionary<string, NotificationResult> EventResult = new ConcurrentDictionary<string, NotificationResult>(); public static List<string> Channels = new List<string>(); public const string NotificationId = "NOTIFICATION_ID"; public const string DismissedClickIntent = "android.intent.action.DISMISSED"; public const string OnClickIntent = "android.intent.action.CLICK"; public const string NotificationForceOpenApp = "NOTIFICATION_FORCEOPEN"; public const string DefaultChannelName = "default"; public const int StartId = 123; int _count = 0; object _lock = new object(); static NotificationReceiver _receiver; IPlatformOptions _androidOptions; public void Init(IPlatformOptions androidOptions) { PackageName = Application.Context.PackageName; IntentFilter filter = new IntentFilter(); filter.AddAction(DismissedClickIntent); filter.AddAction(OnClickIntent); _receiver = new NotificationReceiver(); Application.Context.RegisterReceiver(_receiver, filter); _androidOptions = androidOptions; } public static string GetOrCreateChannel(IAndroidChannelOptions channelOptions) { if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O) { var channelId = ""; if (channelOptions == null) channelId = DefaultChannelName; else channelId = channelOptions.Name == null? DefaultChannelName : channelOptions.Name.Replace(" ", string.Empty).ToLower(); if (string.IsNullOrEmpty(channelId) && channelOptions != null) channelOptions.Name = DefaultChannelName; if (!Channels.Contains(channelId)) { // Create new channel. var newChannel = new NotificationChannel(channelId, channelOptions.Name, NotificationImportance.High); newChannel.EnableVibration(channelOptions.EnableVibration); newChannel.SetShowBadge(channelOptions.ShowBadge); if (!string.IsNullOrEmpty(channelOptions.Description)) { newChannel.Description = channelOptions.Description; } // Register channel. var notificationManager = Application.Context.GetSystemService(Context.NotificationService) as NotificationManager; notificationManager.CreateNotificationChannel(newChannel); // Save Id for reference. Channels.Add(channelId); } return channelId; } return null; } public IList<INotification> GetDeliveredNotifications() { IList<INotification> list = new List<INotification>(); if (Android.OS.Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.M) { return new List<INotification>(); } NotificationManager notificationManager = Application.Context.GetSystemService(Context.NotificationService) as NotificationManager; foreach (var notification in notificationManager.GetActiveNotifications()) { list.Add(new Notification() { Id = notification.Id.ToString(), Title = notification.Notification.Extras.GetString("android.title"), Description = notification.Notification.Extras.GetString("android.text"), Delivered = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(notification.Notification.When) }); } return list; } void ScheduleNotification(string id, INotificationOptions options) { if (!string.IsNullOrEmpty(id) && options != null) { var intent = new Intent(Application.Context, typeof(AlarmHandler)).SetAction("AlarmHandlerIntent" + id); if (!string.IsNullOrEmpty(options.AndroidOptions.HexColor) && options.AndroidOptions.HexColor.Substring(0, 1) != "#") { options.AndroidOptions.HexColor = "#" + options.AndroidOptions.HexColor; } var notification = new ScheduledNotification() { AndroidOptions = (AndroidOptions)options.AndroidOptions, ClearFromHistory = options.ClearFromHistory, DelayUntil = options.DelayUntil, Description = options.Description, IsClickable = options.IsClickable, Title = options.Title }; var serializedNotification = Serialize(notification); intent.PutExtra(AlarmHandler.NotificationKey, serializedNotification); intent.PutExtra(NotificationId, id); intent.PutExtra(NotificationForceOpenApp, options.AndroidOptions.ForceOpenAppOnNotificationTap); var pendingIntent = PendingIntent.GetBroadcast(Application.Context, (StartId + int.Parse(id)), intent, PendingIntentFlags.CancelCurrent); var timeTriggered = ConvertToMilliseconds(options.DelayUntil.Value); var alarmManager = Application.Context.GetSystemService(Context.AlarmService) as AlarmManager; alarmManager.Set(AlarmType.RtcWakeup, timeTriggered, pendingIntent); } } long ConvertToMilliseconds(DateTime notifyTime) { var utcTime = TimeZoneInfo.ConvertTimeToUtc(notifyTime); var epochDifference = (new DateTime(1970, 1, 1) - DateTime.MinValue).TotalSeconds; return utcTime.AddSeconds(-epochDifference).Ticks / 10000; } string Serialize(ScheduledNotification options) { var xmlSerializer = new XmlSerializer(typeof(ScheduledNotification)); using (var stringWriter = new StringWriter()) { xmlSerializer.Serialize(stringWriter, options); return stringWriter.ToString(); } } public INotificationResult Notify(Activity activity, INotificationOptions options) { INotificationResult notificationResult = null; if (options != null) { var notificationId = 0; var id = ""; lock (_lock) { notificationId = _count; id = _count.ToString(); _count++; } int smallIcon; if (options.AndroidOptions.SmallDrawableIcon.HasValue) smallIcon = options.AndroidOptions.SmallDrawableIcon.Value; else if (_androidOptions.SmallIconDrawable.HasValue) smallIcon = _androidOptions.SmallIconDrawable.Value; else smallIcon = Android.Resource.Drawable.IcDialogInfo; // As last resort if (options.DelayUntil.HasValue) { options.AndroidOptions.SmallDrawableIcon = smallIcon; ScheduleNotification(id, options); return new NotificationResult() { Action = NotificationAction.NotApplicable, Id = notificationId }; } // Show Notification Right Now var dismissIntent = new Intent(DismissedClickIntent); dismissIntent.PutExtra(NotificationId, notificationId); var pendingDismissIntent = PendingIntent.GetBroadcast(Application.Context, (StartId + notificationId), dismissIntent, 0); var clickIntent = new Intent(OnClickIntent); clickIntent.PutExtra(NotificationId, notificationId); clickIntent.PutExtra(NotificationForceOpenApp, options.AndroidOptions.ForceOpenAppOnNotificationTap); // Add custom args if (options.CustomArgs != null) foreach (var arg in options.CustomArgs) clickIntent.PutExtra(arg.Key, arg.Value); var pendingClickIntent = PendingIntent.GetBroadcast(Application.Context, (StartId + notificationId), clickIntent, 0); if (!string.IsNullOrEmpty(options.AndroidOptions.HexColor) && options.AndroidOptions.HexColor.Substring(0, 1) != "#") { options.AndroidOptions.HexColor = "#" + options.AndroidOptions.HexColor; } Android.App.Notification.Builder builder = new Android.App.Notification.Builder(Application.Context) .SetContentTitle(options.Title) .SetContentText(options.Description) .SetSmallIcon(smallIcon) // Must have small icon to display .SetPriority((int)NotificationPriority.High) // Must be set to High to get Heads-up notification .SetDefaults(NotificationDefaults.All) // Must also include vibrate to get Heads-up notification .SetAutoCancel(true) // To allow click event to trigger delete Intent .SetContentIntent(pendingClickIntent) // Must have Intent to accept the click .SetDeleteIntent(pendingDismissIntent) .SetColor(Color.ParseColor(options.AndroidOptions.HexColor)); try { // Notification Channel if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O) { var notificationChannelId = GetOrCreateChannel(options.AndroidOptions.ChannelOptions); if (!string.IsNullOrEmpty(notificationChannelId)) { builder.SetChannelId(notificationChannelId); } } } catch { } // System.MissingMethodException: Method 'Android.App.Notification/Builder.SetChannelId' not found. // I know this is bad, but I can't replicate it on any version, and many people are experiencing it. Android.App.Notification notification = builder.Build(); NotificationManager notificationManager = Application.Context.GetSystemService(Context.NotificationService) as NotificationManager; notificationManager.Notify(notificationId, notification); if (options.DelayUntil.HasValue) { return new NotificationResult() { Action = NotificationAction.NotApplicable, Id = notificationId }; } var timer = new Timer(x => TimerFinished(id, options.ClearFromHistory, options.AllowTapInNotificationCenter), null, TimeSpan.FromSeconds(7), TimeSpan.FromMilliseconds(-1)); var resetEvent = new ManualResetEvent(false); ResetEvent.Add(id, resetEvent); resetEvent.WaitOne(); // Wait for a result notificationResult = EventResult[id]; if (!options.IsClickable && notificationResult.Action == NotificationAction.Clicked) { notificationResult.Action = NotificationAction.Dismissed; notificationResult.Id = notificationId; } if (EventResult.ContainsKey(id)) { EventResult.Remove(id); } if (ResetEvent.ContainsKey(id)) { ResetEvent.Remove(id); } // Dispose of Intents and Timer pendingClickIntent.Cancel(); pendingDismissIntent.Cancel(); timer.Dispose(); } return notificationResult; } public void CancelAll() { using (NotificationManager notificationManager = Application.Context.GetSystemService(Context.NotificationService) as NotificationManager) { notificationManager.CancelAll(); } } void TimerFinished(string id, bool cancel, bool allowTapInNotificationCenter) { if (string.IsNullOrEmpty(id)) return; if (cancel) // Will clear from Notification Center { using (NotificationManager notificationManager = Application.Context.GetSystemService(Context.NotificationService) as NotificationManager) { notificationManager.Cancel(Convert.ToInt32(id)); } } if (!allowTapInNotificationCenter || cancel) if (ResetEvent.ContainsKey(id)) { if (EventResult != null) { EventResult.Add(id, new NotificationResult() { Action = NotificationAction.Timeout, Id = int.Parse(id) }); } if (ResetEvent != null && ResetEvent.ContainsKey(id)) { ResetEvent[id].Set(); } } } } class NotificationReceiver : BroadcastReceiver { public override void OnReceive(Context context, Intent intent) { var notificationId = intent.Extras.GetInt(NotificationBuilder.NotificationId, -1); if (notificationId > -1) { switch (intent.Action) { case NotificationBuilder.OnClickIntent: try { // Attempt to re-focus/open the app. var doForceOpen = intent.Extras.GetBoolean(NotificationBuilder.NotificationForceOpenApp, false); if (doForceOpen) { var packageManager = Application.Context.PackageManager; Intent launchIntent = packageManager.GetLaunchIntentForPackage(NotificationBuilder.PackageName); if (launchIntent != null) { launchIntent.AddCategory(Intent.CategoryLauncher); Application.Context.StartActivity(launchIntent); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Failed to re-focus/launch the app: " + ex); } // Click if (NotificationBuilder.EventResult != null && !NotificationBuilder.EventResult.ContainsKey(notificationId.ToString())) { NotificationBuilder.EventResult.Add(notificationId.ToString(), new NotificationResult() { Action = NotificationAction.Clicked, Id = notificationId }); } break; default: // Dismiss/Default if (NotificationBuilder.EventResult != null && !NotificationBuilder.EventResult.ContainsKey(notificationId.ToString())) { NotificationBuilder.EventResult.Add(notificationId.ToString(), new NotificationResult() { Action = NotificationAction.Dismissed, Id = notificationId }); } break; } if (NotificationBuilder.ResetEvent != null && NotificationBuilder.ResetEvent.ContainsKey(notificationId.ToString())) { NotificationBuilder.ResetEvent[notificationId.ToString()].Set(); } } } } }
using System; using System.Drawing; using System.Drawing.Imaging; namespace Hydra.Framework.ImageProcessing.Analysis.Filters { // //********************************************************************** /// <summary> /// MoveTowards filter - move source image towards overlay image by /// the specified value /// </summary> //********************************************************************** // public class MoveTowards : IFilter { #region Private Member Variables // //********************************************************************** /// <summary> /// Step Size (default to 1) /// </summary> //********************************************************************** // private int stepSize_m = 1; // //********************************************************************** /// <summary> /// Overlay Image bitmap /// </summary> //********************************************************************** // private Bitmap overlayImage_m; #endregion #region Properties // //********************************************************************** /// <summary> /// Gets or sets the size of the StepSize property. /// </summary> /// <value>The size of the step.</value> //********************************************************************** // public int StepSize { get { return stepSize_m; } set { stepSize_m = Math.Max(1, Math.Min(255, value)); } } // //********************************************************************** /// <summary> /// Gets or sets the overlay image property. /// </summary> /// <value>The overlay image.</value> //********************************************************************** // public Bitmap OverlayImage { get { return overlayImage_m; } set { overlayImage_m = value; } } #endregion #region Constructors // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:MoveTowards"/> class. /// </summary> //********************************************************************** // public MoveTowards() { } // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:MoveTowards"/> class. /// </summary> /// <param name="overlayImage">The overlay image.</param> //********************************************************************** // public MoveTowards(Bitmap overlayImage) { this.overlayImage_m = overlayImage; } // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:MoveTowards"/> class. /// </summary> /// <param name="overlayImage">The overlay image.</param> /// <param name="stepSize">Size of the step.</param> //********************************************************************** // public MoveTowards(Bitmap overlayImage, int stepSize) { this.overlayImage_m = overlayImage; StepSize = stepSize; } // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:MoveTowards"/> class. /// </summary> /// <param name="stepSize">Size of the step.</param> //********************************************************************** // public MoveTowards(int stepSize) { StepSize = stepSize; } #endregion #region Public Methods // //********************************************************************** /// <summary> /// Apply filter /// Output image will have the same dimension as source image /// </summary> /// <param name="srcImg">The SRC img.</param> /// <returns></returns> //********************************************************************** // public Bitmap Apply(Bitmap srcImg) { // // get source image size // int width = srcImg.Width; int height = srcImg.Height; // // overlay dimension // int ovrW = overlayImage_m.Width; int ovrH = overlayImage_m.Height; // // source image and overlay must have the same pixel format, width and height // if ((srcImg.PixelFormat != overlayImage_m.PixelFormat) || (width != ovrW) || (height != ovrH)) throw new ArgumentException(); PixelFormat fmt = (srcImg.PixelFormat == PixelFormat.Format8bppIndexed) ? PixelFormat.Format8bppIndexed : PixelFormat.Format24bppRgb; // // lock source bitmap data // BitmapData srcData = srcImg.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, fmt); // // create new image // Bitmap dstImg = (fmt == PixelFormat.Format8bppIndexed) ? Hydra.Framework.ImageProcessing.Analysis.Image.CreateGrayscaleImage(width, height) : new Bitmap(width, height, fmt); // // lock destination bitmap data // BitmapData dstData = dstImg.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, fmt); // // lock overlay image // BitmapData ovrData = overlayImage_m.LockBits( new Rectangle(0, 0, ovrW, ovrH), ImageLockMode.ReadOnly, fmt); int pixelSize = (fmt == PixelFormat.Format8bppIndexed) ? 1 : 3; int stride = srcData.Stride; int offset = stride - pixelSize * width; int v; // // do the job (Warning Unsafe Code) // unsafe { byte * src = (byte *) srcData.Scan0.ToPointer(); byte * dst = (byte *) dstData.Scan0.ToPointer(); byte * ovr = (byte *) ovrData.Scan0.ToPointer(); // // for each line // for (int y = 0; y < height; y++) { // // for each pixel // for (int x = 0; x < width; x++) { for (int i = 0; i < pixelSize; i++, src++, dst++, ovr++) { v = (int) *ovr - *src; *dst = *src; if (v > 0) { *dst += (byte)((stepSize_m < v) ? stepSize_m : v); } else if (v < 0) { v = -v; *dst -= (byte)((stepSize_m < v) ? stepSize_m : v); } } } src += offset; dst += offset; ovr += offset; } } // // unlock all images // dstImg.UnlockBits(dstData); srcImg.UnlockBits(srcData); overlayImage_m.UnlockBits(ovrData); return dstImg; } #endregion } }
//----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- function initializeForestEditor() { echo(" % - Initializing Forest Editor"); exec( "./forestEditor.cs" ); exec( "./forestEditorGui.gui" ); exec( "./forestEditToolbar.ed.gui" ); exec( "./forestEditorGui.cs" ); exec( "./tools.cs" ); ForestEditorGui.setVisible( false ); ForestEditorPalleteWindow.setVisible( false ); ForestEditorPropertiesWindow.setVisible( false ); ForestEditToolbar.setVisible( false ); EditorGui.add( ForestEditorGui ); EditorGui.add( ForestEditorPalleteWindow ); EditorGui.add( ForestEditorPropertiesWindow ); EditorGui.add( ForestEditToolbar ); new ScriptObject( ForestEditorPlugin ) { superClass = "EditorPlugin"; editorGui = ForestEditorGui; }; new SimSet(ForestTools) { new ForestBrushTool() { internalName = "BrushTool"; toolTip = "Paint Tool"; buttonImage = "tools/forest/images/brushTool"; }; new ForestSelectionTool() { internalName = "SelectionTool"; toolTip = "Selection Tool"; buttonImage = "tools/forest/images/selectionTool"; }; }; %map = new ActionMap(); %map.bindCmd( keyboard, "1", "ForestEditorSelectModeBtn.performClick();", "" ); // Select %map.bindCmd( keyboard, "2", "ForestEditorMoveModeBtn.performClick();", "" ); // Move %map.bindCmd( keyboard, "3", "ForestEditorRotateModeBtn.performClick();", "" ); // Rotate %map.bindCmd( keyboard, "4", "ForestEditorScaleModeBtn.performClick();", "" ); // Scale %map.bindCmd( keyboard, "5", "ForestEditorPaintModeBtn.performClick();", "" ); // Paint %map.bindCmd( keyboard, "6", "ForestEditorEraseModeBtn.performClick();", "" ); // Erase %map.bindCmd( keyboard, "7", "ForestEditorEraseSelectedModeBtn.performClick();", "" ); // EraseSelected //%map.bindCmd( keyboard, "backspace", "ForestEditorGui.onDeleteKey();", "" ); //%map.bindCmd( keyboard, "delete", "ForestEditorGui.onDeleteKey();", "" ); ForestEditorPlugin.map = %map; } function destroyForestEditor() { } // NOTE: debugging helper. function reinitForest() { exec( "./main.cs" ); exec( "./forestEditorGui.cs" ); exec( "./tools.cs" ); } function ForestEditorPlugin::onWorldEditorStartup( %this ) { new PersistenceManager( ForestDataManager ); %brushPath = "art/forest/brushes.cs"; if ( !isFile( %brushPath ) ) createPath( %brushPath ); // This creates the ForestBrushGroup, all brushes, and elements. exec( %brushpath ); if ( !isObject( ForestBrushGroup ) ) { new SimGroup( ForestBrushGroup ); %this.showError = true; } ForestEditBrushTree.open( ForestBrushGroup ); if ( !isObject( ForestItemDataSet ) ) new SimSet( ForestItemDataSet ); ForestEditMeshTree.open( ForestItemDataSet ); // Add ourselves to the window menu. %accel = EditorGui.addToEditorsMenu( "Forest Editor", "", ForestEditorPlugin ); // Add ourselves to the tools menu. %tooltip = "Forest Editor (" @ %accel @ ")"; EditorGui.addToToolsToolbar( "ForestEditorPlugin", "ForestEditorPalette", expandFilename("tools/forestEditor/images/forest-editor-btn"), %tooltip ); //connect editor windows GuiWindowCtrl::attach( ForestEditorPropertiesWindow, ForestEditorPalleteWindow ); ForestEditTabBook.selectPage(0); } function ForestEditorPlugin::onWorldEditorShutdown( %this ) { if ( isObject( ForestBrushGroup ) ) ForestBrushGroup.delete(); if ( isObject( ForestDataManager ) ) ForestDataManager.delete(); } function ForestEditorPlugin::onActivated( %this ) { EditorGui.bringToFront( ForestEditorGui ); ForestEditorGui.setVisible( true ); ForestEditorPalleteWindow.setVisible( true ); ForestEditorPropertiesWindow.setVisible( true ); ForestEditorGui.makeFirstResponder( true ); //ForestEditToolbar.setVisible( true ); //Get our existing forest object in our current mission if we have one %forestObject = trim(parseMissionGroupForIds("Forest", "")); if(isObject(%forestObject)) { ForestEditorGui.setActiveForest(%forestObject.getName()); } %this.map.push(); Parent::onActivated(%this); ForestEditBrushTree.open( ForestBrushGroup ); ForestEditMeshTree.open( ForestItemDataSet ); // Open the Brush tab. ForestEditTabBook.selectPage(0); // Sync the pallete button state // And toolbar. %tool = ForestEditorGui.getActiveTool(); if ( isObject( %tool ) ) %tool.onActivated(); if ( !isObject( %tool ) ) { ForestEditorPaintModeBtn.performClick(); if ( ForestEditBrushTree.getItemCount() > 0 ) { ForestEditBrushTree.selectItem( 0, true ); } } else if ( %tool == ForestTools->SelectionTool ) { %mode = GlobalGizmoProfile.mode; switch$ (%mode) { case "None": ForestEditorSelectModeBtn.performClick(); case "Move": ForestEditorMoveModeBtn.performClick(); case "Rotate": ForestEditorRotateModeBtn.performClick(); case "Scale": ForestEditorScaleModeBtn.performClick(); } } else if ( %tool == ForestTools->BrushTool ) { %mode = ForestTools->BrushTool.mode; switch$ (%mode) { case "Paint": ForestEditorPaintModeBtn.performClick(); case "Erase": ForestEditorEraseModeBtn.performClick(); case "EraseSelected": ForestEditorEraseSelectedModeBtn.performClick(); } } if ( %this.showError ) MessageBoxOK( "Error", "Your art/forest folder does not contain a valid brushes.cs. Brushes you create will not be saved!" ); } function ForestEditorPlugin::onDeactivated( %this ) { ForestEditorGui.setVisible( false ); ForestEditorPalleteWindow.setVisible( false ); ForestEditorPropertiesWindow.setVisible( false ); %tool = ForestEditorGui.getActiveTool(); if ( isObject( %tool ) ) %tool.onDeactivated(); // Also take this opportunity to save. ForestDataManager.saveDirty(); %this.map.pop(); Parent::onDeactivated(%this); } function ForestEditorPlugin::isDirty( %this ) { %dirty = %this.dirty || ForestEditorGui.isDirty(); return %dirty; } function ForestEditorPlugin::clearDirty( %this ) { %this.dirty = false; } function ForestEditorPlugin::onSaveMission( %this, %missionFile ) { ForestDataManager.saveDirty(); //First, find out if we have an existing forest object %forestObject = trim(parseMissionGroupForIds("Forest", "")); if ( isObject( %forestObject ) ) { //We do. Next, see if we have a file already by polling the datafield. if(%forestObject.dataFile !$= "") { //If we do, just save to the provided file. %forestObject.saveDataFile(%forestObject.dataFile); } else { //We don't, so we'll save in the same place as the mission file and give it the missionpath\missionName.forest //naming convention. %path = filePath(%missionFile); %missionName = fileBase(%missionFile); %forestObject.saveDataFile(%path @ "/" @ %missionName @ ".forest"); } } ForestBrushGroup.save( "art/forest/brushes.cs" ); } function ForestEditorPlugin::onEditorSleep( %this ) { } function ForestEditorPlugin::onEditMenuSelect( %this, %editMenu ) { %hasSelection = false; %selTool = ForestTools->SelectionTool; if ( ForestEditorGui.getActiveTool() == %selTool ) if ( %selTool.getSelectionCount() > 0 ) %hasSelection = true; %editMenu.enableItem( 3, %hasSelection ); // Cut %editMenu.enableItem( 4, %hasSelection ); // Copy %editMenu.enableItem( 5, %hasSelection ); // Paste %editMenu.enableItem( 6, %hasSelection ); // Delete %editMenu.enableItem( 8, %hasSelection ); // Deselect } function ForestEditorPlugin::handleDelete( %this ) { ForestTools->SelectionTool.deleteSelection(); } function ForestEditorPlugin::handleDeselect( %this ) { ForestTools->SelectionTool.clearSelection(); } function ForestEditorPlugin::handleCut( %this ) { ForestTools->SelectionTool.cutSelection(); } function ForestEditorPlugin::handleCopy( %this ) { ForestTools->SelectionTool.copySelection(); } function ForestEditorPlugin::handlePaste( %this ) { ForestTools->SelectionTool.pasteSelection(); }
// 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; namespace System.Threading { internal static partial class WaitSubsystem { /// <summary> /// Contains thread-specific information for the wait subsystem. There is one instance per thread that is registered /// using <see cref="WaitedListNode"/>s with each <see cref="WaitableObject"/> that the thread is waiting upon. /// /// Used by the wait subsystem on Unix, so this class cannot have any dependencies on the wait subsystem. /// </summary> public sealed class ThreadWaitInfo { private readonly Thread _thread; /// <summary> /// The monitor the thread would wait upon when the wait needs to be interruptible /// </summary> private readonly LowLevelMonitor _waitMonitor; //////////////////////////////////////////////////////////////// /// Thread wait state. The following members indicate the waiting state of the thread, and convery information from /// a signaler to the waiter. They are synchronized with <see cref="_waitMonitor"/>. private WaitSignalState _waitSignalState; /// <summary> /// Index of the waitable object in <see cref="_waitedObjects"/>, which got signaled and satisfied the wait. -1 if /// the wait has not yet been satisfied. /// </summary> private int _waitedObjectIndexThatSatisfiedWait; //////////////////////////////////////////////////////////////// /// Information about the current wait, including the type of wait, the <see cref="WaitableObject"/>s involved in /// the wait, etc. They are synchronized with <see cref="s_lock"/>. private bool _isWaitForAll; /// <summary> /// Number of <see cref="WaitableObject"/>s the thread is waiting upon /// </summary> private int _waitedCount; /// <summary> /// - <see cref="WaitableObject"/>s that are waited upon by the thread. This array is also used for temporarily /// storing <see cref="WaitableObject"/>s corresponding to <see cref="WaitHandle"/>s when the thread is not /// waiting. /// - The count of this array is a power of 2, the filled count is <see cref="_waitedCount"/> /// - Indexes in all arrays that use <see cref="_waitedCount"/> correspond /// </summary> private WaitHandleArray<WaitableObject> _waitedObjects; /// <summary> /// - Nodes used for registering a thread's wait on each <see cref="WaitableObject"/>, in the /// <see cref="WaitableObject.WaitersHead"/> linked list /// - The count of this array is a power of 2, the filled count is <see cref="_waitedCount"/> /// - Indexes in all arrays that use <see cref="_waitedCount"/> correspond /// </summary> private WaitHandleArray<WaitedListNode> _waitedListNodes; /// <summary> /// Indicates whether the next wait should be interrupted. /// /// Synchronization: /// - In most cases, reads and writes are synchronized with <see cref="s_lock"/> /// - Sleep(nonzero) intentionally does not acquire <see cref="s_lock"/>, but it must acquire /// <see cref="_waitMonitor"/> to do the wait. To support this case, a pending interrupt is recorded while /// <see cref="s_lock"/> and <see cref="_waitMonitor"/> are locked, and the read and reset for Sleep(nonzero) are /// done while <see cref="_waitMonitor"/> is locked. /// - Sleep(0) intentionally does not acquire any lock, so it uses an interlocked compare-exchange for the read and /// reset, see <see cref="CheckAndResetPendingInterrupt_NotLocked"/> /// </summary> private int _isPendingInterrupt; //////////////////////////////////////////////////////////////// /// <summary> /// Linked list of mutex <see cref="WaitableObject"/>s that are owned by the thread and need to be abandoned before /// the thread exits. The linked list has only a head and no tail, which means acquired mutexes are prepended and /// mutexes are abandoned in reverse order. /// </summary> private WaitableObject _lockedMutexesHead; public ThreadWaitInfo(Thread thread) { Debug.Assert(thread != null); _thread = thread; _waitMonitor = new LowLevelMonitor(); _waitSignalState = WaitSignalState.NotWaiting; _waitedObjectIndexThatSatisfiedWait = -1; _waitedObjects = new WaitHandleArray<WaitableObject>(elementInitializer: null); _waitedListNodes = new WaitHandleArray<WaitedListNode>(i => new WaitedListNode(this, i)); } public Thread Thread => _thread; private bool IsWaiting { get { _waitMonitor.VerifyIsLocked(); return _waitSignalState < WaitSignalState.NotWaiting; } } /// <summary> /// Callers must ensure to clear the array after use. Once <see cref="RegisterWait(int, bool)"/> is called (followed /// by a call to <see cref="Wait(int, bool, out int)"/>, the array will be cleared automatically. /// </summary> public WaitableObject[] GetWaitedObjectArray(int requiredCapacity) { Debug.Assert(_thread == Thread.CurrentThread); Debug.Assert(_waitedCount == 0); _waitedObjects.VerifyElementsAreDefault(); _waitedObjects.EnsureCapacity(requiredCapacity); return _waitedObjects.Items; } private WaitedListNode[] GetWaitedListNodeArray(int requiredCapacity) { Debug.Assert(_thread == Thread.CurrentThread); Debug.Assert(_waitedCount == 0); _waitedListNodes.EnsureCapacity(requiredCapacity, i => new WaitedListNode(this, i)); return _waitedListNodes.Items; } /// <summary> /// The caller is expected to populate <see cref="WaitedObjects"/> and pass in the number of objects filled /// </summary> public void RegisterWait(int waitedCount, bool prioritize, bool isWaitForAll) { s_lock.VerifyIsLocked(); Debug.Assert(_thread == Thread.CurrentThread); Debug.Assert(waitedCount > (isWaitForAll ? 1 : 0)); Debug.Assert(waitedCount <= _waitedObjects.Items.Length); Debug.Assert(_waitedCount == 0); WaitableObject[] waitedObjects = _waitedObjects.Items; #if DEBUG for (int i = 0; i < waitedCount; ++i) { Debug.Assert(waitedObjects[i] != null); } for (int i = waitedCount; i < waitedObjects.Length; ++i) { Debug.Assert(waitedObjects[i] == null); } #endif bool success = false; WaitedListNode[] waitedListNodes; try { waitedListNodes = GetWaitedListNodeArray(waitedCount); success = true; } finally { if (!success) { // Once this function is called, the caller is effectively transferring ownership of the waited objects // to this and the wait functions. On exception, clear the array. for (int i = 0; i < waitedCount; ++i) { waitedObjects[i] = null; } } } _isWaitForAll = isWaitForAll; _waitedCount = waitedCount; if (prioritize) { for (int i = 0; i < waitedCount; ++i) { waitedListNodes[i].RegisterPrioritizedWait(waitedObjects[i]); } } else { for (int i = 0; i < waitedCount; ++i) { waitedListNodes[i].RegisterWait(waitedObjects[i]); } } } public void UnregisterWait() { s_lock.VerifyIsLocked(); Debug.Assert(_waitedCount > (_isWaitForAll ? 1 : 0)); for (int i = 0; i < _waitedCount; ++i) { _waitedListNodes.Items[i].UnregisterWait(_waitedObjects.Items[i]); _waitedObjects.Items[i] = null; } _waitedCount = 0; } private int ProcessSignaledWaitState() { s_lock.VerifyIsNotLocked(); _waitMonitor.VerifyIsLocked(); Debug.Assert(_thread == Thread.CurrentThread); switch (_waitSignalState) { case WaitSignalState.Waiting: case WaitSignalState.Waiting_Interruptible: return WaitHandle.WaitTimeout; case WaitSignalState.NotWaiting_SignaledToSatisfyWait: { Debug.Assert(_waitedObjectIndexThatSatisfiedWait >= 0); int waitedObjectIndexThatSatisfiedWait = _waitedObjectIndexThatSatisfiedWait; _waitedObjectIndexThatSatisfiedWait = -1; return waitedObjectIndexThatSatisfiedWait; } case WaitSignalState.NotWaiting_SignaledToSatisfyWaitWithAbandonedMutex: { Debug.Assert(_waitedObjectIndexThatSatisfiedWait >= 0); int waitedObjectIndexThatSatisfiedWait = _waitedObjectIndexThatSatisfiedWait; _waitedObjectIndexThatSatisfiedWait = -1; return WaitHandle.WaitAbandoned + waitedObjectIndexThatSatisfiedWait; } case WaitSignalState.NotWaiting_SignaledToAbortWaitDueToMaximumMutexReacquireCount: Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0); throw new OverflowException(SR.Overflow_MutexReacquireCount); default: Debug.Assert(_waitSignalState == WaitSignalState.NotWaiting_SignaledToInterruptWait); Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0); throw new ThreadInterruptedException(); } } public int Wait(int timeoutMilliseconds, bool interruptible, bool isSleep) { if (isSleep) { s_lock.VerifyIsNotLocked(); } else { s_lock.VerifyIsLocked(); } Debug.Assert(_thread == Thread.CurrentThread); Debug.Assert(timeoutMilliseconds >= -1); Debug.Assert(timeoutMilliseconds != 0); // caller should have taken care of it _thread.SetWaitSleepJoinState(); /// <see cref="_waitMonitor"/> must be acquired before <see cref="s_lock"/> is released, to ensure that there is /// no gap during which a waited object may be signaled to satisfy the wait but the thread may not yet be in a /// wait state to accept the signal _waitMonitor.Acquire(); if (!isSleep) { s_lock.Release(); } Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0); Debug.Assert(_waitSignalState == WaitSignalState.NotWaiting); // A signaled state may be set only when the thread is in one of the following states _waitSignalState = interruptible ? WaitSignalState.Waiting_Interruptible : WaitSignalState.Waiting; try { if (isSleep && interruptible && CheckAndResetPendingInterrupt) { throw new ThreadInterruptedException(); } if (timeoutMilliseconds < 0) { do { _waitMonitor.Wait(); } while (IsWaiting); int waitResult = ProcessSignaledWaitState(); Debug.Assert(waitResult != WaitHandle.WaitTimeout); return waitResult; } int elapsedMilliseconds = 0; int startTimeMilliseconds = Environment.TickCount; while (true) { bool monitorWaitResult = _waitMonitor.Wait(timeoutMilliseconds - elapsedMilliseconds); // It's possible for the wait to have timed out, but before the monitor could reacquire the lock, a // signaler could have acquired it and signaled to satisfy the wait or interrupt the thread. Accept the // signal and ignore the wait timeout. int waitResult = ProcessSignaledWaitState(); if (waitResult != WaitHandle.WaitTimeout) { return waitResult; } if (monitorWaitResult) { elapsedMilliseconds = Environment.TickCount - startTimeMilliseconds; if (elapsedMilliseconds < timeoutMilliseconds) { continue; } } // Timeout Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0); break; } } finally { _waitSignalState = WaitSignalState.NotWaiting; _waitMonitor.Release(); _thread.ClearWaitSleepJoinState(); } /// Timeout. It's ok to read <see cref="_waitedCount"/> without acquiring <see cref="s_lock"/> here, because it /// is initially set by this thread, and another thread cannot unregister this thread's wait without first /// signaling this thread, in which case this thread wouldn't be timing out. Debug.Assert(isSleep == (_waitedCount == 0)); if (!isSleep) { s_lock.Acquire(); UnregisterWait(); s_lock.Release(); } return WaitHandle.WaitTimeout; } public static void UninterruptibleSleep0() { s_lock.VerifyIsNotLocked(); // On Unix, a thread waits on a condition variable. The timeout time will have already elapsed at the time // of the call. The documentation does not state whether the thread yields or does nothing before returning // an error, and in some cases, suggests that doing nothing is acceptable. The behavior could also be // different between distributions. Yield directly here. Thread.Yield(); } public static void Sleep(int timeoutMilliseconds, bool interruptible) { s_lock.VerifyIsNotLocked(); Debug.Assert(timeoutMilliseconds >= -1); if (timeoutMilliseconds == 0) { if (interruptible && Thread.CurrentThread.WaitInfo.CheckAndResetPendingInterrupt_NotLocked) { throw new ThreadInterruptedException(); } UninterruptibleSleep0(); return; } int waitResult = Thread .CurrentThread .WaitInfo .Wait(timeoutMilliseconds, interruptible, isSleep: true); Debug.Assert(waitResult == WaitHandle.WaitTimeout); } public bool TrySignalToSatisfyWait(WaitedListNode registeredListNode, bool isAbandonedMutex) { s_lock.VerifyIsLocked(); Debug.Assert(_thread != Thread.CurrentThread); Debug.Assert(registeredListNode != null); Debug.Assert(registeredListNode.WaitInfo == this); Debug.Assert(registeredListNode.WaitedObjectIndex >= 0); Debug.Assert(registeredListNode.WaitedObjectIndex < _waitedCount); Debug.Assert(_waitedCount > (_isWaitForAll ? 1 : 0)); int signaledWaitedObjectIndex = registeredListNode.WaitedObjectIndex; bool isWaitForAll = _isWaitForAll; int waitedCount = 0; WaitableObject[] waitedObjects = null; bool wouldAnyMutexReacquireCountOverflow = false; if (isWaitForAll) { // Determine if all waits would be satisfied waitedCount = _waitedCount; waitedObjects = _waitedObjects.Items; if (!WaitableObject.WouldWaitForAllBeSatisfiedOrAborted( _thread, waitedObjects, waitedCount, signaledWaitedObjectIndex, ref wouldAnyMutexReacquireCountOverflow, ref isAbandonedMutex)) { return false; } } // The wait would be satisfied. Before making changes to satisfy the wait, acquire the monitor and verify that // the thread can accept a signal. _waitMonitor.Acquire(); if (!IsWaiting) { _waitMonitor.Release(); return false; } if (isWaitForAll && !wouldAnyMutexReacquireCountOverflow) { // All waits would be satisfied, accept the signals WaitableObject.SatisfyWaitForAll(this, waitedObjects, waitedCount, signaledWaitedObjectIndex); } UnregisterWait(); Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0); if (wouldAnyMutexReacquireCountOverflow) { _waitSignalState = WaitSignalState.NotWaiting_SignaledToAbortWaitDueToMaximumMutexReacquireCount; } else { _waitedObjectIndexThatSatisfiedWait = signaledWaitedObjectIndex; _waitSignalState = isAbandonedMutex ? WaitSignalState.NotWaiting_SignaledToSatisfyWaitWithAbandonedMutex : WaitSignalState.NotWaiting_SignaledToSatisfyWait; } _waitMonitor.Signal_Release(); return !wouldAnyMutexReacquireCountOverflow; } public void TrySignalToInterruptWaitOrRecordPendingInterrupt() { s_lock.VerifyIsLocked(); _waitMonitor.Acquire(); if (_waitSignalState != WaitSignalState.Waiting_Interruptible) { RecordPendingInterrupt(); _waitMonitor.Release(); return; } if (_waitedCount != 0) { UnregisterWait(); } Debug.Assert(_waitedObjectIndexThatSatisfiedWait < 0); _waitSignalState = WaitSignalState.NotWaiting_SignaledToInterruptWait; _waitMonitor.Signal_Release(); } private void RecordPendingInterrupt() { s_lock.VerifyIsLocked(); _waitMonitor.VerifyIsLocked(); _isPendingInterrupt = 1; } public bool CheckAndResetPendingInterrupt { get { #if DEBUG Debug.Assert(s_lock.IsLocked || _waitMonitor.IsLocked); #endif if (_isPendingInterrupt == 0) { return false; } _isPendingInterrupt = 0; return true; } } private bool CheckAndResetPendingInterrupt_NotLocked { get { s_lock.VerifyIsNotLocked(); _waitMonitor.VerifyIsNotLocked(); return Interlocked.CompareExchange(ref _isPendingInterrupt, 0, 1) != 0; } } public WaitableObject LockedMutexesHead { get { s_lock.VerifyIsLocked(); return _lockedMutexesHead; } set { s_lock.VerifyIsLocked(); _lockedMutexesHead = value; } } public void OnThreadExiting() { // Abandon locked mutexes. Acquired mutexes are prepended to the linked list, so the mutexes are abandoned in // last-acquired-first-abandoned order. s_lock.Acquire(); try { while (true) { WaitableObject waitableObject = LockedMutexesHead; if (waitableObject == null) { break; } waitableObject.AbandonMutex(); Debug.Assert(LockedMutexesHead != waitableObject); } } finally { s_lock.Release(); } } public sealed class WaitedListNode { /// <summary> /// For <see cref="WaitedListNode"/>s registered with <see cref="WaitableObject"/>s, this provides information /// about the thread that is waiting and the <see cref="WaitableObject"/>s it is waiting upon /// </summary> private readonly ThreadWaitInfo _waitInfo; /// <summary> /// Index of the waited object corresponding to this node /// </summary> private readonly int _waitedObjectIndex; /// <summary> /// Link in the <see cref="WaitableObject.WaitersHead"/> linked list /// </summary> private WaitedListNode _previous, _next; public WaitedListNode(ThreadWaitInfo waitInfo, int waitedObjectIndex) { Debug.Assert(waitInfo != null); Debug.Assert(waitedObjectIndex >= 0); Debug.Assert(waitedObjectIndex < WaitHandle.MaxWaitHandles); _waitInfo = waitInfo; _waitedObjectIndex = waitedObjectIndex; } public ThreadWaitInfo WaitInfo { get { s_lock.VerifyIsLocked(); return _waitInfo; } } public int WaitedObjectIndex { get { s_lock.VerifyIsLocked(); return _waitedObjectIndex; } } public WaitedListNode Previous { get { s_lock.VerifyIsLocked(); return _previous; } } public WaitedListNode Next { get { s_lock.VerifyIsLocked(); return _next; } } public void RegisterWait(WaitableObject waitableObject) { s_lock.VerifyIsLocked(); Debug.Assert(_waitInfo.Thread == Thread.CurrentThread); Debug.Assert(waitableObject != null); Debug.Assert(_previous == null); Debug.Assert(_next == null); WaitedListNode tail = waitableObject.WaitersTail; if (tail != null) { _previous = tail; tail._next = this; } else { waitableObject.WaitersHead = this; } waitableObject.WaitersTail = this; } public void RegisterPrioritizedWait(WaitableObject waitableObject) { s_lock.VerifyIsLocked(); Debug.Assert(_waitInfo.Thread == Thread.CurrentThread); Debug.Assert(waitableObject != null); Debug.Assert(_previous == null); Debug.Assert(_next == null); WaitedListNode head = waitableObject.WaitersHead; if (head != null) { _next = head; head._previous = this; } else { waitableObject.WaitersTail = this; } waitableObject.WaitersHead = this; } public void UnregisterWait(WaitableObject waitableObject) { s_lock.VerifyIsLocked(); Debug.Assert(waitableObject != null); WaitedListNode previous = _previous; WaitedListNode next = _next; if (previous != null) { previous._next = next; _previous = null; } else { Debug.Assert(waitableObject.WaitersHead == this); waitableObject.WaitersHead = next; } if (next != null) { next._previous = previous; _next = null; } else { Debug.Assert(waitableObject.WaitersTail == this); waitableObject.WaitersTail = previous; } } } private enum WaitSignalState : byte { Waiting, Waiting_Interruptible, NotWaiting, NotWaiting_SignaledToSatisfyWait, NotWaiting_SignaledToSatisfyWaitWithAbandonedMutex, NotWaiting_SignaledToAbortWaitDueToMaximumMutexReacquireCount, NotWaiting_SignaledToInterruptWait } } } }
using System; using System.Collections.Generic; using NUnit.Framework; namespace NServiceKit.Text.Tests.DynamicModels { /// <summary>A dynamic message.</summary> public class DynamicMessage : IMessageHeaders { /// <summary>Gets or sets the identifier.</summary> /// <value>The identifier.</value> public Guid Id { get; set; } /// <summary>Gets or sets the reply to.</summary> /// <value>The reply to.</value> public string ReplyTo { get; set; } /// <summary>Gets or sets the priority.</summary> /// <value>The priority.</value> public int Priority { get; set; } /// <summary>Gets or sets the retry attempts.</summary> /// <value>The retry attempts.</value> public int RetryAttempts { get; set; } /// <summary>Gets or sets the body.</summary> /// <value>The body.</value> public object Body { get; set; } /// <summary>Gets or sets the type.</summary> /// <value>The type.</value> public Type Type { get; set; } /// <summary>Gets the body.</summary> /// <returns>The body.</returns> public object GetBody() { //When deserialized this.Body is a string so use the serilaized //this.Type to deserialize it back into the original type return this.Body is string ? TypeSerializer.DeserializeFromString((string)this.Body, this.Type) : this.Body; } } /// <summary>A generic message.</summary> /// <typeparam name="T">Generic type parameter.</typeparam> public class GenericMessage<T> : IMessageHeaders { /// <summary>Gets or sets the identifier.</summary> /// <value>The identifier.</value> public Guid Id { get; set; } /// <summary>Gets or sets the reply to.</summary> /// <value>The reply to.</value> public string ReplyTo { get; set; } /// <summary>Gets or sets the priority.</summary> /// <value>The priority.</value> public int Priority { get; set; } /// <summary>Gets or sets the retry attempts.</summary> /// <value>The retry attempts.</value> public int RetryAttempts { get; set; } /// <summary>Gets or sets the body.</summary> /// <value>The body.</value> public T Body { get; set; } } /// <summary>A strict message.</summary> public class StrictMessage : IMessageHeaders { /// <summary>Gets or sets the identifier.</summary> /// <value>The identifier.</value> public Guid Id { get; set; } /// <summary>Gets or sets the reply to.</summary> /// <value>The reply to.</value> public string ReplyTo { get; set; } /// <summary>Gets or sets the priority.</summary> /// <value>The priority.</value> public int Priority { get; set; } /// <summary>Gets or sets the retry attempts.</summary> /// <value>The retry attempts.</value> public int RetryAttempts { get; set; } /// <summary>Gets or sets the body.</summary> /// <value>The body.</value> public MessageBody Body { get; set; } } /// <summary>A message body.</summary> public class MessageBody { /// <summary> /// Initializes a new instance of the NServiceKit.Text.Tests.DynamicModels.MessageBody class. /// </summary> public MessageBody() { this.Arguments = new List<string>(); } /// <summary>Gets or sets the action.</summary> /// <value>The action.</value> public string Action { get; set; } /// <summary>Gets or sets the arguments.</summary> /// <value>The arguments.</value> public List<string> Arguments { get; set; } } /// <summary>Interface for message headers.</summary> public interface IMessageHeaders { /// <summary>Gets or sets the identifier.</summary> /// <value>The identifier.</value> Guid Id { get; set; } /// <summary>Gets or sets the reply to.</summary> /// <value>The reply to.</value> string ReplyTo { get; set; } /// <summary>Gets or sets the priority.</summary> /// <value>The priority.</value> int Priority { get; set; } /// <summary>Gets or sets the retry attempts.</summary> /// <value>The retry attempts.</value> int RetryAttempts { get; set; } } /// <summary>A dynamic message tests.</summary> [TestFixture] public class DynamicMessageTests { /// <summary>Tests object set to object.</summary> [Test] public void Object_Set_To_Object_Test() { var original = new DynamicMessage { Id = Guid.NewGuid(), Priority = 3, ReplyTo = "http://path/to/reply.svc", RetryAttempts = 1, Type = typeof(MessageBody), Body = new Object() }; var jsv = TypeSerializer.SerializeToString(original); var json = JsonSerializer.SerializeToString(original); var jsvDynamicType = TypeSerializer.DeserializeFromString<DynamicMessage>(jsv); var jsonDynamicType = JsonSerializer.DeserializeFromString<DynamicMessage>(json); AssertHeadersAreEqual(jsvDynamicType, original); AssertHeadersAreEqual(jsonDynamicType, original); AssertHeadersAreEqual(jsvDynamicType, jsonDynamicType); } /// <summary>Can deserialize between dynamic generic and strict messages.</summary> [Test] public void Can_deserialize_between_dynamic_generic_and_strict_messages() { var original = new DynamicMessage { Id = Guid.NewGuid(), Priority = 3, ReplyTo = "http://path/to/reply.svc", RetryAttempts = 1, Type = typeof(MessageBody), Body = new MessageBody { Action = "Alphabet", Arguments = { "a", "b", "c" } } }; var jsv = TypeSerializer.SerializeToString(original); var dynamicType = TypeSerializer.DeserializeFromString<DynamicMessage>(jsv); var genericType = TypeSerializer.DeserializeFromString<GenericMessage<MessageBody>>(jsv); var strictType = TypeSerializer.DeserializeFromString<StrictMessage>(jsv); AssertHeadersAreEqual(dynamicType, original); AssertBodyIsEqual(dynamicType.GetBody(), (MessageBody)original.Body); AssertHeadersAreEqual(genericType, original); AssertBodyIsEqual(genericType.Body, (MessageBody)original.Body); AssertHeadersAreEqual(strictType, original); AssertBodyIsEqual(strictType.Body, (MessageBody)original.Body); //Debug purposes Console.WriteLine(strictType.Dump()); /* { Id: 891653ea2d0a4626ab0623fc2dc9dce1, ReplyTo: http://path/to/reply.svc, Priority: 3, RetryAttempts: 1, Body: { Action: Alphabet, Arguments: [ a, b, c ] } } */ } /// <summary>Assert headers are equal.</summary> /// <param name="actual"> The actual.</param> /// <param name="expected">The expected.</param> public void AssertHeadersAreEqual(IMessageHeaders actual, IMessageHeaders expected) { Assert.That(actual.Id, Is.EqualTo(expected.Id)); Assert.That(actual.ReplyTo, Is.EqualTo(expected.ReplyTo)); Assert.That(actual.Priority, Is.EqualTo(expected.Priority)); Assert.That(actual.RetryAttempts, Is.EqualTo(expected.RetryAttempts)); } /// <summary>Assert body is equal.</summary> /// <param name="actual"> The actual.</param> /// <param name="expected">The expected.</param> public void AssertBodyIsEqual(object actual, MessageBody expected) { var actualBody = actual as MessageBody; Assert.That(actualBody, Is.Not.Null); Assert.That(actualBody.Action, Is.EqualTo(expected.Action)); Assert.That(actualBody.Arguments, Is.EquivalentTo(expected.Arguments)); } } }
using System; using System.Collections; using OrbServerSDK; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using Server.Accounting; using Server; using Server.Network; using System.Threading; namespace Server.Engines.OrbRemoteServer { class OrbServer { private static readonly int SERVER_PORT = 2594; private static readonly AccessLevel REQUIRED_ACCESS_LEVEL = AccessLevel.GameMaster; private static readonly string SERVER_VERSION = ""; private static readonly string SERVER_NAME = "UO Architect Server for RunUO 2.0"; private static Hashtable m_Registry = System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable(0); private static Hashtable m_Clients = new Hashtable(); private static bool m_IsRunning = false; public static bool IsRunning { get{ return m_IsRunning; } } public static void Initialize() { } static OrbServer() { StartServer(); OrbConnection.OnLogin += new OrbConnection.LoginEvent(OnLogin); OrbConnection.OnExecuteCommand += new OrbConnection.ExecuteCommandEvent(OnExecuteCommand); OrbConnection.OnExecuteRequest += new OrbConnection.ExecuteRequestEvent(OnExecuteRequest); } private static void OnExecuteCommand(string alias, OrbClientInfo clientInfo, OrbCommandArgs args) { OrbClientState client = GetClientState(clientInfo); if(client == null) return; try { OrbCommand command = GetCommand(alias, client); if(command != null) { new CommandSyncTimer(client, command, args).Start(); } } catch(Exception e) { Console.WriteLine("Exception occurred for OrbServer command {0}\nMessage: {1}", alias, e.Message); } } private static OrbClientState GetClientState(OrbClientInfo clientInfo) { return (OrbClientState)m_Clients[clientInfo.ClientID]; } private static OrbResponse OnExecuteRequest(string alias, OrbClientInfo clientInfo, OrbRequestArgs args) { OrbClientState client = GetClientState(clientInfo); if(client == null) return null; OrbResponse response = null; try { OrbRequest request = GetRequest(alias, client); if(request != null) { ManualResetEvent reset = new ManualResetEvent(false); request.ResetEvent = reset; new RequestSyncTimer(client, request, args).Start(); reset.WaitOne(); response = request.Response; } } catch(Exception e) { Console.WriteLine("Exception occurred for OrbServer request {0}\nMessage: {1}", alias, e.Message); } return response; } private static OrbRequest GetRequest(string alias, OrbClientState client) { OrbRegistryEntry entry = (OrbRegistryEntry)m_Registry[alias]; OrbRequest request = null; if(entry != null) { if(CanConnectionAccess(client, entry)) { try { request = (OrbRequest)Activator.CreateInstance(entry.Type); } catch(Exception e) { Console.WriteLine("OrbServer Exception: " + e.Message); } } } return request; } private static OrbCommand GetCommand(string alias, OrbClientState client) { OrbRegistryEntry entry = (OrbRegistryEntry)m_Registry[alias]; OrbCommand command = null; if(entry != null) { if(CanConnectionAccess(client, entry)) { try { command = (OrbCommand)Activator.CreateInstance(entry.Type); } catch(Exception e) { Console.WriteLine("OrbServer Exception: " + e.Message); } } } return command; } private static bool CanConnectionAccess(OrbClientState client, OrbRegistryEntry entry) { bool authorized = false; if(entry.RequiresLogin) { if(client.OnlineMobile != null) { authorized = IsAccessAllowed(client.OnlineMobile, entry.RequiredLevel); } } else { authorized = IsAccessAllowed(client.Account, entry.RequiredLevel); } return authorized; } private static void StartServer() { // Run the OrbServer in a worked thread ThreadPool.QueueUserWorkItem(new WaitCallback(OrbServer.Run), null); } public static void Register(string alias, Type type, AccessLevel requiredLevel, bool requiresLogin) { if(!type.IsSubclassOf(typeof(OrbRequest)) && !type.IsSubclassOf(typeof(OrbCommand)) ) { Console.WriteLine("OrbRemoteServer Error: The type {0} isn't a subclass of the OrbCommand or OrbRequest classes.", type.FullName); } else if(m_Registry.ContainsKey(alias)) { Console.WriteLine("OrbRemoteServer Error: The type {0} has been assigned a duplicate alias.", type.FullName); } else { m_Registry.Add(alias, new OrbRegistryEntry(alias, type, requiredLevel, requiresLogin)); } } ////////////////////////////////////////////////////////////////////////////// // main method - this method registers the TCP/IP channel and the OrbConnection Type // for remote instanciation. public static void Run(object o) { try{ Console.WriteLine("\n{0} {1} is listening on port {2}", SERVER_NAME, SERVER_VERSION, SERVER_PORT); // Create Tcp channel using the selected Port number TcpChannel chan = new TcpChannel(SERVER_PORT); ChannelServices.RegisterChannel(chan); //register channel // register the remote object RemotingConfiguration.RegisterWellKnownServiceType( typeof(OrbConnection), "OrbConnection", WellKnownObjectMode.Singleton); while(true) { // Keep sleeping in order to keep this tread alive without hogging cpu cycles Thread.Sleep(30000); } }catch{} } // This function callback validates an account and returns true if it has access // rights to use this tool. private static LoginCodes OnLogin(OrbClientInfo clientInfo, string password) { LoginCodes code = LoginCodes.Success; //Console.WriteLine("OnValidateAccount"); IAccount account = Accounts.GetAccount(clientInfo.UserName); if(account == null || account.CheckPassword(password) == false) { code = LoginCodes.InvalidAccount; } else { if(!IsAccessAllowed(account, REQUIRED_ACCESS_LEVEL)) { Mobile player = GetOnlineMobile(account); if(player == null || !IsAccessAllowed(player, REQUIRED_ACCESS_LEVEL)) { // Neither the account or the char the account is logged in with has // the required accesslevel to make this connection. code = LoginCodes.NotAuthorized; } } Console.WriteLine("{0} connected to the Orb Script Server", account.Username); } if(code == LoginCodes.Success) { if(m_Clients.ContainsKey(clientInfo.ClientID)) m_Clients.Remove(clientInfo.ClientID); m_Clients.Add(clientInfo.ClientID, new OrbClientState(clientInfo, account, DateTime.Now)); } return code; } private static bool IsAccessAllowed(IAccount acct, AccessLevel accessLevel) { bool AccessAllowed = false; if(acct != null) { if((int)acct.AccessLevel >= (int)accessLevel) { AccessAllowed = true; } } return AccessAllowed; } private static bool IsAccessAllowed(Mobile mobile, AccessLevel accessLevel) { bool AccessAllowed = false; if(mobile != null) { if((int)mobile.AccessLevel >= (int)accessLevel) { AccessAllowed = true; } } return AccessAllowed; } // get logged in char for an account internal static Mobile GetOnlineMobile(IAccount acct) { if(acct == null) return null; Mobile mobile = null; // syncronize the account object to keep this access thread safe lock(acct) { for(int i=0; i < 5; ++i) { Mobile mob = acct[i]; if(mob == null) continue; if(mob.NetState != null) { mobile = mob; break; } } } return mobile; } // Stores info regarding the registered OrbCommand or OrbRequest class OrbRegistryEntry { public string Alias; public Type Type; public AccessLevel RequiredLevel; public bool RequiresLogin; public OrbRegistryEntry(string alias, Type type, AccessLevel requiredLevel, bool requiresLogin) { Alias = alias; Type = type; RequiredLevel = requiredLevel; RequiresLogin = requiresLogin; } public bool IsCommand { get{ return Type.IsSubclassOf(typeof(OrbCommand)); } } public bool IsRequest { get{ return Type.IsSubclassOf(typeof(OrbRequest)); } } } class RequestSyncTimer : Timer { private OrbClientState m_Client; private OrbRequest m_Request; private OrbRequestArgs m_Args; public RequestSyncTimer(OrbClientState client, OrbRequest request, OrbRequestArgs args) : base(TimeSpan.FromMilliseconds(20.0), TimeSpan.FromMilliseconds(20.0)) { m_Client = client; m_Request = request; m_Args = args; } protected override void OnTick() { if(m_Request != null) m_Request.OnRequest(m_Client, m_Args); Stop(); } } class CommandSyncTimer : Timer { private OrbClientState m_Client; private OrbCommand m_Command; private OrbCommandArgs m_Args; public CommandSyncTimer(OrbClientState client, OrbCommand command, OrbCommandArgs args) : base(TimeSpan.FromMilliseconds(20.0), TimeSpan.FromMilliseconds(20.0)) { m_Client = client; m_Command = command; m_Args = args; } protected override void OnTick() { if(m_Command != null) m_Command.OnCommand(m_Client, m_Args); Stop(); } } } internal class OrbClientState : OrbClientInfo { private IAccount m_Account = null; private DateTime m_LoginTime; internal OrbClientState(OrbClientInfo clientInfo, IAccount account, DateTime loginTime) : base(clientInfo.ClientID, clientInfo.UserName) { m_Account = account; m_LoginTime = loginTime; } internal IAccount Account { get{ return m_Account; } } internal Mobile OnlineMobile { get{ return OrbServer.GetOnlineMobile(m_Account); } } internal DateTime LoginTime { get{ return m_LoginTime; } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Avalonia.Input; namespace Avalonia.Gtk { public class GtkKeyboardDevice : KeyboardDevice { private static readonly Dictionary<Gdk.Key, Key> KeyDic = new Dictionary<Gdk.Key, Key> { { Gdk.Key.Cancel, Key.Cancel }, { Gdk.Key.BackSpace, Key.Back }, { Gdk.Key.Tab, Key.Tab }, { Gdk.Key.Linefeed, Key.LineFeed }, { Gdk.Key.Clear, Key.Clear }, { Gdk.Key.Return, Key.Return }, { Gdk.Key.Pause, Key.Pause }, //{ Gdk.Key.?, Key.CapsLock } //{ Gdk.Key.?, Key.HangulMode } //{ Gdk.Key.?, Key.JunjaMode } //{ Gdk.Key.?, Key.FinalMode } //{ Gdk.Key.?, Key.KanjiMode } { Gdk.Key.Escape, Key.Escape }, //{ Gdk.Key.?, Key.ImeConvert } //{ Gdk.Key.?, Key.ImeNonConvert } //{ Gdk.Key.?, Key.ImeAccept } //{ Gdk.Key.?, Key.ImeModeChange } { Gdk.Key.space, Key.Space }, { Gdk.Key.Prior, Key.Prior }, //{ Gdk.Key.?, Key.PageDown } { Gdk.Key.End, Key.End }, { Gdk.Key.Home, Key.Home }, { Gdk.Key.Left, Key.Left }, { Gdk.Key.Up, Key.Up }, { Gdk.Key.Right, Key.Right }, { Gdk.Key.Down, Key.Down }, { Gdk.Key.Select, Key.Select }, { Gdk.Key.Print, Key.Print }, { Gdk.Key.Execute, Key.Execute }, //{ Gdk.Key.?, Key.Snapshot } { Gdk.Key.Insert, Key.Insert }, { Gdk.Key.Delete, Key.Delete }, { Gdk.Key.Help, Key.Help }, //{ Gdk.Key.?, Key.D0 } //{ Gdk.Key.?, Key.D1 } //{ Gdk.Key.?, Key.D2 } //{ Gdk.Key.?, Key.D3 } //{ Gdk.Key.?, Key.D4 } //{ Gdk.Key.?, Key.D5 } //{ Gdk.Key.?, Key.D6 } //{ Gdk.Key.?, Key.D7 } //{ Gdk.Key.?, Key.D8 } //{ Gdk.Key.?, Key.D9 } { Gdk.Key.A, Key.A }, { Gdk.Key.B, Key.B }, { Gdk.Key.C, Key.C }, { Gdk.Key.D, Key.D }, { Gdk.Key.E, Key.E }, { Gdk.Key.F, Key.F }, { Gdk.Key.G, Key.G }, { Gdk.Key.H, Key.H }, { Gdk.Key.I, Key.I }, { Gdk.Key.J, Key.J }, { Gdk.Key.K, Key.K }, { Gdk.Key.L, Key.L }, { Gdk.Key.M, Key.M }, { Gdk.Key.N, Key.N }, { Gdk.Key.O, Key.O }, { Gdk.Key.P, Key.P }, { Gdk.Key.Q, Key.Q }, { Gdk.Key.R, Key.R }, { Gdk.Key.S, Key.S }, { Gdk.Key.T, Key.T }, { Gdk.Key.U, Key.U }, { Gdk.Key.V, Key.V }, { Gdk.Key.W, Key.W }, { Gdk.Key.X, Key.X }, { Gdk.Key.Y, Key.Y }, { Gdk.Key.Z, Key.Z }, { Gdk.Key.a, Key.A }, { Gdk.Key.b, Key.B }, { Gdk.Key.c, Key.C }, { Gdk.Key.d, Key.D }, { Gdk.Key.e, Key.E }, { Gdk.Key.f, Key.F }, { Gdk.Key.g, Key.G }, { Gdk.Key.h, Key.H }, { Gdk.Key.i, Key.I }, { Gdk.Key.j, Key.J }, { Gdk.Key.k, Key.K }, { Gdk.Key.l, Key.L }, { Gdk.Key.m, Key.M }, { Gdk.Key.n, Key.N }, { Gdk.Key.o, Key.O }, { Gdk.Key.p, Key.P }, { Gdk.Key.q, Key.Q }, { Gdk.Key.r, Key.R }, { Gdk.Key.s, Key.S }, { Gdk.Key.t, Key.T }, { Gdk.Key.u, Key.U }, { Gdk.Key.v, Key.V }, { Gdk.Key.w, Key.W }, { Gdk.Key.x, Key.X }, { Gdk.Key.y, Key.Y }, { Gdk.Key.z, Key.Z }, //{ Gdk.Key.?, Key.LWin } //{ Gdk.Key.?, Key.RWin } //{ Gdk.Key.?, Key.Apps } //{ Gdk.Key.?, Key.Sleep } //{ Gdk.Key.?, Key.NumPad0 } //{ Gdk.Key.?, Key.NumPad1 } //{ Gdk.Key.?, Key.NumPad2 } //{ Gdk.Key.?, Key.NumPad3 } //{ Gdk.Key.?, Key.NumPad4 } //{ Gdk.Key.?, Key.NumPad5 } //{ Gdk.Key.?, Key.NumPad6 } //{ Gdk.Key.?, Key.NumPad7 } //{ Gdk.Key.?, Key.NumPad8 } //{ Gdk.Key.?, Key.NumPad9 } { Gdk.Key.multiply, Key.Multiply }, //{ Gdk.Key.?, Key.Add } //{ Gdk.Key.?, Key.Separator } //{ Gdk.Key.?, Key.Subtract } //{ Gdk.Key.?, Key.Decimal } //{ Gdk.Key.?, Key.Divide } { Gdk.Key.F1, Key.F1 }, { Gdk.Key.F2, Key.F2 }, { Gdk.Key.F3, Key.F3 }, { Gdk.Key.F4, Key.F4 }, { Gdk.Key.F5, Key.F5 }, { Gdk.Key.F6, Key.F6 }, { Gdk.Key.F7, Key.F7 }, { Gdk.Key.F8, Key.F8 }, { Gdk.Key.F9, Key.F9 }, { Gdk.Key.F10, Key.F10 }, { Gdk.Key.F11, Key.F11 }, { Gdk.Key.F12, Key.F12 }, { Gdk.Key.L3, Key.F13 }, { Gdk.Key.F14, Key.F14 }, { Gdk.Key.L5, Key.F15 }, { Gdk.Key.F16, Key.F16 }, { Gdk.Key.F17, Key.F17 }, { Gdk.Key.L8, Key.F18 }, { Gdk.Key.L9, Key.F19 }, { Gdk.Key.L10, Key.F20 }, { Gdk.Key.R1, Key.F21 }, { Gdk.Key.R2, Key.F22 }, { Gdk.Key.F23, Key.F23 }, { Gdk.Key.R4, Key.F24 }, //{ Gdk.Key.?, Key.NumLock } //{ Gdk.Key.?, Key.Scroll } //{ Gdk.Key.?, Key.LeftShift } //{ Gdk.Key.?, Key.RightShift } //{ Gdk.Key.?, Key.LeftCtrl } //{ Gdk.Key.?, Key.RightCtrl } //{ Gdk.Key.?, Key.LeftAlt } //{ Gdk.Key.?, Key.RightAlt } //{ Gdk.Key.?, Key.BrowserBack } //{ Gdk.Key.?, Key.BrowserForward } //{ Gdk.Key.?, Key.BrowserRefresh } //{ Gdk.Key.?, Key.BrowserStop } //{ Gdk.Key.?, Key.BrowserSearch } //{ Gdk.Key.?, Key.BrowserFavorites } //{ Gdk.Key.?, Key.BrowserHome } //{ Gdk.Key.?, Key.VolumeMute } //{ Gdk.Key.?, Key.VolumeDown } //{ Gdk.Key.?, Key.VolumeUp } //{ Gdk.Key.?, Key.MediaNextTrack } //{ Gdk.Key.?, Key.MediaPreviousTrack } //{ Gdk.Key.?, Key.MediaStop } //{ Gdk.Key.?, Key.MediaPlayPause } //{ Gdk.Key.?, Key.LaunchMail } //{ Gdk.Key.?, Key.SelectMedia } //{ Gdk.Key.?, Key.LaunchApplication1 } //{ Gdk.Key.?, Key.LaunchApplication2 } //{ Gdk.Key.?, Key.OemSemicolon } //{ Gdk.Key.?, Key.OemPlus } //{ Gdk.Key.?, Key.OemComma } //{ Gdk.Key.?, Key.OemMinus } //{ Gdk.Key.?, Key.OemPeriod } //{ Gdk.Key.?, Key.Oem2 } //{ Gdk.Key.?, Key.OemTilde } //{ Gdk.Key.?, Key.AbntC1 } //{ Gdk.Key.?, Key.AbntC2 } //{ Gdk.Key.?, Key.Oem4 } //{ Gdk.Key.?, Key.OemPipe } //{ Gdk.Key.?, Key.OemCloseBrackets } //{ Gdk.Key.?, Key.Oem7 } //{ Gdk.Key.?, Key.Oem8 } //{ Gdk.Key.?, Key.Oem102 } //{ Gdk.Key.?, Key.ImeProcessed } //{ Gdk.Key.?, Key.System } //{ Gdk.Key.?, Key.OemAttn } //{ Gdk.Key.?, Key.OemFinish } //{ Gdk.Key.?, Key.DbeHiragana } //{ Gdk.Key.?, Key.OemAuto } //{ Gdk.Key.?, Key.DbeDbcsChar } //{ Gdk.Key.?, Key.OemBackTab } //{ Gdk.Key.?, Key.Attn } //{ Gdk.Key.?, Key.DbeEnterWordRegisterMode } //{ Gdk.Key.?, Key.DbeEnterImeConfigureMode } //{ Gdk.Key.?, Key.EraseEof } //{ Gdk.Key.?, Key.Play } //{ Gdk.Key.?, Key.Zoom } //{ Gdk.Key.?, Key.NoName } //{ Gdk.Key.?, Key.DbeEnterDialogConversionMode } //{ Gdk.Key.?, Key.OemClear } //{ Gdk.Key.?, Key.DeadCharProcessed } }; public new static GtkKeyboardDevice Instance { get; } = new GtkKeyboardDevice(); public static Key ConvertKey(Gdk.Key key) { Key result; return KeyDic.TryGetValue(key, out result) ? result : Key.None; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Runtime.Serialization; using System.Runtime.CompilerServices; namespace HTLib2 { [Serializable] public partial class Vector : IVector<double>, ICloneable, IBinarySerializable { public double[] _data; public Vector(int size) { HDebug.Assert(size >= 0); this._data = new double[size]; } public Vector(int size, double initval) { HDebug.Assert(size >= 0); this._data = new double[size]; if(initval != 0) { for(int i=0; i<size; i++) _data[i] = initval; } } //static char[] separator { get { return " ,\t".ToCharArray(); } } //public Vector(string vec) //{ // try // { // string[] data = vec.Split(separator, StringSplitOptions.RemoveEmptyEntries); // _data = new double[data.Length]; // for(int i=0; i<data.Length; i++) // _data[i] = double.Parse(data[i]); // } // catch(Exception) // { // Debug.Break(); // _data = null; // } //} public Vector(Vector vec) { this._data = new double[vec.Size]; for(int i=0; i<Size; i++) _data[i] = vec._data[i]; } public Vector(params double[] data) { this._data = data; } public Vector(params double[][] valuess) { _data = new double[valuess.HCount().Sum()]; int i=0; foreach(double[] values in valuess) foreach(double value in values) { this[i] = value; i++; } } //public Vector(int size, params double[] data) //{ // Debug.Assert(false); // Debug.Assert(size >= 0); // this._data = new double[size]; // for(int i=0; i<data.Length; i++) // this[i] = data[i]; //} public long SizeLong { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _data.Length; } } public int Size { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _data.Length; } } public double this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { HDebug.Assert(i >= 0 && i < Size); return _data[i]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { HDebug.Assert(i >= 0 && i < Size); _data[i] = value; } } public double this[long i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { HDebug.Assert(i >= 0 && i < Size); return _data[i]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { HDebug.Assert(i >= 0 && i < Size); _data[i] = value; } } public bool IsNaN { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { for(int i=0; i<Size; i++) if(double.IsNaN (this[i])) return true; return false; } } public bool IsInfinity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { for(int i=0; i<Size; i++) if(double.IsInfinity (this[i])) return true; return false; } } public bool IsPositiveInfinity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { for(int i=0; i<Size; i++) if(double.IsPositiveInfinity(this[i])) return true; return false; } } public bool IsNegativeInfinity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { for(int i=0; i<Size; i++) if(double.IsNegativeInfinity(this[i])) return true; return false; } } public bool IsComputable { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ((IsNaN == false) && (IsInfinity == false)); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetZero() { for(int i=0; i<Size; i++) this[i] = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetOne () { for(int i=0; i<Size; i++) this[i] = 1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetValue(double value) { for(int i=0; i<Size; i++) this[i] = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Zeros(int size) { return new Vector(size, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Ones (int size) { return new Vector(size, 1); } //////////////////////////////////////////////////////////////////////////////////// // ToMatrix public static implicit operator double[](Vector vec) { return vec._data; } public static implicit operator Vector(double[] vec) { return new Vector(vec); } public static explicit operator MatrixByArr(Vector vec) { return vec.ToColMatrix(); } static bool operator_Equal_SelfTest = HDebug.IsDebuggerAttached; public static bool operator==(Vector lvec, Vector rvec) { if(operator_Equal_SelfTest) #region self test { operator_Equal_SelfTest = false; Vector v0 = new double[] { 1, 2, 3, 4 }; Vector v1 = new double[] { 1, 2, 3, 4 }; Vector v2 = new double[] { 0, 2, 3, 4 }; Vector v3 = new double[] { 1, 2, 3 }; bool valid = true; if((v0 == v1) == false) valid = false; if((v0 != v2) == false) valid = false; if((v0 != v3) == false) valid = false; HDebug.Assert(valid); }; #endregion object lobj = lvec; object robj = rvec; if(object.ReferenceEquals(lvec, rvec)) return true; if((lobj != null && robj == null) || (lobj == null && robj != null)) return false; if(lvec._data == rvec._data) return true; if(lvec._data==null ||rvec._data==null) return false; if(lvec.Size != rvec.Size) return false; for(int i=0; i<lvec.Size; i++) if(lvec[i] != rvec[i]) return false; return true; } public static bool operator!=(Vector lvec, Vector rvec) { return !(lvec == rvec); } public static Vector operator+(Vector l, Vector r) { HDebug.Assert(l.Size == r.Size); int size = l.Size; Vector result = new Vector(size); for(int i=0; i<size; i++) result[i] = l[i] + r[i]; return result; } public static Vector operator-(Vector l, Vector r) { return Sub(l._data, r._data); } public static Vector Sub(double[] l, double[] r) { HDebug.Assert(l.Length == r.Length); int size = l.Length; Vector result = new Vector(size); for(int i=0; i<size; i++) result[i] = l[i] - r[i]; return result; } public static Vector operator -(Vector v) { int size = v.Size; Vector result = new Vector(size); for(int i=0; i<size; i++) result[i] = -1 * v[i]; return result; } public static Vector operator*(double l, Vector r) { int size = r.Size; Vector result = new Vector(size); for(int i=0; i<size; i++) result[i] = l * r[i]; return result; } public static Vector operator*(Vector l, double r) { return r*l; } public static Vector operator/(Vector l, double r) { int size = l.Size; Vector result = new Vector(size); for(int i=0; i<size; i++) result[i] = l[i] / r; return result; } public static bool IsNull(Vector vec) { return (vec._data == null); } public double Sum() { double sum = 0; for(int i=0; i<Size; i++) sum += this[i]; return sum; } public double SumSquared() { double sum = 0; for(int i=0; i<Size; i++) sum += (this[i] * this[i]); return sum; } //////////////////////////////////////////////////////////////////////////////////// // Functions public double Dist2 { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] get { double result = 0; for(int i=0; i<Size; i++) result += this[i] * this[i]; //HDebug.Assert(double.IsNaN(result) == false, double.IsInfinity(result) == false); return result; } } public double Dist { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] get { double dist = Math.Sqrt(Dist2); return dist; } } public Vector UnitVector() { double length = 1.0 / Math.Sqrt(_VtV(this, this)); return this * length; } public static void UnitVector(Vector vec) { double length = 1.0 / Math.Sqrt(_VtV(vec, vec)); for(int i=0; i<vec.Size; i++) vec[i] *= length; } public static void AddTo(IList<Vector> dest, IList<Vector> add) { HDebug.Assert(dest.Count == add.Count); for(int i=0; i<dest.Count; i++) dest[i] += add[i]; } //////////////////////////////////////////////////////////////////////////////////// // for Collection public static Vector Average(IList<Vector> list) { if(list.Count <= 0) return null; Vector avg = list[0]; for(int i=1; i<list.Count; i++) { if(list[i].Size != avg.Size) return null; avg += list[i]; } avg /= list.Count; return avg; } //////////////////////////////////////////////////////////////////////////////////// // ToArray public double[] ToArray() { return _data; } //////////////////////////////////////////////////////////////////////////////////// // ToString public override string ToString() { StringBuilder str = new StringBuilder(); str.Append("Vector ["+Size+"] "); str.Append(HToString("0.00000", null, "{", "}", ", ")); return str.ToString(); } public string ToString(string format) { StringBuilder str = new StringBuilder(); str.Append("Vector ["+Size+"] "); str.Append(HToString(format, null, "{", "}", ", ")); return str.ToString(); } public string HToString(string format="0.00000" , IFormatProvider formatProvider=null , string begindelim = "{" , string enddelim = "}" , string delim = ", " ) { StringBuilder sb = new StringBuilder(); HStatic.HToString ( this, sb , format, formatProvider, begindelim, enddelim, delim ); return sb.ToString(); } //////////////////////////////////////////////////////////////////////////////////// // IBinarySerializable public void BinarySerialize(HBinaryWriter writer) { writer.Write(_data); } public Vector(HBinaryReader reader) { reader.Read(out _data); } // IBinarySerializable //////////////////////////////////////////////////////////////////////////////////// // Serializable public Vector(SerializationInfo info, StreamingContext ctxt) { this._data = (double[])info.GetValue("data", typeof(double[])); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("data", this._data); } //////////////////////////////////////////////////////////////////////////////////// // ICloneable object ICloneable.Clone() { return Clone(); } public Vector Clone() { double[] data = null; if(_data != null) data = (double[])_data.Clone(); return new Vector(data); } //////////////////////////////////////////////////////////////////////////////////// // Object override public int GetHashCode() { return _data.GetHashCode(); } public override bool Equals(object obj) { if(typeof(Vector).IsInstanceOfType(obj) == false) return false; return (this == ((Vector)obj)); } static double _VtV(Vector l, Vector r) { // same to LinAlg.VtV HDebug.Assert(l.Size == r.Size); int size = l.Size; double result = 0; for(int i = 0; i < size; i++) result += l[i] * r[i]; return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Tools.ServiceModel.SvcUtil { using System; using System.ServiceModel.Channels; using System.Configuration; using System.Collections.Generic; using System.IO; using System.Reflection; using System.ServiceModel; internal partial class Options { private ToolMode? _defaultMode; private ToolMode _validModes = ToolMode.Any; private string _modeSettingOption; private string _modeSettingValue; private string _targetValue; private string _outputFileArg; private string _directoryArg; private string _configFileArg; private SerializerMode _serializer; private bool _asyncMethods; private bool _internalTypes; private bool _serializableAttribute; private bool _importXmlTypes; private bool _typedMessages; private bool _noLogo; private bool _noConfig; private bool _mergeConfig; private bool _dataContractOnly; private bool _enableDataBinding; private string _serviceName; private List<string> _inputParameters; private List<Type> _referencedTypes; private List<Assembly> _referencedAssemblies; private List<Type> _referencedCollectionTypes; private Dictionary<string, Type> _excludedTypes; private bool _nostdlib; private Dictionary<string, string> _namespaceMappings; private TypeResolver _typeResolver; private TargetClientVersionMode _targetClientVersion; private bool _useSerializerForFaults; private bool _wrapped; private bool _serviceContractGeneration; private bool _syncMethodOnly; internal string OutputFileArg { get { return _outputFileArg; } } internal string DirectoryArg { get { return _directoryArg; } } internal string ConfigFileArg { get { return _configFileArg; } } internal bool AsyncMethods { get { return _asyncMethods; } } internal bool InternalTypes { get { return _internalTypes; } } internal bool SerializableAttribute { get { return _serializableAttribute; } } internal SerializerMode Serializer { get { return _serializer; } } internal bool ImportXmlTypes { get { return _importXmlTypes; } } internal bool TypedMessages { get { return _typedMessages; } } internal bool NoLogo { get { return _noLogo; } } internal bool NoConfig { get { return _noConfig || _dataContractOnly; } } internal bool MergeConfig { get { return _mergeConfig; } } internal string ServiceName { get { return _serviceName; } } internal bool EnableDataBinding { get { return _enableDataBinding; } } internal List<string> InputParameters { get { return _inputParameters; } } internal List<Type> ReferencedTypes { get { return _referencedTypes; } } internal List<Assembly> ReferencedAssemblies { get { return _referencedAssemblies; } } internal List<Type> ReferencedCollectionTypes { get { return _referencedCollectionTypes; } } internal bool Nostdlib { get { return _nostdlib; } } internal Dictionary<string, string> NamespaceMappings { get { return _namespaceMappings; } } internal TypeResolver TypeResolver { get { return _typeResolver; } } internal string ModeSettingOption { get { return _modeSettingOption; } } internal string ModeSettingValue { get { return _modeSettingValue; } } internal TargetClientVersionMode TargetClientVersion { get { return _targetClientVersion; } } internal bool UseSerializerForFaults { get { return _useSerializerForFaults; } } internal bool Wrapped { get { return _wrapped; } } internal bool ServiceContractGeneration { get { return _serviceContractGeneration; } } internal bool SyncMethodOnly { get { return _syncMethodOnly; } } private Options(ArgumentDictionary arguments) { OptionProcessingHelper optionProcessor = new OptionProcessingHelper(this, arguments); optionProcessor.ProcessArguments(); } internal static Options ParseArguments(string[] args) { ArgumentDictionary arguments; try { arguments = CommandParser.ParseCommand(args, Options.Switches.All); } catch (ArgumentException ae) { throw new ToolOptionException(ae.Message); } return new Options(arguments); } internal void SetAllowedModes(ToolMode newDefaultMode, ToolMode validModes, string option, string value) { Tool.Assert(validModes != ToolMode.None, "validModes should never be set to None!"); Tool.Assert(newDefaultMode != ToolMode.None, "newDefaultMode should never be set to None!"); Tool.Assert((validModes & newDefaultMode) != ToolMode.None, "newDefaultMode must be a validMode!"); Tool.Assert(IsSingleBit(newDefaultMode), "newDefaultMode must Always represent a single mode!"); //update/filter list of valid modes _validModes &= validModes; if (_validModes == ToolMode.None) throw new InvalidToolModeException(); bool currentDefaultIsValid = (_defaultMode.HasValue && (_defaultMode & _validModes) != ToolMode.None); bool newDefaultIsValid = (newDefaultMode & _validModes) != ToolMode.None; if (!currentDefaultIsValid) { if (newDefaultIsValid) _defaultMode = newDefaultMode; else _defaultMode = null; } //If this is true, then this is an explicit mode setting if (IsSingleBit(validModes)) { _modeSettingOption = option; _modeSettingValue = value; } } internal ToolMode? GetToolMode() { if (IsSingleBit(_validModes)) return _validModes; return _defaultMode; } internal string GetCommandLineString(string option, string value) { return (value == null) ? option : option + ":" + value; } private static bool IsSingleBit(ToolMode mode) { //figures out if the mode has a single bit set ( is a power of 2) int x = (int)mode; return (x != 0) && ((x & (x + ~0)) == 0); } internal bool IsTypeExcluded(Type type) { return OptionProcessingHelper.IsTypeSpecified(type, _excludedTypes, Options.Cmd.ExcludeType); } private class OptionProcessingHelper { private Options _parent; private ArgumentDictionary _arguments; private static Type s_typeOfDateTimeOffset = typeof(DateTimeOffset); internal OptionProcessingHelper(Options options, ArgumentDictionary arguments) { _parent = options; _arguments = arguments; } internal void ProcessArguments() { CheckForBasicOptions(); if (CheckForHelpOption()) return; //We're Checking these values first because they are explicit statements about tool mode. CheckForTargetOrValidateOptions(); ProcessDirectoryOption(); ProcessOutputOption(); ProcessServiceNameOption(); ReadInputArguments(); ParseMiscCodeGenOptions(); ParseConfigOption(); ParseNamespaceMappings(); ParseReferenceAssemblies(); } private void ParseServiceContractOption() { _parent._serviceContractGeneration = _arguments.ContainsArgument(Options.Cmd.ServiceContract); if (_parent._serviceContractGeneration) { SetAllowedModesFromOption(ToolMode.ServiceContractGeneration, ToolMode.ServiceContractGeneration, Options.Cmd.ServiceContract, null); } } private bool CheckForHelpOption() { if (_arguments.ContainsArgument(Options.Cmd.Help) || _arguments.Count == 0) { _parent.SetAllowedModes(ToolMode.DisplayHelp, ToolMode.DisplayHelp, Options.Cmd.Help, null); return true; } return false; } private void CheckForTargetOrValidateOptions() { if (_arguments.ContainsArgument(Options.Cmd.Target)) { ParseTargetOption(_arguments.GetArgument(Options.Cmd.Target)); } if (_arguments.ContainsArgument(Options.Cmd.Validate)) { try { _parent.SetAllowedModes(ToolMode.Validate, ToolMode.Validate, Options.Cmd.Validate, null); } catch (InvalidToolModeException) { throw new ToolOptionException(SR.Format(SR.ErrValidateInvalidUse, Options.Cmd.Validate, Options.Cmd.Target)); } if (!_arguments.ContainsArgument(Options.Cmd.ServiceName)) { throw new ToolOptionException(SR.Format(SR.ErrValidateRequiresServiceName, Options.Cmd.ServiceName)); } } } private void ParseTargetOption(string targetValue) { try { if (String.Equals(targetValue, Options.Targets.Metadata, StringComparison.OrdinalIgnoreCase)) { _parent.SetAllowedModes(ToolMode.MetadataFromAssembly, ToolMode.MetadataFromAssembly | ToolMode.DataContractExport | ToolMode.WSMetadataExchange, Options.Cmd.Target, targetValue); } else if (String.Equals(targetValue, Options.Targets.Code, StringComparison.OrdinalIgnoreCase)) { _parent.SetAllowedModes(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration | ToolMode.DataContractImport | ToolMode.ServiceContractGeneration, Options.Cmd.Target, targetValue); } else if (String.Equals(targetValue, Options.Targets.XmlSerializer, StringComparison.OrdinalIgnoreCase)) { _parent.SetAllowedModes(ToolMode.XmlSerializerGeneration, ToolMode.XmlSerializerGeneration, Options.Cmd.Target, targetValue); } else { throw new ToolOptionException(SR.Format(SR.ErrInvalidTarget, Options.Cmd.Target, targetValue, Options.Targets.SupportedTargets)); } _parent._targetValue = targetValue; } catch (InvalidToolModeException) { Tool.Assert(true, "This should have been the first check and shouldn't ever be called"); } } private void CheckForBasicOptions() { _parent._noLogo = _arguments.ContainsArgument(Options.Cmd.NoLogo); #if DEBUG ToolConsole.SetOptions(_arguments.ContainsArgument(Options.Cmd.Debug)); #endif } private void ProcessDirectoryOption() { // Directory //--------------------------------------------------------------------------------------------------------- if (_arguments.ContainsArgument(Options.Cmd.Directory)) { string directoryArgValue = _arguments.GetArgument(Options.Cmd.Directory); try { ValidateIsDirectoryPathOnly(Options.Cmd.Directory, directoryArgValue); if (!directoryArgValue.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) directoryArgValue += Path.DirectorySeparatorChar; _parent._directoryArg = Path.GetFullPath(directoryArgValue); } catch (ToolOptionException) { throw; } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Tool.IsFatal(e)) throw; throw new ToolArgumentException(SR.Format(SR.ErrInvalidPath, directoryArgValue, Options.Cmd.Directory), e); } } else { _parent._directoryArg = null; } } private static void ValidateIsDirectoryPathOnly(string arg, string value) { ValidatePath(arg, value); FileInfo fileInfo = new FileInfo(value); if (fileInfo.Exists) throw new ToolOptionException(SR.Format(SR.ErrDirectoryPointsToAFile, arg, value)); } private static void ValidatePath(string arg, string value) { int invalidCharacterIndex = value.IndexOfAny(Path.GetInvalidPathChars()); if (invalidCharacterIndex != -1) { string invalidCharacter = value[invalidCharacterIndex].ToString(); throw new ToolOptionException(SR.Format(SR.ErrDirectoryContainsInvalidCharacters, arg, value, invalidCharacter)); } } private void ProcessOutputOption() { if (_arguments.ContainsArgument(Options.Cmd.Out)) { _parent._outputFileArg = _arguments.GetArgument(Options.Cmd.Out); if (_parent._outputFileArg != string.Empty) { SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration | ToolMode.DataContractImport | ToolMode.XmlSerializerGeneration | ToolMode.ServiceContractGeneration, Options.Cmd.Out, ""); ValidatePath(Options.Cmd.Out, _parent._outputFileArg); } } else { _parent._outputFileArg = null; } } private void ProcessServiceNameOption() { if (_arguments.ContainsArgument(Options.Cmd.ServiceName)) { _parent._serviceName = _arguments.GetArgument(Options.Cmd.ServiceName); if (_parent._serviceName != string.Empty) { SetAllowedModesFromOption(ToolMode.MetadataFromAssembly, ToolMode.MetadataFromAssembly | ToolMode.Validate, Options.Cmd.ServiceName, ""); } } else { _parent._serviceName = null; } } private void ReadInputArguments() { _parent._inputParameters = new List<string>(_arguments.GetArguments(String.Empty)); } private void ParseMiscCodeGenOptions() { ParseSerializerOption(); ParseDCOnly(); ParseServiceContractOption(); ParseTargetClientVersionOption(); _parent._wrapped = _arguments.ContainsArgument(Options.Cmd.Wrapped); if (_parent._wrapped) SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration | ToolMode.DataContractImport | ToolMode.ServiceContractGeneration, Options.Cmd.Wrapped, null); _parent._useSerializerForFaults = _arguments.ContainsArgument(Options.Cmd.UseSerializerForFaults); if (_parent._useSerializerForFaults) SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration | ToolMode.DataContractImport | ToolMode.ServiceContractGeneration, Options.Cmd.UseSerializerForFaults, null); _parent._importXmlTypes = _arguments.ContainsArgument(Options.Cmd.ImportXmlTypes); if (_parent._importXmlTypes) SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration | ToolMode.DataContractImport | ToolMode.ServiceContractGeneration, Options.Cmd.ImportXmlTypes, null); _parent._noConfig = _arguments.ContainsArgument(Options.Cmd.NoConfig); if (_parent._noConfig) SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration, Options.Cmd.NoConfig, null); _parent._internalTypes = _arguments.ContainsArgument(Options.Cmd.Internal); if (_parent._internalTypes) SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration | ToolMode.DataContractImport | ToolMode.ServiceContractGeneration, Options.Cmd.Internal, null); _parent._serializableAttribute = _arguments.ContainsArgument(Options.Cmd.Serializable); if (_parent._serializableAttribute) SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration | ToolMode.DataContractImport | ToolMode.ServiceContractGeneration, Options.Cmd.Serializable, null); _parent._typedMessages = _arguments.ContainsArgument(Options.Cmd.MessageContract); if (_parent._typedMessages) SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration | ToolMode.ServiceContractGeneration, Options.Cmd.MessageContract, null); _parent._enableDataBinding = _arguments.ContainsArgument(Options.Cmd.EnableDataBinding); if (_parent._enableDataBinding) SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration | ToolMode.DataContractImport | ToolMode.ServiceContractGeneration, Options.Cmd.EnableDataBinding, null); _parent._asyncMethods = _arguments.ContainsArgument(Options.Cmd.Async); if (_parent._asyncMethods) SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration | ToolMode.ServiceContractGeneration, Options.Cmd.Async, null); _parent._syncMethodOnly = _arguments.ContainsArgument(Options.Cmd.SyncOnly); if (_parent._syncMethodOnly) { if (_parent._asyncMethods) { throw new ToolOptionException(SR.Format(SR.ErrExclusiveOptionsSpecified, Options.Cmd.SyncOnly, Options.Cmd.Async)); } else { SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration | ToolMode.ServiceContractGeneration, Options.Cmd.SyncOnly, null); } } } private void ParseDCOnly() { _parent._dataContractOnly = _arguments.ContainsArgument(Options.Cmd.DataContractOnly); if (_parent._dataContractOnly) SetAllowedModesFromOption(ToolMode.DataContractImport, ToolMode.DataContractImport | ToolMode.DataContractExport, Options.Cmd.DataContractOnly, null); } private void ParseSerializerOption() { if (_arguments.ContainsArgument(Options.Cmd.Serializer)) { string serializerValue = _arguments.GetArgument(Options.Cmd.Serializer); try { _parent._serializer = (SerializerMode)Enum.Parse(typeof(SerializerMode), serializerValue, true); } catch (ArgumentException) { throw new ToolOptionException(SR.Format(SR.ErrInvalidSerializer, Options.Cmd.Serializer, serializerValue, Options.s_supportedSerializers)); } SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration | ToolMode.DataContractImport | ToolMode.ServiceContractGeneration, Options.Cmd.Serializer, null); } else { _parent._serializer = SerializerMode.Default; } } private void ParseTargetClientVersionOption() { if (_arguments.ContainsArgument(Options.Cmd.TargetClientVersion)) { string targetClientVersionValue = _arguments.GetArgument(Options.Cmd.TargetClientVersion); try { _parent._targetClientVersion = (TargetClientVersionMode)Enum.Parse(typeof(TargetClientVersionMode), targetClientVersionValue, true); } catch (ArgumentException) { throw new ToolOptionException(SR.Format(SR.ErrInvalidTargetClientVersion, Options.Cmd.TargetClientVersion, targetClientVersionValue, Options.s_supportedTargetClientVersions)); } SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration | ToolMode.DataContractImport | ToolMode.ServiceContractGeneration, Options.Cmd.TargetClientVersion, null); } else { _parent._targetClientVersion = TargetClientVersionMode.Version30; } } private void ParseConfigOption() { // Parse config //----------------------------------------------------------------------------------------------------- if (_arguments.ContainsArgument(Options.Cmd.Config)) { if (_parent._noConfig) throw new ToolOptionException(SR.Format(SR.ErrExclusiveOptionsSpecified, Options.Cmd.NoConfig, Options.Cmd.Config)); SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.ProxyGeneration, Options.Cmd.Config, null); _parent._configFileArg = _arguments.GetArgument(Options.Cmd.Config); if (_arguments.ContainsArgument(Options.Cmd.MergeConfig)) _parent._mergeConfig = true; else _parent._mergeConfig = false; if (_parent._configFileArg != null) ValidatePath(Options.Cmd.Config, _parent._configFileArg); } else { if (_arguments.ContainsArgument(Options.Cmd.MergeConfig)) throw new ToolOptionException(SR.Format(SR.ErrMergeConfigUsedWithoutConfig, Options.Cmd.MergeConfig, Options.Cmd.Config)); _parent._configFileArg = null; _parent._mergeConfig = false; } } private void ParseNamespaceMappings() { IList<string> namespaceMappingsArgs = _arguments.GetArguments(Options.Cmd.Namespace); _parent._namespaceMappings = new Dictionary<string, string>(namespaceMappingsArgs.Count); foreach (string namespaceMapping in namespaceMappingsArgs) { string[] parts = namespaceMapping.Split(','); if (parts == null || parts.Length != 2) throw new ToolOptionException(SR.Format(SR.ErrInvalidNamespaceArgument, Options.Cmd.Namespace, namespaceMapping)); string targetNamespace = parts[0].Trim(); string clrNamespace = parts[1].Trim(); if (_parent._namespaceMappings.ContainsKey(targetNamespace)) { string prevClrNamespace = _parent._namespaceMappings[targetNamespace]; if (prevClrNamespace != clrNamespace) throw new ToolOptionException(SR.Format(SR.ErrCannotSpecifyMultipleMappingsForNamespace, Options.Cmd.Namespace, targetNamespace, prevClrNamespace, clrNamespace)); } else { _parent._namespaceMappings.Add(targetNamespace, clrNamespace); } } } private void ParseReferenceAssemblies() { IList<string> referencedAssembliesArgs = _arguments.GetArguments(Options.Cmd.Reference); IList<string> excludeTypesArgs = _arguments.GetArguments(Options.Cmd.ExcludeType); IList<string> referencedCollectionTypesArgs = _arguments.GetArguments(Options.Cmd.CollectionType); bool nostdlib = _arguments.ContainsArgument(Options.Cmd.Nostdlib); if (excludeTypesArgs != null && excludeTypesArgs.Count > 0) SetAllowedModesFromOption(ToolMode.ProxyGeneration, ToolMode.MetadataFromAssembly | ToolMode.ProxyGeneration | ToolMode.DataContractImport | ToolMode.XmlSerializerGeneration | ToolMode.ServiceContractGeneration, Options.Cmd.ExcludeType, null); AddReferencedTypes(referencedAssembliesArgs, excludeTypesArgs, referencedCollectionTypesArgs, nostdlib); _parent._typeResolver = CreateTypeResolver(_parent); } private void SetAllowedModesFromOption(ToolMode newDefaultMode, ToolMode allowedModes, string option, string value) { try { _parent.SetAllowedModes(newDefaultMode, allowedModes, option, value); } catch (InvalidToolModeException) { string optionStr = _parent.GetCommandLineString(option, value); if (_parent._modeSettingOption != null) { if (_parent._modeSettingOption == Options.Cmd.Target) { throw new ToolOptionException(SR.Format(SR.ErrOptionConflictsWithTarget, Options.Cmd.Target, _parent.ModeSettingValue, optionStr)); } else { string modeSettingStr = _parent.GetCommandLineString(_parent._modeSettingOption, _parent._modeSettingValue); throw new ToolOptionException(SR.Format(SR.ErrOptionModeConflict, optionStr, modeSettingStr)); } } else { throw new ToolOptionException(SR.Format(SR.ErrAmbiguousOptionModeConflict, optionStr)); } } } private void AddReferencedTypes(IList<string> referenceArgs, IList<string> excludedTypeArgs, IList<string> collectionTypesArgs, bool nostdlib) { _parent._referencedTypes = new List<Type>(); _parent._referencedAssemblies = new List<Assembly>(referenceArgs.Count); _parent._referencedCollectionTypes = new List<Type>(); _parent._nostdlib = nostdlib; _parent._excludedTypes = AddSpecifiedTypesToDictionary(excludedTypeArgs, Options.Cmd.ExcludeType); //Add the DateTimeOffset type to excluded types if the target client version is 3.0. //Ensures that the DateTimeOffset type is not referenced even if mscorlib is referenced from a non-3.0 machine. switch (_parent._targetClientVersion) { case TargetClientVersionMode.Version35: break; default: if (!_parent.IsTypeExcluded(s_typeOfDateTimeOffset)) { _parent._excludedTypes.Add(s_typeOfDateTimeOffset.FullName, s_typeOfDateTimeOffset); } break; } Dictionary<string, Type> foundCollectionTypes = AddSpecifiedTypesToDictionary(collectionTypesArgs, Options.Cmd.CollectionType); LoadReferencedAssemblies(referenceArgs); foreach (Assembly assembly in _parent._referencedAssemblies) { AddReferencedTypesFromAssembly(assembly, foundCollectionTypes); } if (!nostdlib) { AddMscorlib(foundCollectionTypes); AddServiceModelLib(foundCollectionTypes); } AddReferencedCollectionTypes(collectionTypesArgs, foundCollectionTypes); } private void LoadReferencedAssemblies(IList<string> referenceArgs) { foreach (string path in referenceArgs) { Assembly assembly; try { assembly = InputModule.LoadAssembly(path); if (!_parent._referencedAssemblies.Contains(assembly)) { _parent._referencedAssemblies.Add(assembly); } else { throw new ToolOptionException(SR.Format(SR.ErrDuplicateReferenceValues, Options.Cmd.Reference, assembly.Location)); } } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Tool.IsFatal(e)) throw; throw new ToolOptionException(SR.Format(SR.ErrCouldNotLoadReferenceAssemblyAt, path), e); } } } private Dictionary<string, Type> AddSpecifiedTypesToDictionary(IList<string> typeArgs, string cmd) { Dictionary<string, Type> specifiedTypes = new Dictionary<string, Type>(typeArgs.Count); foreach (string typeArg in typeArgs) { if (specifiedTypes.ContainsKey(typeArg)) throw new ToolOptionException(SR.Format(SR.ErrDuplicateValuePassedToTypeArg, cmd, typeArg)); specifiedTypes.Add(typeArg, null); } return specifiedTypes; } private void AddReferencedTypesFromAssembly(Assembly assembly, Dictionary<string, Type> foundCollectionTypes) { foreach (Type type in InputModule.LoadTypes(assembly)) { if (type.IsPublic || type.IsNestedPublic) { if (!_parent.IsTypeExcluded(type)) _parent._referencedTypes.Add(type); else if (IsTypeSpecified(type, foundCollectionTypes, Options.Cmd.CollectionType)) _parent._referencedCollectionTypes.Add(type); } } } private void AddMscorlib(Dictionary<string, Type> foundCollectionTypes) { Assembly mscorlib = typeof(int).Assembly; if (!_parent._referencedAssemblies.Contains(mscorlib)) { AddReferencedTypesFromAssembly(mscorlib, foundCollectionTypes); } } private void AddServiceModelLib(Dictionary<string, Type> foundCollectionTypes) { Assembly serviceModelLib = typeof(ChannelFactory).Assembly; if (!_parent._referencedAssemblies.Contains(serviceModelLib)) { AddReferencedTypesFromAssembly(serviceModelLib, foundCollectionTypes); } } internal static bool IsTypeSpecified(Type type, Dictionary<string, Type> specifiedTypes, string cmd) { Type foundType = null; string foundTypeName = null; // Search the Dictionary for the type // -------------------------------------------------------------------------------------------------------- if (specifiedTypes.TryGetValue(type.FullName, out foundType)) foundTypeName = type.FullName; if (specifiedTypes.TryGetValue(type.AssemblyQualifiedName, out foundType)) foundTypeName = type.AssemblyQualifiedName; // Throw appropriate error message if we found something and the entry value wasn't null // -------------------------------------------------------------------------------------------------------- if (foundTypeName != null) { if (foundType != null && foundType != type) { throw new ToolOptionException(SR.Format(SR.ErrCannotDisambiguateSpecifiedTypes, cmd, type.AssemblyQualifiedName, foundType.AssemblyQualifiedName)); } else { specifiedTypes[foundTypeName] = type; } return true; } return false; } private void AddReferencedCollectionTypes(IList<string> collectionTypesArgs, Dictionary<string, Type> foundCollectionTypes) { // Instantiated generics specified via /rct can only be added via assembly.GetType or Type.GetType foreach (string collectionType in collectionTypesArgs) { if (foundCollectionTypes[collectionType] == null) { Type foundType = null; foreach (Assembly assembly in _parent._referencedAssemblies) { foundType = assembly.GetType(collectionType); if (foundType != null) break; } foundType = foundType ?? Type.GetType(collectionType); if (foundType == null) throw new ToolOptionException(SR.Format(SR.ErrCannotLoadSpecifiedType, Options.Cmd.CollectionType, collectionType, Options.Cmd.Reference)); else _parent._referencedCollectionTypes.Add(foundType); } } } private static TypeResolver CreateTypeResolver(Options options) { TypeResolver typeResolver = new TypeResolver(options); AppDomain.CurrentDomain.TypeResolve += new ResolveEventHandler(typeResolver.ResolveType); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(typeResolver.ResolveAssembly); return typeResolver; } } } }