context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#region /* Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu. All rights reserved. http://code.google.com/p/msnp-sharp/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of Bas Geertsema or Xih Solutions 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.IO; using System.Text; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; namespace MSNPSharp.Apps { using MSNPSharp; using MSNPSharp.P2P; using MSNPSharp.Core; /// <summary> /// A P2P application which can be used in P2P activities. /// </summary> /// <remarks>P2P activities can be defined as examples, including scene images, emoticons and display image's etc...</remarks> [P2PApplication(0, "6A13AF9C-5308-4F35-923A-67E8DDA40C2F")] public class P2PActivity : P2PApplication { private bool sending = false; private string activityData = String.Empty; private string activityName = String.Empty; public string ActivityName { get { return activityName; } } public P2PActivity(P2PSession p2pSess) : base(p2pSess.Version, p2pSess.Remote, p2pSess.RemoteContactEndPointID) { try { byte[] byts = Convert.FromBase64String(p2pSess.Invitation.BodyValues["Context"].Value); string activityUrl = System.Text.Encoding.Unicode.GetString(byts); string[] activityProperties = activityUrl.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (activityProperties.Length >= 3) { uint.TryParse(activityProperties[0], out applicationId); activityName = activityProperties[2]; } } catch (Exception ex) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "An error occured while parsing activity context, error info: " + ex.Message, GetType().Name); } sending = false; } /// <summary> /// P2PActivity constructor. /// </summary> /// <param name="remote"></param> /// <param name="applicationID"></param> /// <param name="activityName"></param> /// <param name="activityData"></param> public P2PActivity(Contact remote, uint applicationID, string activityName, string activityData) : base(remote.P2PVersionSupported, remote, remote.SelectBestEndPointId()) { this.applicationId = applicationID; this.activityName = activityName; this.activityData = activityData; sending = true; } public override string InvitationContext { get { string activityID = applicationId + ";1;" + activityName; byte[] contextData = UnicodeEncoding.Unicode.GetBytes(activityID); return Convert.ToBase64String(contextData, 0, contextData.Length); } } public override bool ValidateInvitation(SLPMessage invitation) { bool ret = base.ValidateInvitation(invitation); if (ret) { try { byte[] byts = Convert.FromBase64String(invitation.BodyValues["Context"].Value); string activityUrl = System.Text.Encoding.Unicode.GetString(byts); string[] activityProperties = activityUrl.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (activityProperties.Length >= 3) { return true; } } catch (Exception ex) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "An error occured while parsing activity context, error info: " + ex.Message, GetType().Name); } } return ret; } public override void Start() { base.Start(); if (sending) { if (activityData != string.Empty && activityData != null) { activityData += "\0"; int urlLength = Encoding.Unicode.GetByteCount(activityData); // Data prep MemoryStream urlDataStream = new MemoryStream(); P2PDataMessage prepData = new P2PDataMessage(P2PVersion); byte[] header = (P2PVersion == P2PVersion.P2PV1) ? new byte[] { 0x80, 0x00, 0x00, 0x00 } : new byte[] { 0x80, 0x3f, 0x14, 0x05 }; urlDataStream.Write(header, 0, header.Length); urlDataStream.Write(BitUtility.GetBytes((ushort)0x08, true), 0, sizeof(ushort)); //data type: 0x08: string urlDataStream.Write(BitUtility.GetBytes(urlLength, true), 0, sizeof(int)); urlDataStream.Write(Encoding.Unicode.GetBytes(activityData), 0, urlLength); urlDataStream.Seek(0, SeekOrigin.Begin); byte[] urlData = urlDataStream.ToArray(); urlDataStream.Close(); prepData.InnerBody = urlData; if (P2PVersion == P2PVersion.P2PV2) { prepData.V2Header.TFCombination = TFCombination.First; } SendMessage(prepData); Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "Data sent...", GetType().Name); } } } public override bool ProcessData(P2PBridge bridge, byte[] data, bool reset) { Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "DATA RECEIVED: " + P2PMessage.DumpBytes(data, 128, true), GetType().Name); return true; } } };
using System; using Avalonia.Utilities; using Avalonia.VisualTree; namespace Avalonia.Layout { /// <summary> /// Provides helper methods needed for layout. /// </summary> public static class LayoutHelper { /// <summary> /// Epsilon value used for certain layout calculations. /// Based on the value in WPF LayoutDoubleUtil. /// </summary> public static double LayoutEpsilon { get; } = 0.00000153; /// <summary> /// Calculates a control's size based on its <see cref="ILayoutable.Width"/>, /// <see cref="ILayoutable.Height"/>, <see cref="ILayoutable.MinWidth"/>, /// <see cref="ILayoutable.MaxWidth"/>, <see cref="ILayoutable.MinHeight"/> and /// <see cref="ILayoutable.MaxHeight"/>. /// </summary> /// <param name="control">The control.</param> /// <param name="constraints">The space available for the control.</param> /// <returns>The control's size.</returns> public static Size ApplyLayoutConstraints(ILayoutable control, Size constraints) { var minmax = new MinMax(control); return new Size( MathUtilities.Clamp(constraints.Width, minmax.MinWidth, minmax.MaxWidth), MathUtilities.Clamp(constraints.Height, minmax.MinHeight, minmax.MaxHeight)); } public static Size MeasureChild(ILayoutable control, Size availableSize, Thickness padding, Thickness borderThickness) { return MeasureChild(control, availableSize, padding + borderThickness); } public static Size MeasureChild(ILayoutable control, Size availableSize, Thickness padding) { if (control != null) { control.Measure(availableSize.Deflate(padding)); return control.DesiredSize.Inflate(padding); } return new Size(padding.Left + padding.Right, padding.Bottom + padding.Top); } public static Size ArrangeChild(ILayoutable child, Size availableSize, Thickness padding, Thickness borderThickness) { return ArrangeChild(child, availableSize, padding + borderThickness); } public static Size ArrangeChild(ILayoutable child, Size availableSize, Thickness padding) { child?.Arrange(new Rect(availableSize).Deflate(padding)); return availableSize; } /// <summary> /// Invalidates measure for given control and all visual children recursively. /// </summary> public static void InvalidateSelfAndChildrenMeasure(ILayoutable control) { void InnerInvalidateMeasure(IVisual target) { if (target is ILayoutable targetLayoutable) { targetLayoutable.InvalidateMeasure(); } var visualChildren = target.VisualChildren; var visualChildrenCount = visualChildren.Count; for (int i = 0; i < visualChildrenCount; i++) { IVisual child = visualChildren[i]; InnerInvalidateMeasure(child); } } InnerInvalidateMeasure(control); } /// <summary> /// Obtains layout scale of the given control. /// </summary> /// <param name="control">The control.</param> /// <exception cref="Exception">Thrown when control has no root or returned layout scaling is invalid.</exception> public static double GetLayoutScale(ILayoutable control) { var visualRoot = control.VisualRoot; var result = (visualRoot as ILayoutRoot)?.LayoutScaling ?? 1.0; if (result == 0 || double.IsNaN(result) || double.IsInfinity(result)) { throw new Exception($"Invalid LayoutScaling returned from {visualRoot.GetType()}"); } return result; } /// <summary> /// Rounds a size to integer values for layout purposes, compensating for high DPI screen /// coordinates. /// </summary> /// <param name="size">Input size.</param> /// <param name="dpiScaleX">DPI along x-dimension.</param> /// <param name="dpiScaleY">DPI along y-dimension.</param> /// <returns>Value of size that will be rounded under screen DPI.</returns> /// <remarks> /// This is a layout helper method. It takes DPI into account and also does not return /// the rounded value if it is unacceptable for layout, e.g. Infinity or NaN. It's a helper /// associated with the UseLayoutRounding property and should not be used as a general rounding /// utility. /// </remarks> public static Size RoundLayoutSize(Size size, double dpiScaleX, double dpiScaleY) { return new Size(RoundLayoutValue(size.Width, dpiScaleX), RoundLayoutValue(size.Height, dpiScaleY)); } /// <summary> /// Calculates the value to be used for layout rounding at high DPI. /// </summary> /// <param name="value">Input value to be rounded.</param> /// <param name="dpiScale">Ratio of screen's DPI to layout DPI</param> /// <returns>Adjusted value that will produce layout rounding on screen at high dpi.</returns> /// <remarks> /// This is a layout helper method. It takes DPI into account and also does not return /// the rounded value if it is unacceptable for layout, e.g. Infinity or NaN. It's a helper /// associated with the UseLayoutRounding property and should not be used as a general rounding /// utility. /// </remarks> public static double RoundLayoutValue(double value, double dpiScale) { double newValue; // If DPI == 1, don't use DPI-aware rounding. if (!MathUtilities.IsOne(dpiScale)) { newValue = Math.Round(value * dpiScale) / dpiScale; // If rounding produces a value unacceptable to layout (NaN, Infinity or MaxValue), // use the original value. if (double.IsNaN(newValue) || double.IsInfinity(newValue) || MathUtilities.AreClose(newValue, double.MaxValue)) { newValue = value; } } else { newValue = Math.Round(value); } return newValue; } /// <summary> /// Calculates the min and max height for a control. Ported from WPF. /// </summary> private readonly struct MinMax { public MinMax(ILayoutable e) { MaxHeight = e.MaxHeight; MinHeight = e.MinHeight; double l = e.Height; double height = (double.IsNaN(l) ? double.PositiveInfinity : l); MaxHeight = Math.Max(Math.Min(height, MaxHeight), MinHeight); height = (double.IsNaN(l) ? 0 : l); MinHeight = Math.Max(Math.Min(MaxHeight, height), MinHeight); MaxWidth = e.MaxWidth; MinWidth = e.MinWidth; l = e.Width; double width = (double.IsNaN(l) ? double.PositiveInfinity : l); MaxWidth = Math.Max(Math.Min(width, MaxWidth), MinWidth); width = (double.IsNaN(l) ? 0 : l); MinWidth = Math.Max(Math.Min(MaxWidth, width), MinWidth); } public double MinWidth { get; } public double MaxWidth { get; } public double MinHeight { get; } public double MaxHeight { get; } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Provides helper overloads to a <see cref="ReferenceCollection"/>. /// </summary> public static class ReferenceCollectionExtensions { private enum RefState { Exists, DoesNotExistButLooksValid, DoesNotLookValid, } private static RefState TryResolveReference(out Reference reference, ReferenceCollection refsColl, string canonicalName) { if (!refsColl.IsValidName(canonicalName)) { reference = null; return RefState.DoesNotLookValid; } reference = refsColl[canonicalName]; return reference != null ? RefState.Exists : RefState.DoesNotExistButLooksValid; } /// <summary> /// Creates a direct or symbolic reference with the specified name and target /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="name">The name of the reference to create.</param> /// <param name="canonicalRefNameOrObjectish">The target which can be either the canonical name of a reference or a revparse spec.</param> /// <param name="signature">The identity used for updating the reflog</param> /// <param name="logMessage">The optional message to log in the <see cref="ReflogCollection"/> when adding the <see cref="Reference"/></param> /// <param name="allowOverwrite">True to allow silent overwriting a potentially existing reference, false otherwise.</param> /// <returns>A new <see cref="Reference"/>.</returns> public static Reference Add(this ReferenceCollection refsColl, string name, string canonicalRefNameOrObjectish, Signature signature, string logMessage, bool allowOverwrite = false) { Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNullOrEmptyString(canonicalRefNameOrObjectish, "canonicalRefNameOrObjectish"); Reference reference; RefState refState = TryResolveReference(out reference, refsColl, canonicalRefNameOrObjectish); var gitObject = refsColl.repo.Lookup(canonicalRefNameOrObjectish, GitObjectType.Any, LookUpOptions.None); if (refState == RefState.Exists) { return refsColl.Add(name, reference, signature, logMessage, allowOverwrite); } if (refState == RefState.DoesNotExistButLooksValid && gitObject == null) { using (ReferenceSafeHandle handle = Proxy.git_reference_symbolic_create(refsColl.repo.Handle, name, canonicalRefNameOrObjectish, allowOverwrite, signature.OrDefault(refsColl.repo.Config), logMessage)) { return Reference.BuildFromPtr<Reference>(handle, refsColl.repo); } } Ensure.GitObjectIsNotNull(gitObject, canonicalRefNameOrObjectish); if (logMessage == null) { logMessage = string.Format(CultureInfo.InvariantCulture, "{0}: Created from {1}", name.LooksLikeLocalBranch() ? "branch" : "reference", canonicalRefNameOrObjectish); } refsColl.EnsureHasLog(name); return refsColl.Add(name, gitObject.Id, signature, logMessage, allowOverwrite); } /// <summary> /// Creates a direct or symbolic reference with the specified name and target /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="name">The name of the reference to create.</param> /// <param name="canonicalRefNameOrObjectish">The target which can be either the canonical name of a reference or a revparse spec.</param> /// <param name="allowOverwrite">True to allow silent overwriting a potentially existing reference, false otherwise.</param> /// <returns>A new <see cref="Reference"/>.</returns> public static Reference Add(this ReferenceCollection refsColl, string name, string canonicalRefNameOrObjectish, bool allowOverwrite = false) { return Add(refsColl, name, canonicalRefNameOrObjectish, null, null, allowOverwrite); } /// <summary> /// Updates the target of a direct reference. /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="directRef">The direct reference which target should be updated.</param> /// <param name="objectish">The revparse spec of the target.</param> /// <param name="signature">The identity used for updating the reflog</param> /// <param name="logMessage">The optional message to log in the <see cref="ReflogCollection"/></param> /// <returns>A new <see cref="Reference"/>.</returns> public static Reference UpdateTarget(this ReferenceCollection refsColl, Reference directRef, string objectish, Signature signature, string logMessage) { Ensure.ArgumentNotNull(directRef, "directRef"); Ensure.ArgumentNotNull(objectish, "objectish"); GitObject target = refsColl.repo.Lookup(objectish); Ensure.GitObjectIsNotNull(target, objectish); return refsColl.UpdateTarget(directRef, target.Id, signature, logMessage); } /// <summary> /// Updates the target of a direct reference /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="directRef">The direct reference which target should be updated.</param> /// <param name="objectish">The revparse spec of the target.</param> /// <returns>A new <see cref="Reference"/>.</returns> public static Reference UpdateTarget(this ReferenceCollection refsColl, Reference directRef, string objectish) { return UpdateTarget(refsColl, directRef, objectish, null, null); } /// <summary> /// Rename an existing reference with a new name /// </summary> /// <param name="currentName">The canonical name of the reference to rename.</param> /// <param name="newName">The new canonical name.</param> /// <param name="signature">The identity used for updating the reflog</param> /// <param name="logMessage">The optional message to log in the <see cref="ReflogCollection"/></param> /// <param name="allowOverwrite">True to allow silent overwriting a potentially existing reference, false otherwise.</param> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <returns>A new <see cref="Reference"/>.</returns> public static Reference Move(this ReferenceCollection refsColl, string currentName, string newName, Signature signature = null, string logMessage = null, bool allowOverwrite = false) { Ensure.ArgumentNotNullOrEmptyString(currentName, "currentName"); Reference reference = refsColl[currentName]; if (reference == null) { throw new LibGit2SharpException( string.Format(CultureInfo.InvariantCulture, "Reference '{0}' doesn't exist. One cannot move a non existing reference.", currentName)); } return refsColl.Move(reference, newName, signature, logMessage, allowOverwrite); } /// <summary> /// Updates the target of a reference /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="name">The canonical name of the reference.</param> /// <param name="canonicalRefNameOrObjectish">The target which can be either the canonical name of a reference or a revparse spec.</param> /// <param name="signature">The identity used for updating the reflog</param> /// <param name="logMessage">The optional message to log in the <see cref="ReflogCollection"/> of the <paramref name="name"/> reference.</param> /// <returns>A new <see cref="Reference"/>.</returns> public static Reference UpdateTarget(this ReferenceCollection refsColl, string name, string canonicalRefNameOrObjectish, Signature signature, string logMessage) { Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNullOrEmptyString(canonicalRefNameOrObjectish, "canonicalRefNameOrObjectish"); signature = signature.OrDefault(refsColl.repo.Config); if (name == "HEAD") { return refsColl.UpdateHeadTarget(canonicalRefNameOrObjectish, signature, logMessage); } Reference reference = refsColl[name]; var directReference = reference as DirectReference; if (directReference != null) { return refsColl.UpdateTarget(directReference, canonicalRefNameOrObjectish, signature, logMessage); } var symbolicReference = reference as SymbolicReference; if (symbolicReference != null) { Reference targetRef; RefState refState = TryResolveReference(out targetRef, refsColl, canonicalRefNameOrObjectish); if (refState == RefState.DoesNotLookValid) { throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The reference specified by {0} is a Symbolic reference, you must provide a reference canonical name as the target.", name), "canonicalRefNameOrObjectish"); } return refsColl.UpdateTarget(symbolicReference, targetRef, signature, logMessage); } throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Reference '{0}' has an unexpected type ('{1}').", name, reference.GetType())); } /// <summary> /// Updates the target of a reference /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="name">The canonical name of the reference.</param> /// <param name="canonicalRefNameOrObjectish">The target which can be either the canonical name of a reference or a revparse spec.</param> /// <returns>A new <see cref="Reference"/>.</returns> public static Reference UpdateTarget(this ReferenceCollection refsColl, string name, string canonicalRefNameOrObjectish) { return UpdateTarget(refsColl, name, canonicalRefNameOrObjectish, null, null); } /// <summary> /// Delete a reference with the specified name /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="name">The canonical name of the reference to delete.</param> public static void Remove(this ReferenceCollection refsColl, string name) { Ensure.ArgumentNotNullOrEmptyString(name, "name"); Reference reference = refsColl[name]; if (reference == null) { return; } refsColl.Remove(reference); } /// <summary> /// Find the <see cref="Reference"/>s among <paramref name="refSubset"/> /// that can reach at least one <see cref="Commit"/> in the specified <paramref name="targets"/>. /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="refSubset">The set of <see cref="Reference"/>s to examine.</param> /// <param name="targets">The set of <see cref="Commit"/>s that are interesting.</param> /// <returns>A subset of <paramref name="refSubset"/> that can reach at least one <see cref="Commit"/> within <paramref name="targets"/>.</returns> public static IEnumerable<Reference> ReachableFrom( this ReferenceCollection refsColl, IEnumerable<Reference> refSubset, IEnumerable<Commit> targets) { Ensure.ArgumentNotNull(refSubset, "refSubset"); Ensure.ArgumentNotNull(targets, "targets"); var refs = new List<Reference>(refSubset); if (refs.Count == 0) { return Enumerable.Empty<Reference>(); } List<ObjectId> targetsSet = targets.Select(c => c.Id).Distinct().ToList(); if (targetsSet.Count == 0) { return Enumerable.Empty<Reference>(); } var result = new List<Reference>(); foreach (var reference in refs) { var peeledTargetCommit = reference .ResolveToDirectReference() .Target.DereferenceToCommit(false); if (peeledTargetCommit == null) { continue; } var commitId = peeledTargetCommit.Id; foreach (var potentialAncestorId in targetsSet) { if (potentialAncestorId == commitId) { result.Add(reference); break; } if (Proxy.git_graph_descendant_of(refsColl.repo.Handle, commitId, potentialAncestorId)) { result.Add(reference); break; } } } return result; } /// <summary> /// Find the <see cref="Reference"/>s /// that can reach at least one <see cref="Commit"/> in the specified <paramref name="targets"/>. /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="targets">The set of <see cref="Commit"/>s that are interesting.</param> /// <returns>The list of <see cref="Reference"/> that can reach at least one <see cref="Commit"/> within <paramref name="targets"/>.</returns> public static IEnumerable<Reference> ReachableFrom( this ReferenceCollection refsColl, IEnumerable<Commit> targets) { return ReachableFrom(refsColl, refsColl, targets); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.IO; using System.Linq; using JetBrains.Annotations; using osu.Framework.Audio; using osu.Framework.Audio.Sample; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using osu.Game.Audio; using osu.Game.IO; using osu.Game.Rulesets.Scoring; using osuTK.Graphics; namespace osu.Game.Skinning { public class LegacySkin : Skin { [CanBeNull] protected TextureStore Textures; [CanBeNull] protected IResourceStore<SampleChannel> Samples; public new LegacySkinConfiguration Configuration { get => base.Configuration as LegacySkinConfiguration; set => base.Configuration = value; } public LegacySkin(SkinInfo skin, IResourceStore<byte[]> storage, AudioManager audioManager) : this(skin, new LegacySkinResourceStore<SkinFileInfo>(skin, storage), audioManager, "skin.ini") { } protected LegacySkin(SkinInfo skin, IResourceStore<byte[]> storage, AudioManager audioManager, string filename) : base(skin) { Stream stream = storage?.GetStream(filename); if (stream != null) { using (LineBufferedReader reader = new LineBufferedReader(stream)) Configuration = new LegacySkinDecoder().Decode(reader); } else Configuration = new LegacySkinConfiguration { LegacyVersion = LegacySkinConfiguration.LATEST_VERSION }; if (storage != null) { Samples = audioManager?.GetSampleStore(storage); Textures = new TextureStore(new TextureLoaderStore(storage)); (storage as ResourceStore<byte[]>)?.AddExtension("ogg"); } } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); Textures?.Dispose(); Samples?.Dispose(); } public override IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) { switch (lookup) { case GlobalSkinColours colour: switch (colour) { case GlobalSkinColours.ComboColours: var comboColours = Configuration.ComboColours; if (comboColours != null) return SkinUtils.As<TValue>(new Bindable<IReadOnlyList<Color4>>(comboColours)); break; default: return SkinUtils.As<TValue>(getCustomColour(colour.ToString())); } break; case LegacySkinConfiguration.LegacySetting legacy: switch (legacy) { case LegacySkinConfiguration.LegacySetting.Version: if (Configuration.LegacyVersion is decimal version) return SkinUtils.As<TValue>(new Bindable<decimal>(version)); break; } break; case SkinCustomColourLookup customColour: return SkinUtils.As<TValue>(getCustomColour(customColour.Lookup.ToString())); default: // handles lookups like GlobalSkinConfiguration try { if (Configuration.ConfigDictionary.TryGetValue(lookup.ToString(), out var val)) { // special case for handling skins which use 1 or 0 to signify a boolean state. if (typeof(TValue) == typeof(bool)) val = val == "1" ? "true" : "false"; var bindable = new Bindable<TValue>(); if (val != null) bindable.Parse(val); return bindable; } } catch { } break; } return null; } private IBindable<Color4> getCustomColour(string lookup) => Configuration.CustomColours.TryGetValue(lookup, out var col) ? new Bindable<Color4>(col) : null; public override Drawable GetDrawableComponent(ISkinComponent component) { switch (component) { case GameplaySkinComponent<HitResult> resultComponent: switch (resultComponent.Component) { case HitResult.Miss: return this.GetAnimation("hit0", true, false); case HitResult.Meh: return this.GetAnimation("hit50", true, false); case HitResult.Good: return this.GetAnimation("hit100", true, false); case HitResult.Great: return this.GetAnimation("hit300", true, false); } break; } return this.GetAnimation(component.LookupName, false, false); } public override Texture GetTexture(string componentName) { componentName = getFallbackName(componentName); float ratio = 2; var texture = Textures?.Get($"{componentName}@2x"); if (texture == null) { ratio = 1; texture = Textures?.Get(componentName); } if (texture != null) texture.ScaleAdjust = ratio; return texture; } public override SampleChannel GetSample(ISampleInfo sampleInfo) { foreach (var lookup in sampleInfo.LookupNames) { var sample = Samples?.Get(lookup); if (sample != null) return sample; } if (sampleInfo is HitSampleInfo hsi) // Try fallback to non-bank samples. return Samples?.Get(hsi.Name); return null; } private string getFallbackName(string componentName) { string lastPiece = componentName.Split('/').Last(); return componentName.StartsWith("Gameplay/taiko/") ? "taiko-" + lastPiece : lastPiece; } } }
using UnityEngine; using System.Collections; /// <summary> /// Simply moves the current game object /// </summary> public class MoveScript : MonoBehaviour { // 1 - Designer variables /// <summary> /// Object speed /// </summary> public Vector2 speed = new Vector2(10, 10); /// <summary> /// Moving direction /// </summary> public Vector2 direction = new Vector2(-1, 0); private Vector2 movement; public bool alternateYMovement = false; public bool alternateXMovement = false; public bool chasePlayer = false; private float lastDirectionChange = 0f; private float changeDirectionInterval = 1.0f; //only for X axis private float lastXDirectionChange = 0f; private float changeXDirectionInterval = 1.0f; public int limitedMovementXInterval = 0; public int limitedMovementYInterval = 0; //This is related with the 2 intervals above, basically stops movement (with script still enabled) public bool stopOnMaxX=false; public bool stopOnMaxY=false; private bool stopMovement = false; public bool allowRevertXDirection = false; public bool allowRevertYDirection = false; //revert the transform, not just the direction public bool revertAlsoTransform = false; private bool revert = false; private GameObject target; private Vector3 startPosition; //allows the object to move even if not visible //by default is always false, so must be explicit set to true //like on asteroid spawner (of level 1) for instance public bool allowMoveIfNotVisible = false; bool isVisible = false; void Start() { revert = false; startPosition = Camera.main.WorldToScreenPoint (transform.position); } void Awake() { target = GameObject.FindGameObjectWithTag("Player"); } void CheckPositions() { Vector3 currentPosition = Camera.main.WorldToScreenPoint (transform.position); //check on X if(limitedMovementXInterval>0) { if(direction.x < 0 ) { //moving left if(!revert) { if(currentPosition.x < startPosition.x - (0.0f + limitedMovementXInterval ) ){ if(!stopOnMaxX) { revert = true; startPosition.x = currentPosition.x; } else { stopMovement = true; } } } } else if(direction.x > 0) { //moving right if(!revert) { if(currentPosition.x > startPosition.x + (0.0f+ limitedMovementXInterval) ){ if(!stopOnMaxX) { revert = true; startPosition.x = currentPosition.x; } else { stopMovement = true; } } } } } else { //check on Y if(direction.y > 0 ) { //is actually moving down if(!revert) { if(currentPosition.y > startPosition.y + (0.0f- limitedMovementYInterval) ){ //if(!stopOnMaxY) { revert = true; startPosition.y = currentPosition.y; //} //else { Debug.Log("stop movement"); stopMovement = true; //} } } } else if(direction.y < 0) { if(!revert) { if(currentPosition.y < startPosition.y - (0.0f - limitedMovementYInterval ) ){ //if(!stopOnMaxY) { revert = true; startPosition.y = currentPosition.y; //} //else { stopMovement = true; //} } } } }//end check on y } bool AllowRevertDirection() { return allowRevertXDirection || allowRevertYDirection; } bool HasLimitedMovementInterval() { return limitedMovementXInterval > 0 || limitedMovementYInterval>0; } void Update() { if(!revert && (stopOnMaxX || stopOnMaxY) ) { CheckPositions(); //if(!stopMovement) { movement = new Vector2( speed.x * direction.x, speed.y * direction.y); //} } else if(!revert && ( AllowRevertDirection() && HasLimitedMovementInterval() ) ) { CheckPositions(); if(revert) { if(limitedMovementXInterval>0) { // 1 - revert current direction on x axis direction.x = direction.x*-1; } else { //revert is on y axis, instead direction.y = direction.y*-1; } // 3 - Define new movement, based on new direction movement = new Vector2( speed.x * direction.x, speed.y * direction.y); revert = false; } } else if(allowMoveIfNotVisible && allowRevertXDirection && revert) { // 1 - revert current direction on x axis direction.x = direction.x*-1; // 3 - Define new movement, based on new direction movement = new Vector2( speed.x * direction.x, speed.y * direction.y); revert = false; if(revertAlsoTransform) { transform.localScale = new Vector3(transform.localScale.x* -1, transform.localScale.y, transform.localScale.z ); } } else { if( allowMoveIfNotVisible || isVisible ) { lastDirectionChange += Time.deltaTime; lastXDirectionChange += Time.deltaTime; if(alternateYMovement && (lastDirectionChange >= changeDirectionInterval) ) { if(chasePlayer && target!=null) { Vector3 targetPosition = target.transform.position; if(targetPosition.y > transform.position.y) { direction.y = 1; } else if(targetPosition.y < transform.position.y) { direction.y = -1; } else { direction.y = 0; } } else { GetRandomYDirection(); } lastDirectionChange = 0f; //transform.rotation = Rotate2D.SmoothLookAt(transform, Vector3 target, Vector3 axis, float speed); } else if(alternateXMovement && (lastXDirectionChange >= changeXDirectionInterval) ) { GetRandomXDirection(); lastXDirectionChange = 0f; } //transform.RotateAround(transform.position, Vector3.forward, 20 * Time.deltaTime); // 2 - Movement movement = new Vector2( speed.x * direction.x, speed.y * direction.y); //lastXDirection = direction.x; } } } void FixedUpdate() { //we only move the enemy or asteroi if the player is on scene, //otherwise we see a lot of space without enemies, more close to the end of the level // Apply movement to the rigidbody //check if in camera if( (allowMoveIfNotVisible || isVisible) && !stopMovement ) { rigidbody2D.velocity = movement; } } //gets a random y direction, either 0,-1 or 1 private void GetRandomYDirection() { direction.y = Random.Range(-1,2); } //gets a random x direction, either 0,-1 or 1 private void GetRandomXDirection() { direction.x = Random.Range(-1,2); } //called from outside, to allow or not, move if not vivible public void AllowMoveWhenInvisible(bool allowInvisibleMove) { allowMoveIfNotVisible = allowInvisibleMove; } void OnBecameVisible() { isVisible = true; } //TODO; IS NOT TURNING BACK ANYMORE void OnBecameInvisible (){ if(isVisible) { if (allowMoveIfNotVisible && allowRevertXDirection && limitedMovementXInterval == 0) { revert = true; } } isVisible = false; } }
// // Copyright 2014 Matthew Ducker // // 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.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using Obscur.Core.Cryptography.Authentication; using Obscur.Core.Cryptography.Authentication.Primitives; using Obscur.Core.Cryptography.Entropy; using Obscur.Core.Cryptography.Support; using Obscur.Core.Cryptography.Support.Math; using Obscur.Core.Cryptography.Support.Math.EllipticCurve; using Obscur.Core.Cryptography.Support.Math.EllipticCurve.Custom.SEC; using Obscur.Core.Cryptography.Support.Math.EllipticCurve.Multiplier; using Obscur.Core.DTO; namespace Obscur.Core.Cryptography.KeyAgreement.Primitives { /// <summary> /// Implementation of Password Authenticated Key Exchange by Juggling (J-PAKE) /// passphrase-authenticated key agreement protocol with elliptic curve math. /// </summary> public sealed class ECJpakeSession : IDisposable { #region Fields /// <summary> /// Speciality EC base point multiplier. /// </summary> private static readonly ECMultiplier BasePointMultiplier = new FixedPointCombMultiplier(); private static readonly byte[] MacKeyConstantBytes = Encoding.UTF8.GetBytes("JPAKE_KC"); private static readonly byte[] MacTagConstantBytes = Encoding.UTF8.GetBytes("KC_1_U"); /// <summary> /// Provides hashing capability. /// Together with field size of elliptic curve, sets security level. /// </summary> private IHash _digest; /// <summary> /// Domain parameters for elliptic curve system. /// </summary> private readonly ECDomainParameters _domain; private readonly BigInteger _q; private ECPoint _b = null; // Constants private ECPoint _gx1; private ECPoint _gx2; private ECPoint _gx3; private ECPoint _gx4; private BigInteger _keyingMaterial; private BigInteger _macTag; /// <summary> /// Shared secret. /// This only contains the secret between construction and a call to CalculateKeyingMaterial(). /// </summary> private byte[] _passwordBytes; // Variables holding private state private BigInteger _x2; // Private key - x1 is not stored, as it is only ephemeral #endregion /// <summary> /// Start a new or resume a previous J-PAKE key agreement session. /// If resuming, call RestoreState() method immediately after construction. /// </summary> /// <param name="participantId">Participant identifier.</param> /// <param name="passphrase">Passphrase believed to be known to both parties.</param> /// <param name="group">Elliptic curve group/domain (must be over F(<sub>p</sub>).</param> /// <param name="digest">Digest/hash function.</param> /// <param name="random">Random data generator/source.</param> public ECJpakeSession(string participantId, string passphrase, ECDomainParameters group, IHash digest, CsRng random) { Contract.Requires<ArgumentException>(String.IsNullOrEmpty(participantId) == false, "Participant ID must not be null/empty."); Contract.Requires<ArgumentException>(String.IsNullOrEmpty(passphrase) == false, "Passphrase must not be null/empty."); Contract.Requires(group != null); Contract.Requires(digest != null); Contract.Requires(random != null); ECCurve curve = group.Curve; var curveAsFp = group.Curve as FpCurve; if (curveAsFp == null) { if (curve is SecP192K1Curve) { _q = ((SecP192K1Curve) curve).Q; } else if (curve is SecP192R1Curve) { _q = ((SecP192R1Curve) curve).Q; } else if (curve is SecP224K1Curve) { _q = ((SecP224K1Curve) curve).Q; } else if (curve is SecP224R1Curve) { _q = ((SecP224R1Curve) curve).Q; } else if (curve is SecP256K1Curve) { _q = ((SecP256K1Curve) curve).Q; } else if (curve is SecP256R1Curve) { _q = ((SecP256R1Curve) curve).Q; } else if (curve is SecP384R1Curve) { _q = ((SecP384R1Curve) curve).Q; } else if (curve is SecP521R1Curve) { _q = ((SecP521R1Curve) curve).Q; } else { throw new ArgumentException("Curve in EC domain parameters must be over F(p)", "group"); } } else { _q = curveAsFp.Q; } ParticipantId = participantId; _passwordBytes = Encoding.UTF8.GetBytes(passphrase); _domain = group; _digest = digest; EntropySupply = random; ProtocolState = State.Initialised; } #region Properties /// <summary> /// The state of the protocol. /// </summary> public State ProtocolState { get; private set; } /// <summary> /// Unique identifier of this local instance's participant. /// The two participants in the exchange must NOT share the same ID. /// </summary> public string ParticipantId { get; private set; } /// <summary> /// Unique identifier of the remote instance's participant (partner). /// The two participants in the exchange must NOT share the same ID. /// </summary> public string PartnerParticipantId { get; private set; } /// <summary> /// Source of random bytes. /// </summary> public CsRng EntropySupply { get; private set; } #endregion /// <summary> /// Restores the state of an incomplete J-PAKE session, /// given private keys and DTO objects created/received from that session. /// </summary> /// <param name="x2">Private key.</param> /// <param name="round1Created">Round 1 created/sent.</param> /// <param name="round1Received">Round 1 received.</param> /// <param name="round2Created">Round 2 created/sent.</param> /// <param name="round2Received">Round 2 received.</param> /// <param name="round3Created">Round 3 created/sent.</param> public void RestoreState(byte[] x2, ECJpakeRound1 round1Created, ECJpakeRound1 round1Received = null, ECJpakeRound2 round2Created = null, ECJpakeRound2 round2Received = null, JpakeRound3 round3Created = null) { Contract.Requires(ProtocolState == State.Initialised, "Cannot restore state of already-active protocol session!"); Contract.Requires(round1Created != null); _gx1 = _domain.Curve.DecodePoint(round1Created.GX1); _gx2 = _domain.Curve.DecodePoint(round1Created.GX2); ProtocolState = State.Round1Created; if (round1Received != null) { if (String.IsNullOrEmpty(round1Received.ParticipantId)) { throw new ArgumentException("Partner participant ID in round 1 received is null or empty."); } PartnerParticipantId = round1Received.ParticipantId; _gx3 = _domain.Curve.DecodePoint(round1Received.GX1); _gx4 = _domain.Curve.DecodePoint(round1Received.GX2); ProtocolState = State.Round1Validated; } else { return; } if (round2Created != null) { ProtocolState = State.Round2Created; } else { return; } if (round2Received != null) { if (PartnerParticipantId.Equals(round2Received.ParticipantId, StringComparison.Ordinal) == false) { throw new ArgumentException("Partner participant ID of round 2 does not match value from round 1."); } _b = _domain.Curve.DecodePoint(round2Received.A); ProtocolState = State.Round2Validated; } else { return; } if (round3Created != null) { // Keying material has been calculated _b = _domain.Curve.DecodePoint(round2Received.A); ProtocolState = State.Round3Created; } else { if (x2.IsNullOrZeroLength()) { throw new ArgumentException("Session cannot be resumed without private key x2Export. Aborting."); } } } /// <summary> /// Provides the ability to suspend the session for later resumption by exporting the /// session participant's private key. This key must be stored securely! /// DTO state objects created/sent and received thus far must also be retained /// (these are not output by this method). /// </summary> public void SuspendSession(out byte[] x2Export) { x2Export = _x2.ToByteArray(); } #region Round 1 /// <summary> /// Creates a round 1 (zero-knowledge proof) DTO to send to the partner participant. /// </summary> public ECJpakeRound1 CreateRound1ToSend() { Contract.Requires(ProtocolState < State.Round1Created, "Round 1 payload already created."); BigInteger x1 = BigInteger.CreateRandomInRange(BigInteger.One, _domain.N.Subtract(BigInteger.One), EntropySupply); _x2 = BigInteger.CreateRandomInRange(BigInteger.One, _domain.N.Subtract(BigInteger.One), EntropySupply); _gx1 = BasePointMultiplier.Multiply(_domain.G, x1); _gx2 = BasePointMultiplier.Multiply(_domain.G, _x2); ECPoint V1, V2; BigInteger r1, r2; CreateZeroKnowledgeProof(_domain.G, x1, _gx1, ParticipantId, out V1, out r1); CreateZeroKnowledgeProof(_domain.G, _x2, _gx2, ParticipantId, out V2, out r2); var dto = new ECJpakeRound1 { ParticipantId = ParticipantId, GX1 = _gx1.GetEncoded(), X1V = V1.GetEncoded(), X1R = r1.ToByteArray(), GX2 = _gx2.GetEncoded(), X2V = V2.GetEncoded(), X2R = r2.ToByteArray() }; ProtocolState = State.Round1Created; return dto; } /// <summary> /// Validates the round 1 (zero-knowledge proof) DTO received from the partner participant. /// </summary> /// <param name="round1Received">Round 1 DTO received from partner participant.</param> public void ValidateRound1Received(ECJpakeRound1 round1Received) { Contract.Requires<InvalidOperationException>(ProtocolState < State.Round1Validated, "Validation already attempted for round 1 payload."); Contract.Requires<ConfigurationInvalidException>(String.IsNullOrEmpty(round1Received.ParticipantId) == false, "Partner participant ID in round 1 DTO received is null or empty."); PartnerParticipantId = round1Received.ParticipantId; _gx3 = _domain.Curve.DecodePoint(round1Received.GX1); _gx4 = _domain.Curve.DecodePoint(round1Received.GX2); ECPoint X3V = _domain.Curve.DecodePoint(round1Received.X1V); var X3R = new BigInteger(round1Received.X1R); ECPoint X4V = _domain.Curve.DecodePoint(round1Received.X2V); var X4R = new BigInteger(round1Received.X2R); if (ZeroKnowledgeProofValid(_domain.G, _gx3, X3V, X3R, PartnerParticipantId) == false || ZeroKnowledgeProofValid(_domain.G, _gx4, X4V, X4R, PartnerParticipantId) == false) { throw new CryptoException("Verification of zero-knowledge proof in round 1 failed."); } ProtocolState = State.Round1Validated; } #endregion #region Round 2 /// <summary> /// Creates a round 2 (zero-knowledge proof) DTO to send to the partner participant. /// </summary> /// <exception cref="InvalidOperationException"> /// Prior round (1) has not been completed yet, or method may have been called more than once. /// </exception> public ECJpakeRound2 CreateRound2ToSend() { if (ProtocolState >= State.Round2Created) { throw new InvalidOperationException("Round 2 payload already created."); } if (ProtocolState < State.Round1Validated) { throw new InvalidOperationException("Round 1 payload must be validated prior to creating Round 2 payload."); } var s1 = new BigInteger(_passwordBytes); ECPoint GA = _gx1.Add(_gx3).Add(_gx4); BigInteger x2s1 = _x2.Multiply(s1).Mod(_domain.N); ECPoint A = BasePointMultiplier.Multiply(GA, x2s1); ECPoint X2sV; BigInteger X2sR; CreateZeroKnowledgeProof(GA, x2s1, A, ParticipantId, out X2sV, out X2sR); var dto = new ECJpakeRound2 { ParticipantId = ParticipantId, A = A.GetEncoded(), X2sV = X2sV.GetEncoded(), X2sR = X2sR.ToByteArray() }; ProtocolState = State.Round2Created; return dto; } /// <summary> /// Validates the round 2 (zero-knowledge proof) DTO received from the partner participant. /// </summary> /// <param name="round2Received">Round 2 DTO received form partner participant.</param> /// <exception cref="InvalidOperationException"> /// Prior round (1) has not been completed yet, or method may have been called more than once. /// </exception> /// <exception cref="CryptoException"> /// Verification of zero-knowledge proof failed. Possible attempted impersonation, e.g. MiTM. /// </exception> public void ValidateRound2Received(ECJpakeRound2 round2Received) { Contract.Requires<InvalidOperationException>(ProtocolState < State.Round2Validated, "Validation already attempted for round 2 payload."); Contract.Requires<InvalidOperationException>(ProtocolState > State.Round1Validated, "Round 1 payload must be validated prior to validating round 2 payload."); Contract.Requires<ConfigurationInvalidException>(String.IsNullOrEmpty(round2Received.ParticipantId) == false, "Partner participant ID in round 2 DTO received is null or empty."); Contract.Requires<CryptoException>(PartnerParticipantId.Equals(round2Received.ParticipantId, StringComparison.Ordinal), "Partner participant ID of round 2 DTO does not match value from round 1."); ECPoint X4sV = _domain.Curve.DecodePoint(round2Received.X2sV); var X4sR = new BigInteger(round2Received.X2sR); _b = _domain.Curve.DecodePoint(round2Received.A); // Calculate GB : GX1 + GX3 + GX4 symmetrically ECPoint GB = _gx3.Add(_gx1).Add(_gx2); if (ZeroKnowledgeProofValid(GB, _b, X4sV, X4sR, PartnerParticipantId) == false) { throw new CryptoException("Round 2 validation failed. Possible impersonation attempt."); } ProtocolState = State.Round2Validated; } #endregion #region Round 3 /// <summary> /// Creates a round 3 (key confirmation) DTO to send to the partner participant. /// </summary> /// <exception cref="InvalidOperationException"> /// Prior rounds (1 and 2) have not been completed yet, or method may have been called more than once. /// </exception> public JpakeRound3 CreateRound3ToSend() { Contract.Requires<InvalidOperationException>(ProtocolState < State.Round3Created, "Round 3 already created."); Contract.Requires<InvalidOperationException>(ProtocolState == State.Round2Validated, "Round 2 payload must be validated prior to creating round 3 payload."); _keyingMaterial = CalculateKeyingMaterialInternal(); _macTag = CalculateMacTag(ParticipantId, PartnerParticipantId, _gx1, _gx2, _gx3, _gx4, _keyingMaterial); var dto = new JpakeRound3 { ParticipantId = ParticipantId, VerifiedOutput = _macTag.ToByteArrayUnsigned() }; ProtocolState = State.Round3Created; return dto; } /// <summary> /// Validates the round 3 (key confirmation) DTO received from the partner participant. /// </summary> /// <param name="round3Received">Round 3 DTO received from partner participant.</param> /// <param name="keyingMaterial">Shared secret to be derived further before use as a key (e.g. by a KDF).</param> /// <exception cref="InvalidOperationException"> /// Key calculation and/or prior rounds (1 and 2) have not been completed yet, or /// method may have been called more than once. /// </exception> /// <exception cref="CryptoException"> /// Key confirmation failed - partner participant derived a different key. The passphrase used differs. /// Possible attempted impersonation / MiTM. /// </exception> public void ValidateRound3Received(JpakeRound3 round3Received, out byte[] keyingMaterial) { Contract.Requires<InvalidOperationException>(ProtocolState < State.Round3Validated, "Validation already attempted for round 3 payload."); // Contract.Requires<InvalidOperationException>(ProtocolState > State.KeyCalculated, // "Keying material must be calculated validated prior to validating round 3."); Contract.Requires<InvalidOperationException>(ProtocolState > State.Round2Validated, "Round 2 must be validated prior to validating round 3."); Contract.Requires<ConfigurationInvalidException>(String.IsNullOrEmpty(round3Received.ParticipantId) == false, "Partner participant ID in round 3 DTO received is null or empty."); Contract.Requires<CryptoException>(PartnerParticipantId.Equals(round3Received.ParticipantId, StringComparison.Ordinal), "Partner participant ID of round 3 DTO does not match value from prior rounds (1 and 2)."); var receivedTag = new BigInteger(round3Received.VerifiedOutput); if (_keyingMaterial == null) { CalculateKeyingMaterialInternal(); } BigInteger expectedTag = CalculateMacTag(PartnerParticipantId, ParticipantId, _gx3, _gx4, _gx1, _gx2, _keyingMaterial); byte[] expectedMacTagBytes = expectedTag.ToByteArrayUnsigned(); byte[] receivedMacTagBytes = receivedTag.ToByteArrayUnsigned(); if (expectedMacTagBytes.SequenceEqual_ConstantTime(receivedMacTagBytes) == false) { throw new CryptoException("Key confirmation failed - partner MAC tag failed to match expected value."); } // Return the confirmed key to the participant keyingMaterial = _keyingMaterial.ToByteArrayUnsigned(); // Clear sensitive state _keyingMaterial = null; _passwordBytes = null; _macTag = null; _x2 = null; _gx1 = null; _gx2 = null; _gx3 = null; _gx4 = null; ProtocolState = State.Round3Validated; } #endregion /// <summary> /// Calculates the derived shared secret - this can be used externally, skipping key confirmation (NOT RECOMMENDED). /// A session key must be derived from this key material using a secure key derivation function (KDF). /// The KDF used to derive the key is handled externally. /// </summary> internal byte[] CalculateKeyingMaterial() { return CalculateKeyingMaterialInternal().ToByteArrayUnsigned(); } /// <summary> /// Calculates keying material derived from shared secrets and passphrase. /// </summary> private BigInteger CalculateKeyingMaterialInternal() { // Contract.Requires<InvalidOperationException>(ProtocolState < State.KeyCalculated, // "Key already calculated."); Contract.Requires<InvalidOperationException>(ProtocolState == State.Round2Validated, "Round 2 must be validated prior to calculating key."); Contract.Ensures(Contract.Result<BigInteger>() != null); var s1 = new BigInteger(_passwordBytes); // Clear secret _passwordBytes.SecureWipe(); _passwordBytes = null; // Prepare BigInteger to be hashed ECPoint GX4x2s1 = BasePointMultiplier.Multiply(_gx4, _x2.Multiply(s1).Mod(_domain.N)); ECPoint normalised = BasePointMultiplier.Multiply(_b.Subtract(GX4x2s1), _x2).Normalize(); BigInteger preKey = normalised.AffineXCoord.ToBigInteger(); // Clear private keys from memory _x2 = null; _b = null; // Do not clear GX1-4, as these are needed for key confirmation (round 3) // ProtocolState = State.KeyCalculated; return Hash(preKey); } /// <summary> /// Creates a zero knowledge proof. /// </summary> private void CreateZeroKnowledgeProof(ECPoint generator, BigInteger x, ECPoint X, string participantId, out ECPoint V, out BigInteger r) { // Generate a random v from [1, n-1], and compute V = G*v BigInteger v = BigInteger.CreateRandomInRange(BigInteger.One, _domain.N.Subtract(BigInteger.One), EntropySupply); V = BasePointMultiplier.Multiply(generator, v); // g * V BigInteger h = Hash(generator, V, X, participantId); r = v.Subtract(x.Multiply(h)).Mod(_domain.N); // v - (x * h) mod n } /// <summary> /// Verifies a zero knowledge proof. /// </summary> /// <returns><c>true</c>, if zero knowledge proof is valid/correct, <c>false</c> otherwise.</returns> private bool ZeroKnowledgeProofValid(ECPoint generator, ECPoint X, ECPoint V, BigInteger r, string participantId) { // ZKP: { V=G*v, r } BigInteger h = Hash(generator, V, X, participantId); // Public key validation based on p. 25 // http://cs.ucsb.edu/~koc/ccs130h/notes/ecdsa-cert.pdf // 1. X != infinity if (X.IsInfinity) { return false; } BigInteger xCoord = X.AffineXCoord.ToBigInteger(); BigInteger yCoord = X.AffineYCoord.ToBigInteger(); BigInteger qSub1 = _q.Subtract(BigInteger.One); // 2. Check x and y coordinates are in Fq, i.e., x, y in [0, q-1] if (xCoord.CompareTo(BigInteger.Zero) == -1 || xCoord.CompareTo(qSub1) == 1 || yCoord.CompareTo(BigInteger.Zero) == -1 || yCoord.CompareTo(qSub1) == 1) { Debug.WriteLine("Point X coordinates not in Fq."); return false; } // 3. Check X lies on the curve try { if (X.IsValid() == false) { Debug.WriteLine("Point X not valid."); return false; } } catch (Exception e) { Debug.WriteLine("Check that point X is on curve failed.\n" + e.StackTrace); return false; } // 4. Check that nX = infinity. // It is equivalent - but more more efficient - to check the cofactor*X is not infinity. if (X.Multiply(_domain.Curve.Cofactor).IsInfinity) { Debug.WriteLine("X mult H (cofactor) == infinity"); return false; } // Now check if V = G*r + X*h. // Given that {G, X} are valid points on curve, the equality implies that V is also a point on curve. ECPoint Gr = BasePointMultiplier.Multiply(generator, r); ECPoint Xh = BasePointMultiplier.Multiply(X, h.Mod(_domain.Curve.Order)); if (V.Equals(Gr.Add(Xh)) == false) { return false; } // ZKP is valid return true; } /// <summary> /// Hashes a BigInteger into another BigInteger. /// </summary> private BigInteger Hash(BigInteger k) { _digest.Reset(); // Item is prefixed with its length as a little-endian 4-byte unsigned integer byte[] kBytes = k.ToByteArray(); var lengthPrefix = new byte[4]; Pack.UInt32_To_LE((uint) kBytes.Length, lengthPrefix); _digest.BlockUpdate(lengthPrefix, 0, 4); _digest.BlockUpdate(kBytes, 0, kBytes.Length); var hash = new byte[_digest.OutputSize]; _digest.DoFinal(hash, 0); return new BigInteger(1, hash); } /// <summary> /// Calculates the hash for a zero-knowledge proof. /// </summary> private BigInteger Hash(ECPoint generator, ECPoint V, ECPoint X, string participantId) { _digest.Reset(); // Each item is prefixed with its length as a little-endian 4-byte unsigned integer var lengthPrefix = new byte[4]; byte[] generatorBytes = generator.GetEncoded(); Pack.UInt32_To_LE((uint) generatorBytes.Length, lengthPrefix); _digest.BlockUpdate(lengthPrefix, 0, 4); _digest.BlockUpdate(generatorBytes, 0, generatorBytes.Length); byte[] vBytes = V.GetEncoded(); Pack.UInt32_To_LE((uint) vBytes.Length, lengthPrefix); _digest.BlockUpdate(lengthPrefix, 0, 4); _digest.BlockUpdate(vBytes, 0, vBytes.Length); byte[] xBytes = X.GetEncoded(); Pack.UInt32_To_LE((uint) xBytes.Length, lengthPrefix); _digest.BlockUpdate(lengthPrefix, 0, 4); _digest.BlockUpdate(xBytes, 0, xBytes.Length); byte[] idBytes = Encoding.UTF8.GetBytes(participantId); Pack.UInt32_To_LE((uint) idBytes.Length, lengthPrefix); _digest.BlockUpdate(lengthPrefix, 0, 4); _digest.BlockUpdate(idBytes, 0, idBytes.Length); var hash = new byte[_digest.OutputSize]; _digest.DoFinal(hash, 0); return new BigInteger(hash); } /// <summary> /// Calculates the MacTag for a key confirmation. /// </summary> /// <remarks> /// Calculates the MacTag (to be used for key confirmation), as defined by /// NIST SP 800-56A Revision 1, Section 8.2 Unilateral Key Confirmation for Key Agreement Schemes /// (http://csrc.nist.gov/publications/nistpubs/800-56A/SP800-56A_Revision1_Mar08-2007.pdf) /// <para>MacTag = HMAC(MacKey, MacLen, MacData)</para> /// <para>MacKey = H(K || "JPAKE_KC")</para> /// <para>MacData = "KC_1_U" || participantId || partnerParticipantId || gx1 || gx2 || gx3 || gx4</para> /// <para> /// Note that both participants use "KC_1_U" because the sender of the round 3 message is always /// the initiator for key confirmation. /// Participant identifiers and GX numbers are swapped symmetrically to calculate partner's value when /// performing verification in key confirmation. /// </para> /// </remarks> /// <returns>The MagTag.</returns> /// <param name="participantId">Participant identifier.</param> /// <param name="partnerParticipantId">Partner participant identifier.</param> /// <param name="gx1">GX1 (GX3 for partner).</param> /// <param name="gx2">GX2 (GX4 for partner).</param> /// <param name="gx3">GX3 (GX1 for partner).</param> /// <param name="gx4">GX4 (GX2 for partner).</param> /// <param name="keyingMaterial">Keying material.</param> private BigInteger CalculateMacTag(string participantId, string partnerParticipantId, ECPoint gx1, ECPoint gx2, ECPoint gx3, ECPoint gx4, BigInteger keyingMaterial) { _digest.Reset(); byte[] keyingMaterialBytes = keyingMaterial.ToByteArrayUnsigned(); _digest.BlockUpdate(keyingMaterialBytes, 0, keyingMaterialBytes.Length); // This constant is used to ensure that the mac key is NOT the same as the derived key. byte[] constantBytes = MacKeyConstantBytes; _digest.BlockUpdate(constantBytes, 0, constantBytes.Length); var macKey = new byte[_digest.OutputSize]; _digest.DoFinal(macKey, 0); // Create and initialise HMAC primitive var hmac = new Hmac(_digest); hmac.Init(macKey); macKey.SecureWipe(); macKey = null; // MacData = "KC_1_U" || participantId || partnerParticipantId || gx1 || gx2 || gx3 || gx4. byte[] protocolTag = MacTagConstantBytes; hmac.BlockUpdate(protocolTag, 0, protocolTag.Length); byte[] participantTag = Encoding.UTF8.GetBytes(participantId); hmac.BlockUpdate(participantTag, 0, participantTag.Length); byte[] partnerParticipantTag = Encoding.UTF8.GetBytes(partnerParticipantId); hmac.BlockUpdate(partnerParticipantTag, 0, partnerParticipantTag.Length); byte[] gx1Bytes = gx1.GetEncoded(); hmac.BlockUpdate(gx1Bytes, 0, gx1Bytes.Length); byte[] gx2Bytes = gx2.GetEncoded(); hmac.BlockUpdate(gx2Bytes, 0, gx2Bytes.Length); byte[] gx3Bytes = gx3.GetEncoded(); hmac.BlockUpdate(gx3Bytes, 0, gx3Bytes.Length); byte[] gx4Bytes = gx4.GetEncoded(); hmac.BlockUpdate(gx4Bytes, 0, gx4Bytes.Length); var macTag = new byte[hmac.OutputSize]; hmac.DoFinal(macTag, 0); return new BigInteger(macTag); } /// <summary> /// Possible states in the J-PAKE key agreement protocol. /// </summary> /// <remarks> /// Protocol progresses through these states sequentially. /// </remarks> public enum State : byte { Noninitialised = 0x00, Initialised = 0x01, Round1Created = 0x02, Round1Validated = 0x04, Round2Created = 0x08, Round2Validated = 0x10, //KeyCalculated = 0x20, Round3Created = 0x40, Round3Validated = 0x80 } public void Dispose() { if (_passwordBytes != null) { _passwordBytes.SecureWipe(); } _keyingMaterial = null; _macTag = null; _x2 = null; _gx1 = null; _gx2 = null; _gx3 = null; _gx4 = 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. using System; using System.Collections.Generic; using Xunit; namespace System.Net.Sockets.Tests { public class DisposedSocket { private static readonly byte[] s_buffer = new byte[1]; private static readonly IList<ArraySegment<byte>> s_buffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(s_buffer) }; private static readonly SocketAsyncEventArgs s_eventArgs = new SocketAsyncEventArgs(); private static Socket GetDisposedSocket(AddressFamily addressFamily = AddressFamily.InterNetwork) { using (var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp)) { return socket; } } private static void TheAsyncCallback(IAsyncResult ar) { } [Fact] public void Available_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Available); } [Fact] public void LocalEndPoint_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().LocalEndPoint); } [Fact] public void RemoteEndPoint_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().RemoteEndPoint); } [Fact] public void SetBlocking_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().Blocking = true; }); } [Fact] public void ExclusiveAddressUse_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ExclusiveAddressUse); } [Fact] public void SetExclusiveAddressUse_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().ExclusiveAddressUse = true; }); } [Fact] public void ReceiveBufferSize_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveBufferSize); } [Fact] public void SetReceiveBufferSize_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().ReceiveBufferSize = 1; }); } [Fact] public void SendBufferSize_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendBufferSize); } [Fact] public void SetSendBufferSize_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().SendBufferSize = 1; }); } [Fact] public void ReceiveTimeout_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveTimeout); } [Fact] public void SetReceiveTimeout_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().ReceiveTimeout = 1; }); } [Fact] public void SendTimeout_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTimeout); } [Fact] public void SetSendTimeout_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().SendTimeout = 1; }); } [Fact] public void LingerState_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().LingerState); } [Fact] public void SetLingerState_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().LingerState = new LingerOption(true, 1); }); } [Fact] public void NoDelay_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().NoDelay); } [Fact] public void SetNoDelay_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().NoDelay = true; }); } [Fact] public void Ttl_IPv4_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetwork).Ttl); } [Fact] public void SetTtl_IPv4_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket(AddressFamily.InterNetwork).Ttl = 1; }); } [Fact] public void Ttl_IPv6_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetworkV6).Ttl); } [Fact] public void SetTtl_IPv6_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket(AddressFamily.InterNetworkV6).Ttl = 1; }); } [Fact] public void DontFragment_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().DontFragment); } [Fact] public void SetDontFragment_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().DontFragment = true; }); } [Fact] public void MulticastLoopback_IPv4_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetwork).MulticastLoopback); } [Fact] public void SetMulticastLoopback_IPv4_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket(AddressFamily.InterNetwork).MulticastLoopback = true; }); } [Fact] public void MulticastLoopback_IPv6_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetworkV6).MulticastLoopback); } [Fact] public void SetMulticastLoopback_IPv6_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket(AddressFamily.InterNetworkV6).MulticastLoopback = true; }); } [Fact] public void EnableBroadcast_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EnableBroadcast); } [Fact] public void SetEnableBroadcast_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket().EnableBroadcast = true; }); } [Fact] public void DualMode_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetworkV6).DualMode); } [Fact] public void SetDualMode_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => { GetDisposedSocket(AddressFamily.InterNetworkV6).DualMode = true; }); } [Fact] public void Bind_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Bind(new IPEndPoint(IPAddress.Loopback, 0))); } [Fact] public void Connect_IPEndPoint_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Connect(new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void Connect_IPAddress_Port_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Connect(IPAddress.Loopback, 1)); } [Fact] public void Connect_Host_Port_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Connect("localhost", 1)); } [Fact] public void Connect_IPAddresses_Port_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Connect(new[] { IPAddress.Loopback }, 1)); } [Fact] public void Listen_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Listen(1)); } [Fact] public void Accept_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Accept()); } [Fact] public void Send_Buffer_Size_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer, s_buffer.Length, SocketFlags.None)); } [Fact] public void Send_Buffer_SocketFlags_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer, SocketFlags.None)); } [Fact] public void Send_Buffer_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer)); } [Fact] public void Send_Buffer_Offset_Size_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer, 0, s_buffer.Length, SocketFlags.None)); } [Fact] public void Send_Buffer_Offset_Size_SocketError_Throws_ObjectDisposed() { SocketError errorCode; Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer, 0, s_buffer.Length, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffers_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffers)); } [Fact] public void Send_Buffers_SocketFlags_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffers, SocketFlags.None)); } [Fact] public void Send_Buffers_SocketFlags_SocketError_Throws_ObjectDisposed() { SocketError errorCode; Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffers, SocketFlags.None, out errorCode)); } [Fact] public void SendTo_Buffer_Offset_Size_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTo(s_buffer, 0, s_buffer.Length, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void SendTo_Buffer_Size_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTo(s_buffer, s_buffer.Length, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void SendTo_Buffer_SocketFlags_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTo(s_buffer, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void SendTo_Buffer_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTo(s_buffer, new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void Receive_Buffer_Size_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer, s_buffer.Length, SocketFlags.None)); } [Fact] public void Receive_Buffer_SocketFlags_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer, SocketFlags.None)); } [Fact] public void Receive_Buffer_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer)); } [Fact] public void Receive_Buffer_Offset_Size_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer, 0, s_buffer.Length, SocketFlags.None)); } [Fact] public void Receive_Buffer_Offset_Size_SocketError_Throws_ObjectDisposed() { SocketError errorCode; Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer, 0, s_buffer.Length, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffers_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffers)); } [Fact] public void Receive_Buffers_SocketFlags_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffers, SocketFlags.None)); } [Fact] public void Receive_Buffers_SocketFlags_SocketError_Throws_ObjectDisposed() { SocketError errorCode; Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffers, SocketFlags.None, out errorCode)); } [Fact] public void ReceiveMessageFrom_Throws_ObjectDisposed() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveMessageFrom(s_buffer, 0, s_buffer.Length, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveFrom_Buffer_Offset_Size_Throws_ObjectDisposed() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFrom(s_buffer, 0, s_buffer.Length, SocketFlags.None, ref remote)); } [Fact] public void ReceiveFrom_Buffer_Size_Throws_ObjectDisposed() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFrom(s_buffer, s_buffer.Length, SocketFlags.None, ref remote)); } [Fact] public void ReceiveFrom_Buffer_SocketFlags_Throws_ObjectDisposed() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFrom(s_buffer, SocketFlags.None, ref remote)); } [Fact] public void ReceiveFrom_Buffer_Throws_ObjectDisposed() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFrom(s_buffer, ref remote)); } [Fact] public void Shutdown_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Shutdown(SocketShutdown.Both)); } [Fact] public void IOControl_Int_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().IOControl(0, s_buffer, s_buffer)); } [Fact] public void IOControl_IOControlCode_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().IOControl(IOControlCode.Flush, s_buffer, s_buffer)); } [Fact] public void SetSocketOption_Int_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, 0)); } [Fact] public void SetSocketOption_Buffer_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, s_buffer)); } [Fact] public void SetSocketOption_Bool_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, true)); } [Fact] public void SetSocketOption_Object_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 1))); } [Fact] public void GetSocketOption_Int_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, 4)); } [Fact] public void GetSocketOption_Buffer_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, s_buffer)); } [Fact] public void GetSocketOption_Object_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger)); } [Fact] public void Poll_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Poll(-1, SelectMode.SelectWrite)); } [Fact] public void AcceptAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().AcceptAsync(s_eventArgs)); } [Fact] public void ConnectAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ConnectAsync(s_eventArgs)); } [Fact] public void ReceiveAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveAsync(s_eventArgs)); } [Fact] public void ReceiveFromAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFromAsync(s_eventArgs)); } [Fact] public void ReceiveMessageFromAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveMessageFromAsync(s_eventArgs)); } [Fact] public void SendAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendAsync(s_eventArgs)); } [Fact] public void SendPacketsAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendPacketsAsync(s_eventArgs)); } [Fact] public void SendToAsync_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendToAsync(s_eventArgs)); } [Fact] public void BeginConnect_EndPoint_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginConnect(new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddress_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginConnect(IPAddress.Loopback, 1, TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddresses_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginConnect(new[] { IPAddress.Loopback }, 1, TheAsyncCallback, null)); } [Fact] public void BeginConnect_Host_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginConnect("localhost", 1, TheAsyncCallback, null)); } [Fact] public void EndConnect_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndConnect(null)); } [Fact] public void BeginSend_Buffer_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSend(s_buffer, 0, s_buffer.Length, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginSend_Buffer_SocketError_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSend(s_buffer, 0, s_buffer.Length, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginSend_Buffers_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSend(s_buffers, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginSend_Buffers_SocketError_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSend(s_buffers, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void EndSend_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndSend(null)); } [Fact] public void BeginSendTo_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginSendTo(s_buffer, 0, s_buffer.Length, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); } [Fact] public void EndSendTo_Throws_ObjectDisposedException() { // Behavior difference: EndSendTo_Throws_ObjectDisposed Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndSendTo(null)); } [Fact] public void BeginReceive_Buffer_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceive(s_buffer, 0, s_buffer.Length, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginReceive_Buffer_SocketError_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceive(s_buffer, 0, s_buffer.Length, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginReceive_Buffers_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceive(s_buffers, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginReceive_Buffers_SocketError_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceive(s_buffers, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void EndReceive_Throws_ObjectDisposedException() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndReceive(null)); } [Fact] public void BeginReceiveFrom_Throws_ObjectDisposedException() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceiveFrom(s_buffer, 0, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void EndReceiveFrom_Throws_ObjectDisposedException() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndReceiveFrom(null, ref remote)); } [Fact] public void BeginReceiveMessageFrom_Throws_ObjectDisposedException() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginReceiveMessageFrom(s_buffer, 0, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void EndReceiveMessageFrom_Throws_ObjectDisposedException() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void BeginAccept_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().BeginAccept(TheAsyncCallback, null)); } [Fact] public void EndAccept_Throws_ObjectDisposed() { Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EndAccept(null)); } } }
using System; using System.ComponentModel; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using MGTK.Controls; using MGTK.Messaging; using MGTK.Theming; using MGTK.Interfaces.Services; using MGTK.Factories; using MGTK.Interfaces.Providers; namespace MGTK.Services { public class WindowManager : IWindowManager { readonly GraphicsDevice _GraphicsDevice; Form _CurrentModalForm = null; public Form CurrentModalForm { get { return _CurrentModalForm; } internal set { _CurrentModalForm = value; } } public List<Form> Forms; public Theme Theme { get; set; } public int MouseX { get; set; } public int MouseY { get; set; } private bool _MouseLeftPressed = false; private bool _MouseRightPressed = false; public bool PreviousMouseLeftPressed = false; public bool PreviousMouseRightPressed = false; public bool MouseLeftPressed { get { return _MouseLeftPressed; } set { _MouseLeftPressed = value; } } public bool MouseRightPressed { get { return _MouseRightPressed; } set { _MouseRightPressed = value; } } public Texture2D MouseCursor { get; set; } private Keys[] PreviousKeysPressed = null; public SpriteBatch spriteBatch; public GameTime GameTime { get; set; } public int MaximizedWindowWidth { get; set; } public int MaximizedWindowHeight { get; set; } public int ScreenWidth { get; set; } public int ScreenHeight { get; set; } bool Initialized = false; private IDrawingService _DrawingService = null; public IDrawingService DrawingService { get { if (_DrawingService == null) _DrawingService = DrawingServiceFactory.GetSingletonInstance (); return _DrawingService; } set { _DrawingService = value; } } public WindowManager(GraphicsDevice graphicsDevice, int maximizedwindowwidth, int maximizedwindowheight) { _GraphicsDevice = graphicsDevice; ScreenWidth = MaximizedWindowWidth = maximizedwindowwidth; ScreenHeight = MaximizedWindowHeight = maximizedwindowheight; Forms = new List<Form>(); } public SpriteBatch GetSpriteBatch() { return spriteBatch; } public GraphicsDevice GetGraphicsDevice() { return _GraphicsDevice; } public void Draw(SpriteBatch sBatch) { spriteBatch = sBatch; InitializeFormsNotInitialized(); foreach (Form form in Forms) Messages.SendMessage(form, MessageEnum.Draw, null); if (MouseCursor != null) DrawingService.Draw(this, MouseCursor, new Vector2(MouseX, MouseY), Color.White, 0); } public void Update(GameTime gTime) { List<Form> formsQueue = Forms; GameTime = gTime; MouseCursor = Theme.DefaultCursor; MouseState ms = Mouse.GetState(); KeyboardState ks = Keyboard.GetState(); PreviousMouseLeftPressed = MouseLeftPressed; PreviousMouseRightPressed = MouseRightPressed; MouseX = ms.X; MouseY = ms.Y; if (!MouseLeftPressed && ms.LeftButton == ButtonState.Pressed) MouseLeftPressed = true; if (MouseLeftPressed && ms.LeftButton != ButtonState.Pressed) MouseLeftPressed = false; if (!MouseRightPressed && ms.RightButton == ButtonState.Pressed) MouseRightPressed = true; if (MouseRightPressed && ms.RightButton != ButtonState.Pressed) MouseRightPressed = false; if (formsQueue != null && formsQueue.Count > 0) { InitializeFormsNotInitialized(); if (CurrentModalForm != null) formsQueue = new List<Form>() { CurrentModalForm }; if (!PreviousMouseLeftPressed && MouseLeftPressed) Messages.BroadcastMessage(formsQueue, MessageEnum.MouseLeftPressed); if (!PreviousMouseRightPressed && MouseRightPressed) Messages.BroadcastMessage(formsQueue, MessageEnum.MouseRightPressed); if (ms.LeftButton == ButtonState.Pressed) Messages.BroadcastMessage(formsQueue, MessageEnum.MouseLeftDown); if (ms.RightButton == ButtonState.Pressed) Messages.BroadcastMessage(formsQueue, MessageEnum.MouseRightDown); if (!MouseLeftPressed && PreviousMouseLeftPressed == true) Messages.BroadcastMessage(formsQueue, MessageEnum.MouseLeftClick); if (!MouseRightPressed && PreviousMouseRightPressed == true) Messages.BroadcastMessage(formsQueue, MessageEnum.MouseRightClick); if (PreviousMouseLeftPressed && !MouseLeftPressed) Messages.BroadcastMessage(formsQueue, MessageEnum.MouseLeftUp); if (PreviousMouseRightPressed && !MouseRightPressed) Messages.BroadcastMessage(formsQueue, MessageEnum.MouseRightUp); Keys[] KeysPressed = ks.GetPressedKeys(); foreach (Keys keyPressed in KeysPressed) Messages.BroadcastMessage(formsQueue, MessageEnum.KeyDown, keyPressed); if (PreviousKeysPressed != null) { foreach (Keys keyPressed in PreviousKeysPressed) if (!KeysPressed.Contains(keyPressed)) Messages.BroadcastMessage(formsQueue, MessageEnum.KeyUp, keyPressed); } PreviousKeysPressed = KeysPressed; foreach (Form form in Forms)//formsQueue) Messages.SendMessage(form, MessageEnum.Logic, null); } } private void InitializeFormsNotInitialized() { if (Forms == null || Forms.Count == 0) return; foreach (Form form in Forms) { if (form.Initialized) continue; form.InitControl(); BringToFront(form); Messages.BroadcastMessage(Forms, MessageEnum.Init); } } public void BringToFront(Form form) { float interval = 1 / (float)Forms.Count; form.Z = interval; form.Focused = true; List<Form> FormsFiltered = Forms.FindAll(f => f != form); if (FormsFiltered != null) { float newZ = interval; FormsFiltered = FormsFiltered.OrderBy(f => f.Z).ToList(); foreach (Form f in FormsFiltered) { newZ += interval; f.Focused = false; f.Z = newZ; } } Forms = Forms.OrderBy(f => f.Z).ToList(); } public void AddForm(Form form) { AddForm(form, false); } public void AddForm(Form form, bool modal) { form.OnClose += (sender, e) => { if (CurrentModalForm == form) CurrentModalForm = null; Forms.Remove (form); }; Forms.Add (form); if (modal) CurrentModalForm = form; } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Cassandra.ProtocolEvents; using Cassandra.Responses; using Cassandra.Serialization; using Cassandra.SessionManagement; using Cassandra.Tasks; namespace Cassandra.Connections.Control { internal class ControlConnection : IControlConnection { private readonly IInternalCluster _cluster; private readonly Metadata _metadata; private volatile Host _host; private volatile IConnectionEndPoint _currentConnectionEndPoint; private volatile IConnection _connection; internal static readonly Logger Logger = new Logger(typeof(ControlConnection)); private readonly Configuration _config; private readonly IReconnectionPolicy _reconnectionPolicy; private IReconnectionSchedule _reconnectionSchedule; private readonly Timer _reconnectionTimer; private long _isShutdown; private int _refreshFlag; private Task<bool> _reconnectTask; private readonly ISerializerManager _serializer; private readonly IProtocolEventDebouncer _eventDebouncer; private readonly IEnumerable<IContactPoint> _contactPoints; private readonly ITopologyRefresher _topologyRefresher; private readonly ISupportedOptionsInitializer _supportedOptionsInitializer; private bool IsShutdown => Interlocked.Read(ref _isShutdown) > 0L; /// <summary> /// Gets the binary protocol version to be used for this cluster. /// </summary> public ProtocolVersion ProtocolVersion => _serializer.CurrentProtocolVersion; /// <inheritdoc /> public Host Host { get => _host; internal set => _host = value; } public IConnectionEndPoint EndPoint => _connection?.EndPoint; public IPEndPoint LocalAddress => _connection?.LocalAddress; public ISerializerManager Serializer => _serializer; internal ControlConnection( IInternalCluster cluster, IProtocolEventDebouncer eventDebouncer, ProtocolVersion initialProtocolVersion, Configuration config, Metadata metadata, IEnumerable<IContactPoint> contactPoints) { _cluster = cluster; _metadata = metadata; _reconnectionPolicy = config.Policies.ReconnectionPolicy; _reconnectionSchedule = _reconnectionPolicy.NewSchedule(); _reconnectionTimer = new Timer(ReconnectEventHandler, null, Timeout.Infinite, Timeout.Infinite); _config = config; _serializer = new SerializerManager(initialProtocolVersion, config.TypeSerializers); _eventDebouncer = eventDebouncer; _contactPoints = contactPoints; _topologyRefresher = config.TopologyRefresherFactory.Create(metadata, config); _supportedOptionsInitializer = config.SupportedOptionsInitializerFactory.Create(metadata); if (!_config.KeepContactPointsUnresolved) { TaskHelper.WaitToComplete(InitialContactPointResolutionAsync()); } } public void Dispose() { Shutdown(); } /// <inheritdoc /> public async Task InitAsync() { ControlConnection.Logger.Info("Trying to connect the ControlConnection"); await Connect(true).ConfigureAwait(false); } /// <summary> /// Resolves the contact points to a read only list of <see cref="IConnectionEndPoint"/> which will be used /// during initialization. Also sets <see cref="Metadata.SetResolvedContactPoints"/>. /// </summary> private async Task InitialContactPointResolutionAsync() { var tasksDictionary = _contactPoints.ToDictionary(c => c, c => c.GetConnectionEndPointsAsync(true)); await Task.WhenAll(tasksDictionary.Values).ConfigureAwait(false); var resolvedContactPoints = tasksDictionary.ToDictionary(t => t.Key, t => t.Value.Result); _metadata.SetResolvedContactPoints(resolvedContactPoints); if (!resolvedContactPoints.Any(kvp => kvp.Value.Any())) { var hostNames = tasksDictionary.Where(kvp => kvp.Key.CanBeResolved).Select(kvp => kvp.Key.StringRepresentation); throw new NoHostAvailableException($"No host name could be resolved, attempted: {string.Join(", ", hostNames)}"); } } private bool TotalConnectivityLoss() { var currentHosts = _metadata.AllHosts(); return currentHosts.Count(h => h.IsUp) == 0 || currentHosts.All(h => !_cluster.AnyOpenConnections(h)); } private async Task<IEnumerable<IConnectionEndPoint>> ResolveContactPoint(IContactPoint contactPoint, bool isInitializing) { var connectivityLoss = !isInitializing && TotalConnectivityLoss(); if (connectivityLoss && contactPoint.CanBeResolved) { ControlConnection.Logger.Warning( "Total connectivity loss detected due to the fact that there are no open connections, " + "re-resolving the following contact point: {0}", contactPoint.StringRepresentation); } var endpoints = await contactPoint.GetConnectionEndPointsAsync( _config.KeepContactPointsUnresolved || connectivityLoss).ConfigureAwait(false); return _metadata.UpdateResolvedContactPoint(contactPoint, endpoints); } private async Task<IEnumerable<IConnectionEndPoint>> ResolveHostContactPointOrConnectionEndpointAsync( ConcurrentDictionary<IContactPoint, object> attemptedContactPoints, Host host, bool isInitializing) { if (host.ContactPoint != null && attemptedContactPoints.TryAdd(host.ContactPoint, null)) { return await ResolveContactPoint(host.ContactPoint, isInitializing).ConfigureAwait(false); } var endpoint = await _config .EndPointResolver .GetConnectionEndPointAsync(host, TotalConnectivityLoss()) .ConfigureAwait(false); return new List<IConnectionEndPoint> { endpoint }; } private IEnumerable<Task<IEnumerable<IConnectionEndPoint>>> ContactPointResolutionTasksEnumerable( ConcurrentDictionary<IContactPoint, object> attemptedContactPoints, bool isInitializing) { foreach (var contactPoint in _contactPoints) { if (attemptedContactPoints.TryAdd(contactPoint, null)) { yield return ResolveContactPoint(contactPoint, isInitializing); } } } private IEnumerable<Task<IEnumerable<IConnectionEndPoint>>> AllHostsEndPointResolutionTasksEnumerable( ConcurrentDictionary<IContactPoint, object> attemptedContactPoints, ConcurrentDictionary<Host, object> attemptedHosts, bool isInitializing) { foreach (var host in GetHostEnumerable()) { if (attemptedHosts.TryAdd(host, null)) { if (!IsHostValid(host, isInitializing)) { continue; } yield return ResolveHostContactPointOrConnectionEndpointAsync(attemptedContactPoints, host, isInitializing); } } } private IEnumerable<Task<IEnumerable<IConnectionEndPoint>>> DefaultLbpHostsEnumerable( ConcurrentDictionary<IContactPoint, object> attemptedContactPoints, ConcurrentDictionary<Host, object> attemptedHosts, bool isInitializing) { foreach (var host in _config.DefaultRequestOptions.LoadBalancingPolicy.NewQueryPlan(null, null)) { if (attemptedHosts.TryAdd(host, null)) { if (!IsHostValid(host, isInitializing)) { continue; } yield return ResolveHostContactPointOrConnectionEndpointAsync(attemptedContactPoints, host, isInitializing); } } } private bool IsHostValid(Host host, bool initializing) { if (initializing) { return true; } if (_cluster.RetrieveAndSetDistance(host) == HostDistance.Ignored) { ControlConnection.Logger.Verbose("Skipping {0} because it is ignored.", host.Address.ToString()); return false; } if (!host.IsUp) { ControlConnection.Logger.Verbose("Skipping {0} because it is not UP.", host.Address.ToString()); return false; } return true; } /// <summary> /// Iterates through the query plan or hosts and tries to create a connection. /// Once a connection is made, topology metadata is refreshed and the ControlConnection is subscribed to Host /// and Connection events. /// </summary> /// <param name="isInitializing"> /// Determines whether the ControlConnection is connecting for the first time as part of the initialization. /// </param> /// <exception cref="NoHostAvailableException" /> /// <exception cref="DriverInternalError" /> private async Task Connect(bool isInitializing) { // lazy iterator of endpoints to try for the control connection IEnumerable<Task<IEnumerable<IConnectionEndPoint>>> endPointResolutionTasksLazyIterator = Enumerable.Empty<Task<IEnumerable<IConnectionEndPoint>>>(); var attemptedContactPoints = new ConcurrentDictionary<IContactPoint, object>(); var attemptedHosts = new ConcurrentDictionary<Host, object>(); // start with endpoints from the default LBP if it is already initialized if (!isInitializing) { endPointResolutionTasksLazyIterator = DefaultLbpHostsEnumerable(attemptedContactPoints, attemptedHosts, isInitializing); } // add contact points next endPointResolutionTasksLazyIterator = endPointResolutionTasksLazyIterator.Concat( ContactPointResolutionTasksEnumerable(attemptedContactPoints, isInitializing)); // finally add all hosts iterator, this will contain already tried hosts but we will check for it with the concurrent dictionary if (isInitializing) { endPointResolutionTasksLazyIterator = endPointResolutionTasksLazyIterator.Concat( AllHostsEndPointResolutionTasksEnumerable(attemptedContactPoints, attemptedHosts, isInitializing)); } var triedHosts = new Dictionary<IPEndPoint, Exception>(); foreach (var endPointResolutionTask in endPointResolutionTasksLazyIterator) { var endPoints = await endPointResolutionTask.ConfigureAwait(false); foreach (var endPoint in endPoints) { ControlConnection.Logger.Verbose("Attempting to connect to {0}.", endPoint.EndpointFriendlyName); var connection = _config.ConnectionFactory.CreateUnobserved(_serializer.GetCurrentSerializer(), endPoint, _config); try { var version = _serializer.CurrentProtocolVersion; try { await connection.Open().ConfigureAwait(false); } catch (UnsupportedProtocolVersionException ex) { if (!isInitializing) { // The version of the protocol is not supported on this host // Most likely, we are using a higher protocol version than the host supports ControlConnection.Logger.Warning("Host {0} does not support protocol version {1}. You should use a fixed protocol " + "version during rolling upgrades of the cluster. " + "Skipping this host on the current attempt to open the control connection.", endPoint.EndpointFriendlyName, ex.ProtocolVersion); throw; } connection = await _config.ProtocolVersionNegotiator.ChangeProtocolVersion( _config, _serializer, ex.ResponseProtocolVersion, connection, ex, version) .ConfigureAwait(false); } _connection = connection; //// We haven't used a CAS operation, so it's possible that the control connection is //// being closed while a reconnection attempt is happening, we should dispose it in that case. if (IsShutdown) { ControlConnection.Logger.Info( "Connection established to {0} successfully but the Control Connection was being disposed, " + "closing the connection.", connection.EndPoint.EndpointFriendlyName); throw new ObjectDisposedException("Connection established successfully but the Control Connection was being disposed."); } ControlConnection.Logger.Info( "Connection established to {0} using protocol version {1}.", connection.EndPoint.EndpointFriendlyName, _serializer.CurrentProtocolVersion.ToString("D")); if (isInitializing) { await _supportedOptionsInitializer.ApplySupportedOptionsAsync(connection).ConfigureAwait(false); } var currentHost = await _topologyRefresher.RefreshNodeListAsync( endPoint, connection, _serializer.GetCurrentSerializer()).ConfigureAwait(false); SetCurrentConnection(currentHost, endPoint); if (isInitializing) { await _config.ProtocolVersionNegotiator.NegotiateVersionAsync( _config, _metadata, connection, _serializer).ConfigureAwait(false); } await _config.ServerEventsSubscriber.SubscribeToServerEvents(connection, OnConnectionCassandraEvent).ConfigureAwait(false); await _metadata.RebuildTokenMapAsync(false, _config.MetadataSyncOptions.MetadataSyncEnabled).ConfigureAwait(false); _host.Down += OnHostDown; return; } catch (Exception ex) { connection.Dispose(); if (ex is ObjectDisposedException) { throw; } if (IsShutdown) { throw new ObjectDisposedException("Control Connection has been disposed.", ex); } ControlConnection.Logger.Info("Failed to connect to {0}. Exception: {1}", endPoint.EndpointFriendlyName, ex.ToString()); // There was a socket or authentication exception or an unexpected error triedHosts[endPoint.GetHostIpEndPointWithFallback()] = ex; } } } throw new NoHostAvailableException(triedHosts); } private async void ReconnectEventHandler(object state) { try { await Reconnect().ConfigureAwait(false); } catch (Exception ex) { ControlConnection.Logger.Error("An exception was thrown when reconnecting the control connection.", ex); } } internal async Task<bool> Reconnect() { var tcs = new TaskCompletionSource<bool>(); var currentTask = Interlocked.CompareExchange(ref _reconnectTask, tcs.Task, null); if (currentTask != null) { // If there is another thread reconnecting, use the same task return await currentTask.ConfigureAwait(false); } Unsubscribe(); var oldConnection = _connection; try { ControlConnection.Logger.Info("Trying to reconnect the ControlConnection"); await Connect(false).ConfigureAwait(false); } catch (Exception ex) { // It failed to reconnect, schedule the timer for next reconnection and let go. var _ = Interlocked.Exchange(ref _reconnectTask, null); tcs.TrySetException(ex); var delay = _reconnectionSchedule.NextDelayMs(); ControlConnection.Logger.Error("ControlConnection was not able to reconnect: " + ex); try { _reconnectionTimer.Change((int)delay, Timeout.Infinite); } catch (ObjectDisposedException) { //Control connection is being disposed } // It will throw the same exception that it was set in the TCS throw; } finally { if (_connection != oldConnection) { oldConnection.Dispose(); } } if (IsShutdown) { tcs.TrySetResult(false); return false; } try { _reconnectionSchedule = _reconnectionPolicy.NewSchedule(); tcs.TrySetResult(true); var _ = Interlocked.Exchange(ref _reconnectTask, null); ControlConnection.Logger.Info("ControlConnection reconnected to host {0}", _host.Address); } catch (Exception ex) { var _ = Interlocked.Exchange(ref _reconnectTask, null); ControlConnection.Logger.Error("There was an error when trying to refresh the ControlConnection", ex); tcs.TrySetException(ex); try { _reconnectionTimer.Change((int)_reconnectionSchedule.NextDelayMs(), Timeout.Infinite); } catch (ObjectDisposedException) { //Control connection is being disposed } } return await tcs.Task.ConfigureAwait(false); } private async Task Refresh() { if (Interlocked.CompareExchange(ref _refreshFlag, 1, 0) != 0) { // Only one refresh at a time return; } var reconnect = false; try { var currentEndPoint = _currentConnectionEndPoint; var currentHost = await _topologyRefresher.RefreshNodeListAsync( currentEndPoint, _connection, _serializer.GetCurrentSerializer()).ConfigureAwait(false); SetCurrentConnection(currentHost, currentEndPoint); await _metadata.RebuildTokenMapAsync(false, _config.MetadataSyncOptions.MetadataSyncEnabled).ConfigureAwait(false); _reconnectionSchedule = _reconnectionPolicy.NewSchedule(); } catch (SocketException ex) { ControlConnection.Logger.Error("There was a SocketException when trying to refresh the ControlConnection", ex); reconnect = true; } catch (Exception ex) { ControlConnection.Logger.Error("There was an error when trying to refresh the ControlConnection", ex); } finally { Interlocked.Exchange(ref _refreshFlag, 0); } if (reconnect) { await Reconnect().ConfigureAwait(false); } } public void Shutdown() { if (Interlocked.Increment(ref _isShutdown) != 1) { //Only shutdown once return; } var c = _connection; if (c != null) { ControlConnection.Logger.Info("Shutting down control connection to {0}", c.EndPoint.EndpointFriendlyName); c.Dispose(); } _reconnectionTimer.Change(Timeout.Infinite, Timeout.Infinite); _reconnectionTimer.Dispose(); } /// <summary> /// Unsubscribe from the current host 'Down' event. /// </summary> private void Unsubscribe() { var h = _host; if (h != null) { h.Down -= OnHostDown; } } private void OnHostDown(Host h) { h.Down -= OnHostDown; ControlConnection.Logger.Warning("Host {0} used by the ControlConnection DOWN", h.Address); // Queue reconnection to occur in the background Task.Run(Reconnect).Forget(); } private async void OnConnectionCassandraEvent(object sender, CassandraEventArgs e) { try { //This event is invoked from a worker thread (not a IO thread) if (e is TopologyChangeEventArgs tce) { if (tce.What == TopologyChangeEventArgs.Reason.NewNode || tce.What == TopologyChangeEventArgs.Reason.RemovedNode) { // Start refresh await ScheduleHostsRefreshAsync().ConfigureAwait(false); return; } } if (e is StatusChangeEventArgs args) { HandleStatusChangeEvent(args); return; } if (e is SchemaChangeEventArgs ssc) { await HandleSchemaChangeEvent(ssc, false).ConfigureAwait(false); } } catch (Exception ex) { ControlConnection.Logger.Error("Exception thrown while handling cassandra event.", ex); } } /// <inheritdoc /> public Task HandleSchemaChangeEvent(SchemaChangeEventArgs ssc, bool processNow) { if (!_config.MetadataSyncOptions.MetadataSyncEnabled) { return TaskHelper.Completed; } Func<Task> handler; if (!string.IsNullOrEmpty(ssc.Table)) { handler = () => { //Can be either a table or a view _metadata.ClearTable(ssc.Keyspace, ssc.Table); _metadata.ClearView(ssc.Keyspace, ssc.Table); return TaskHelper.Completed; }; } else if (ssc.FunctionName != null) { handler = TaskHelper.ActionToAsync(() => _metadata.ClearFunction(ssc.Keyspace, ssc.FunctionName, ssc.Signature)); } else if (ssc.AggregateName != null) { handler = TaskHelper.ActionToAsync(() => _metadata.ClearAggregate(ssc.Keyspace, ssc.AggregateName, ssc.Signature)); } else if (ssc.Type != null) { return TaskHelper.Completed; } else if (ssc.What == SchemaChangeEventArgs.Reason.Dropped) { handler = TaskHelper.ActionToAsync(() => _metadata.RemoveKeyspace(ssc.Keyspace)); } else { return ScheduleKeyspaceRefreshAsync(ssc.Keyspace, processNow); } return ScheduleObjectRefreshAsync(ssc.Keyspace, processNow, handler); } private void HandleStatusChangeEvent(StatusChangeEventArgs e) { //The address in the Cassandra event message needs to be translated var address = TranslateAddress(e.Address); ControlConnection.Logger.Info("Received Node status change event: host {0} is {1}", address, e.What.ToString().ToUpper()); if (!_metadata.Hosts.TryGet(address, out var host)) { ControlConnection.Logger.Info("Received status change event for host {0} but it was not found", address); return; } var distance = _cluster.RetrieveAndSetDistance(host); if (distance != HostDistance.Ignored) { // We should not consider events for status changes // We should trust the pools. return; } if (e.What == StatusChangeEventArgs.Reason.Up) { host.BringUpIfDown(); return; } host.SetDown(); } private IPEndPoint TranslateAddress(IPEndPoint value) { return _config.AddressTranslator.Translate(value); } private void SetCurrentConnection(Host host, IConnectionEndPoint endPoint) { _host = host; _currentConnectionEndPoint = endPoint; _metadata.SetCassandraVersion(host.CassandraVersion); } /// <summary> /// Uses the active connection to execute a query /// </summary> public IEnumerable<IRow> Query(string cqlQuery, bool retry = false) { return TaskHelper.WaitToComplete(QueryAsync(cqlQuery, retry), _config.SocketOptions.MetadataAbortTimeout); } public async Task<IEnumerable<IRow>> QueryAsync(string cqlQuery, bool retry = false) { return _config.MetadataRequestHandler.GetRowSet( await SendQueryRequestAsync(cqlQuery, retry, QueryProtocolOptions.Default).ConfigureAwait(false)); } public async Task<Response> SendQueryRequestAsync(string cqlQuery, bool retry, QueryProtocolOptions queryProtocolOptions) { Response response; try { response = await _config.MetadataRequestHandler.SendMetadataRequestAsync( _connection, _serializer.GetCurrentSerializer(), cqlQuery, queryProtocolOptions).ConfigureAwait(false); } catch (SocketException) { if (!retry) { throw; } // Try reconnect await Reconnect().ConfigureAwait(false); // Query with retry set to false return await SendQueryRequestAsync(cqlQuery, false, queryProtocolOptions).ConfigureAwait(false); } return response; } /// <inheritdoc /> public Task<Response> UnsafeSendQueryRequestAsync(string cqlQuery, QueryProtocolOptions queryProtocolOptions) { return _config.MetadataRequestHandler.UnsafeSendQueryRequestAsync( _connection, _serializer.GetCurrentSerializer(), cqlQuery, queryProtocolOptions); } /// <summary> /// An iterator designed for the underlying collection to change /// </summary> private IEnumerable<Host> GetHostEnumerable() { var index = 0; var hosts = _metadata.Hosts.ToArray(); while (index < hosts.Length) { yield return hosts[index++]; // Check that the collection changed var newHosts = _metadata.Hosts.ToCollection(); if (newHosts.Count != hosts.Length) { index = 0; hosts = newHosts.ToArray(); } } } /// <inheritdoc /> public async Task HandleKeyspaceRefreshLaterAsync(string keyspace) { var @event = new KeyspaceProtocolEvent(true, keyspace, async () => { await _metadata.RefreshSingleKeyspace(keyspace).ConfigureAwait(false); }); await _eventDebouncer.HandleEventAsync(@event, false).ConfigureAwait(false); } /// <inheritdoc /> public Task ScheduleKeyspaceRefreshAsync(string keyspace, bool processNow) { var @event = new KeyspaceProtocolEvent(true, keyspace, () => _metadata.RefreshSingleKeyspace(keyspace)); return processNow ? _eventDebouncer.HandleEventAsync(@event, true) : _eventDebouncer.ScheduleEventAsync(@event, false); } private Task ScheduleObjectRefreshAsync(string keyspace, bool processNow, Func<Task> handler) { var @event = new KeyspaceProtocolEvent(false, keyspace, handler); return processNow ? _eventDebouncer.HandleEventAsync(@event, true) : _eventDebouncer.ScheduleEventAsync(@event, false); } private Task ScheduleHostsRefreshAsync() { return _eventDebouncer.ScheduleEventAsync(new ProtocolEvent(Refresh), false); } /// <inheritdoc /> public Task ScheduleAllKeyspacesRefreshAsync(bool processNow) { var @event = new ProtocolEvent(() => _metadata.RebuildTokenMapAsync(false, true)); return processNow ? _eventDebouncer.HandleEventAsync(@event, true) : _eventDebouncer.ScheduleEventAsync(@event, false); } } }
using System; using System.IO; using System.Text; using System.Drawing; using System.Collections; using System.Security.Cryptography; using System.Collections.Generic; using System.Windows.Forms; public class MyPassword : Form { // ---------------------------------------------------------------- // GUI // ---------------------------------------------------------------- private Label m_labelPassword; private TextBox m_textPassword; private Button m_buttonOK; private Label m_labelNewPassword; private TextBox m_textNewPassword; public MyPassword() { this.Text = "Meine Vergessen"; this.Size = new Size(400, 155); this.MinimumSize = new Size(400, 155); this.MaximumSize = new Size(400, 155); // label m_labelPassword = new Label(); m_labelPassword.Parent = this; m_labelPassword.Name = "labelPassword"; m_labelPassword.Text = "Vergessen:"; m_labelPassword.Location = new Point(10, 12); m_labelPassword.Size = new Size (110, 25); // password m_textPassword = new TextBox(); m_textPassword.Parent = this; m_textPassword.ReadOnly = false; m_textPassword.Name = "textBoxKey"; m_textPassword.Text = "Ihr Passwort"; m_textPassword.Location = new Point(120, 10); m_textPassword.Size = new Size (250, 50); m_textPassword.TextChanged += new EventHandler(buttonGenerate_Click); this.Controls.Add(m_textPassword); // button m_buttonOK = new Button(); m_buttonOK.Parent = this; m_buttonOK.Name = "buttonOK"; m_buttonOK.Text = "OK"; m_buttonOK.Location = new Point(120, 47); m_buttonOK.Size = new Size (150, 27); m_buttonOK.Click += new EventHandler(buttonGenerate_Click); this.Controls.Add(m_buttonOK); // label m_labelNewPassword = new Label(); m_labelNewPassword.Parent = this; m_labelNewPassword.Name = "labelInstallationCode"; m_labelNewPassword.Text = "Neue Vergessen:"; m_labelNewPassword.Location = new Point(10, 92); m_labelNewPassword.Size = new Size (110, 25); // new password m_textNewPassword = new TextBox(); m_textNewPassword.Parent = this; m_textNewPassword.ReadOnly = true; m_textNewPassword.Name = "textBoxNewPassword"; m_textNewPassword.Text = generateRandomPassword(); // m_textNewPassword.Text = getNewPassword(); m_textNewPassword.Location = new Point(120, 92); m_textNewPassword.Size = new Size (250, 25); CenterToScreen(); } // ---------------------------------------------------------------- private void buttonGenerate_Click(object sender, EventArgs e) { if (m_textPassword.Text == getPassword()) m_textNewPassword.Text = getNewPassword(); else m_textNewPassword.Text = generateRandomPassword(); } // ---------------------------------------------------------------- static string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; // ---------------------------------------------------------------- static public void Main() { Application.Run(new MyPassword()); } // ---------------------------------------------------------------- private int getChar(string s) { for (int i = 0; i < chars.Length; i++) { if (chars[i] == s[0]) return i; } return 0; } private string getPassword() { var stringChars = new char[10]; // mY68cRe7P2 stringChars[0] = chars[38]; // m stringChars[1] = chars[24]; // Y stringChars[2] = chars[getChar("6")]; stringChars[3] = chars[getChar("8")]; stringChars[4] = chars[getChar("c")]; stringChars[5] = chars[getChar("R")]; stringChars[6] = chars[getChar("e")]; stringChars[7] = chars[getChar("7")]; stringChars[8] = chars[getChar("P")]; stringChars[9] = chars[getChar("2")]; return new string(stringChars); } // ---------------------------------------------------------------- private void generateCode(string s) { Console.WriteLine("\t\tvar s = new char[{0}];", s.Length); Random random = new Random((int)DateTime.Now.Ticks); int n = random.Next(chars.Length); Console.WriteLine("\t\tint n = {0};", n); for (int i = 0; i < s.Length; i++) { int nChar = getChar(s[i].ToString()); int nMethod = random.Next(3); if (nMethod == 0) { if (nChar > n) { Console.WriteLine("\t\tn = n + {0};", nChar - n); } else if (n > nChar) { Console.WriteLine("\t\tn = n - {0};", n - nChar); }; } else { int n1 = 1; int n2 = 1; int n3 = 0; int n4 = 0; while (n3 < (chars.Length + nChar)) { n1 = random.Next(10) + 4; n2 = random.Next(10) + 2; n3 = n2*(n + n1); n4 = 1; while ((n3 % n4) != nChar) { if (n4 > 1000) { break; } n4++; } if (n3 % n4 == nChar) { break; } n3 = 1; } Console.WriteLine("\t\tn = ({0}*(n + {1})) % {2};", n2, n1, n4); } n = nChar; Console.WriteLine("\t\ts[{0}] = chars[n];", i); } Console.WriteLine("\t\treturn \"flagis\" + new string(s);"); } // ---------------------------------------------------------------- private string getNewPassword() { // generateCode("foxes5ayHumansMu5tD1e"); var s = new char[21]; int n = 14; n = (3*(n + 11)) % 44; s[0] = chars[n]; n = n + 9; s[1] = chars[n]; n = (9*(n + 13)) % 107; s[2] = chars[n]; n = n - 19; s[3] = chars[n]; n = (3*(n + 10)) % 76; s[4] = chars[n]; n = (7*(n + 8)) % 307; s[5] = chars[n]; n = n - 31; s[6] = chars[n]; n = (10*(n + 9)) % 60; s[7] = chars[n]; n = (5*(n + 8)) % 283; s[8] = chars[n]; n = (10*(n + 5)) % 74; s[9] = chars[n]; n = n - 8; s[10] = chars[n]; n = n - 12; s[11] = chars[n]; n = (10*(n + 8)) % 43; s[12] = chars[n]; n = (2*(n + 11)) % 56; s[13] = chars[n]; n = n - 32; s[14] = chars[n]; n = (11*(n + 6)) % 76; s[15] = chars[n]; n = (11*(n + 4)) % 493; s[16] = chars[n]; n = (4*(n + 7)) % 211; s[17] = chars[n]; n = (6*(n + 10)) % 109; s[18] = chars[n]; n = n + 50; s[19] = chars[n]; n = n - 23; s[20] = chars[n]; return "flagis" + new string(s); } // ---------------------------------------------------------------- private string generateRandomPassword() { var stringChars = new char[27]; Random random = new Random((int)DateTime.Now.Ticks); for (int i = 0; i < stringChars.Length; i++) { stringChars[i] = chars[random.Next(chars.Length)]; } return new string(stringChars); } }
namespace android.bluetooth { [global::MonoJavaBridge.JavaClass()] public sealed partial class BluetoothDevice : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal BluetoothDevice(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public sealed override bool equals(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.bluetooth.BluetoothDevice.staticClass, "equals", "(Ljava/lang/Object;)Z", ref global::android.bluetooth.BluetoothDevice._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public sealed override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.bluetooth.BluetoothDevice.staticClass, "toString", "()Ljava/lang/String;", ref global::android.bluetooth.BluetoothDevice._m1) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m2; public sealed override int hashCode() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.bluetooth.BluetoothDevice.staticClass, "hashCode", "()I", ref global::android.bluetooth.BluetoothDevice._m2); } public new global::java.lang.String Address { get { return getAddress(); } } private static global::MonoJavaBridge.MethodId _m3; public global::java.lang.String getAddress() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.bluetooth.BluetoothDevice.staticClass, "getAddress", "()Ljava/lang/String;", ref global::android.bluetooth.BluetoothDevice._m3) as java.lang.String; } public new global::java.lang.String Name { get { return getName(); } } private static global::MonoJavaBridge.MethodId _m4; public global::java.lang.String getName() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.bluetooth.BluetoothDevice.staticClass, "getName", "()Ljava/lang/String;", ref global::android.bluetooth.BluetoothDevice._m4) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m5; public void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.bluetooth.BluetoothDevice.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V", ref global::android.bluetooth.BluetoothDevice._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m6; public int describeContents() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.bluetooth.BluetoothDevice.staticClass, "describeContents", "()I", ref global::android.bluetooth.BluetoothDevice._m6); } public new int BondState { get { return getBondState(); } } private static global::MonoJavaBridge.MethodId _m7; public int getBondState() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.bluetooth.BluetoothDevice.staticClass, "getBondState", "()I", ref global::android.bluetooth.BluetoothDevice._m7); } public new global::android.bluetooth.BluetoothClass BluetoothClass { get { return getBluetoothClass(); } } private static global::MonoJavaBridge.MethodId _m8; public global::android.bluetooth.BluetoothClass getBluetoothClass() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.bluetooth.BluetoothClass>(this, global::android.bluetooth.BluetoothDevice.staticClass, "getBluetoothClass", "()Landroid/bluetooth/BluetoothClass;", ref global::android.bluetooth.BluetoothDevice._m8) as android.bluetooth.BluetoothClass; } private static global::MonoJavaBridge.MethodId _m9; public global::android.bluetooth.BluetoothSocket createRfcommSocketToServiceRecord(java.util.UUID arg0) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.bluetooth.BluetoothSocket>(this, global::android.bluetooth.BluetoothDevice.staticClass, "createRfcommSocketToServiceRecord", "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothSocket;", ref global::android.bluetooth.BluetoothDevice._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.bluetooth.BluetoothSocket; } public static int ERROR { get { return -2147483648; } } public static global::java.lang.String ACTION_FOUND { get { return "android.bluetooth.device.action.FOUND"; } } public static global::java.lang.String ACTION_CLASS_CHANGED { get { return "android.bluetooth.device.action.CLASS_CHANGED"; } } public static global::java.lang.String ACTION_ACL_CONNECTED { get { return "android.bluetooth.device.action.ACL_CONNECTED"; } } public static global::java.lang.String ACTION_ACL_DISCONNECT_REQUESTED { get { return "android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED"; } } public static global::java.lang.String ACTION_ACL_DISCONNECTED { get { return "android.bluetooth.device.action.ACL_DISCONNECTED"; } } public static global::java.lang.String ACTION_NAME_CHANGED { get { return "android.bluetooth.device.action.NAME_CHANGED"; } } public static global::java.lang.String ACTION_BOND_STATE_CHANGED { get { return "android.bluetooth.device.action.BOND_STATE_CHANGED"; } } public static global::java.lang.String EXTRA_DEVICE { get { return "android.bluetooth.device.extra.DEVICE"; } } public static global::java.lang.String EXTRA_NAME { get { return "android.bluetooth.device.extra.NAME"; } } public static global::java.lang.String EXTRA_RSSI { get { return "android.bluetooth.device.extra.RSSI"; } } public static global::java.lang.String EXTRA_CLASS { get { return "android.bluetooth.device.extra.CLASS"; } } public static global::java.lang.String EXTRA_BOND_STATE { get { return "android.bluetooth.device.extra.BOND_STATE"; } } public static global::java.lang.String EXTRA_PREVIOUS_BOND_STATE { get { return "android.bluetooth.device.extra.PREVIOUS_BOND_STATE"; } } public static int BOND_NONE { get { return 10; } } public static int BOND_BONDING { get { return 11; } } public static int BOND_BONDED { get { return 12; } } internal static global::MonoJavaBridge.FieldId _CREATOR1605; public static global::android.os.Parcelable_Creator CREATOR { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable_Creator>(@__env.GetStaticObjectField(global::android.bluetooth.BluetoothDevice.staticClass, _CREATOR1605)) as android.os.Parcelable_Creator; } } static BluetoothDevice() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.bluetooth.BluetoothDevice.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/bluetooth/BluetoothDevice")); global::android.bluetooth.BluetoothDevice._CREATOR1605 = @__env.GetStaticFieldIDNoThrow(global::android.bluetooth.BluetoothDevice.staticClass, "CREATOR", "Landroid/os/Parcelable$Creator;"); } } }
/* * 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.Tests.Cache.Store { using System; using System.Collections; using System.Collections.Generic; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Portable; using NUnit.Framework; /// <summary> /// /// </summary> class Key { private readonly int _idx; public Key(int idx) { _idx = idx; } public int Index() { return _idx; } public override bool Equals(object obj) { if (obj == null || obj.GetType() != GetType()) return false; Key key = (Key)obj; return key._idx == _idx; } public override int GetHashCode() { return _idx; } } /// <summary> /// /// </summary> class Value { private int _idx; public Value(int idx) { _idx = idx; } public int Index() { return _idx; } } /// <summary> /// Cache entry predicate. /// </summary> [Serializable] public class CacheEntryFilter : ICacheEntryFilter<int, string> { /** <inheritdoc /> */ public bool Invoke(ICacheEntry<int, string> entry) { return entry.Key >= 105; } } /// <summary> /// /// </summary> public class CacheStoreTest { /** */ private const string PortableStoreCacheName = "portable_store"; /** */ private const string ObjectStoreCacheName = "object_store"; /** */ private const string CustomStoreCacheName = "custom_store"; /** */ private const string TemplateStoreCacheName = "template_store*"; /// <summary> /// /// </summary> [TestFixtureSetUp] public void BeforeTests() { //TestUtils.JVM_DEBUG = true; TestUtils.KillProcesses(); TestUtils.JvmDebug = true; IgniteConfigurationEx cfg = new IgniteConfigurationEx(); cfg.GridName = GridName(); cfg.JvmClasspath = TestUtils.CreateTestClasspath(); cfg.JvmOptions = TestUtils.TestJavaOptions(); cfg.SpringConfigUrl = "config\\native-client-test-cache-store.xml"; PortableConfiguration portCfg = new PortableConfiguration(); portCfg.Types = new List<string> { typeof(Key).FullName, typeof(Value).FullName }; cfg.PortableConfiguration = portCfg; Ignition.Start(cfg); } /// <summary> /// /// </summary> [TestFixtureTearDown] public virtual void AfterTests() { Ignition.StopAll(true); } /// <summary> /// /// </summary> [SetUp] public void BeforeTest() { Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name); } /// <summary> /// /// </summary> [TearDown] public void AfterTest() { var cache = Cache(); cache.Clear(); Assert.IsTrue(cache.IsEmpty, "Cache is not empty: " + cache.Size()); CacheTestStore.Reset(); Console.WriteLine("Test finished: " + TestContext.CurrentContext.Test.Name); } [Test] public void TestLoadCache() { var cache = Cache(); Assert.AreEqual(0, cache.Size()); cache.LoadCache(new CacheEntryFilter(), 100, 10); Assert.AreEqual(5, cache.Size()); for (int i = 105; i < 110; i++) Assert.AreEqual("val_" + i, cache.Get(i)); } [Test] public void TestLocalLoadCache() { var cache = Cache(); Assert.AreEqual(0, cache.Size()); cache.LocalLoadCache(new CacheEntryFilter(), 100, 10); Assert.AreEqual(5, cache.Size()); for (int i = 105; i < 110; i++) Assert.AreEqual("val_" + i, cache.Get(i)); } [Test] public void TestLoadCacheMetadata() { CacheTestStore.LoadObjects = true; var cache = Cache(); Assert.AreEqual(0, cache.Size()); cache.LocalLoadCache(null, 0, 3); Assert.AreEqual(3, cache.Size()); var meta = cache.WithKeepPortable<Key, IPortableObject>().Get(new Key(0)).Metadata(); Assert.NotNull(meta); Assert.AreEqual("Value", meta.TypeName); } [Test] public void TestLoadCacheAsync() { var cache = Cache().WithAsync(); Assert.AreEqual(0, cache.Size()); cache.LocalLoadCache(new CacheEntryFilter(), 100, 10); var fut = cache.GetFuture<object>(); fut.Get(); Assert.IsTrue(fut.IsDone); cache.Size(); Assert.AreEqual(5, cache.GetFuture<int>().ToTask().Result); for (int i = 105; i < 110; i++) { cache.Get(i); Assert.AreEqual("val_" + i, cache.GetFuture<string>().ToTask().Result); } } [Test] public void TestPutLoad() { var cache = Cache(); cache.Put(1, "val"); IDictionary map = StoreMap(); Assert.AreEqual(1, map.Count); cache.LocalEvict(new[] { 1 }); Assert.AreEqual(0, cache.Size()); Assert.AreEqual("val", cache.Get(1)); Assert.AreEqual(1, cache.Size()); } [Test] public void TestPutLoadPortables() { var cache = PortableStoreCache<int, Value>(); cache.Put(1, new Value(1)); IDictionary map = StoreMap(); Assert.AreEqual(1, map.Count); IPortableObject v = (IPortableObject)map[1]; Assert.AreEqual(1, v.Field<int>("_idx")); cache.LocalEvict(new[] { 1 }); Assert.AreEqual(0, cache.Size()); Assert.AreEqual(1, cache.Get(1).Index()); Assert.AreEqual(1, cache.Size()); } [Test] public void TestPutLoadObjects() { var cache = ObjectStoreCache<int, Value>(); cache.Put(1, new Value(1)); IDictionary map = StoreMap(); Assert.AreEqual(1, map.Count); Value v = (Value)map[1]; Assert.AreEqual(1, v.Index()); cache.LocalEvict(new[] { 1 }); Assert.AreEqual(0, cache.Size()); Assert.AreEqual(1, cache.Get(1).Index()); Assert.AreEqual(1, cache.Size()); } [Test] public void TestPutLoadAll() { var putMap = new Dictionary<int, string>(); for (int i = 0; i < 10; i++) putMap.Add(i, "val_" + i); var cache = Cache(); cache.PutAll(putMap); IDictionary map = StoreMap(); Assert.AreEqual(10, map.Count); for (int i = 0; i < 10; i++) Assert.AreEqual("val_" + i, map[i]); cache.Clear(); Assert.AreEqual(0, cache.Size()); ICollection<int> keys = new List<int>(); for (int i = 0; i < 10; i++) keys.Add(i); IDictionary<int, string> loaded = cache.GetAll(keys); Assert.AreEqual(10, loaded.Count); for (int i = 0; i < 10; i++) Assert.AreEqual("val_" + i, loaded[i]); Assert.AreEqual(10, cache.Size()); } [Test] public void TestRemove() { var cache = Cache(); for (int i = 0; i < 10; i++) cache.Put(i, "val_" + i); IDictionary map = StoreMap(); Assert.AreEqual(10, map.Count); for (int i = 0; i < 5; i++) cache.Remove(i); Assert.AreEqual(5, map.Count); for (int i = 5; i < 10; i++) Assert.AreEqual("val_" + i, map[i]); } [Test] public void TestRemoveAll() { var cache = Cache(); for (int i = 0; i < 10; i++) cache.Put(i, "val_" + i); IDictionary map = StoreMap(); Assert.AreEqual(10, map.Count); cache.RemoveAll(new List<int> { 0, 1, 2, 3, 4 }); Assert.AreEqual(5, map.Count); for (int i = 5; i < 10; i++) Assert.AreEqual("val_" + i, map[i]); } [Test] public void TestTx() { var cache = Cache(); using (var tx = cache.Ignite.Transactions.TxStart()) { CacheTestStore.ExpCommit = true; tx.AddMeta("meta", 100); cache.Put(1, "val"); tx.Commit(); } IDictionary map = StoreMap(); Assert.AreEqual(1, map.Count); Assert.AreEqual("val", map[1]); } [Test] public void TestLoadCacheMultithreaded() { CacheTestStore.LoadMultithreaded = true; var cache = Cache(); Assert.AreEqual(0, cache.Size()); cache.LocalLoadCache(null, 0, null); Assert.AreEqual(1000, cache.Size()); for (int i = 0; i < 1000; i++) Assert.AreEqual("val_" + i, cache.Get(i)); } [Test] public void TestCustomStoreProperties() { var cache = CustomStoreCache(); Assert.IsNotNull(cache); Assert.AreEqual(42, CacheTestStore.intProperty); Assert.AreEqual("String value", CacheTestStore.stringProperty); } [Test] public void TestDynamicStoreStart() { var cache = TemplateStoreCache(); Assert.IsNotNull(cache); cache.Put(1, cache.Name); Assert.AreEqual(cache.Name, CacheTestStore.Map[1]); } /// <summary> /// Get's grid name for this test. /// </summary> /// <returns>Grid name.</returns> protected virtual string GridName() { return null; } private IDictionary StoreMap() { return CacheTestStore.Map; } private ICache<int, string> Cache() { return PortableStoreCache<int, string>(); } private ICache<TK, TV> PortableStoreCache<TK, TV>() { return Ignition.GetIgnite(GridName()).Cache<TK, TV>(PortableStoreCacheName); } private ICache<TK, TV> ObjectStoreCache<TK, TV>() { return Ignition.GetIgnite(GridName()).Cache<TK, TV>(ObjectStoreCacheName); } private ICache<int, string> CustomStoreCache() { return Ignition.GetIgnite(GridName()).Cache<int, string>(CustomStoreCacheName); } private ICache<int, string> TemplateStoreCache() { var cacheName = TemplateStoreCacheName.Replace("*", Guid.NewGuid().ToString()); return Ignition.GetIgnite(GridName()).GetOrCreateCache<int, string>(cacheName); } } /// <summary> /// /// </summary> public class NamedNodeCacheStoreTest : CacheStoreTest { /** <inheritDoc /> */ protected override string GridName() { return "name"; } } }
using UnityEngine; using System.Collections; public class DudeState { public bool dodging = false; public bool dodgingRecovery = false; public bool blocking = false; public bool attacking = false; public bool attackingRecovery = false; public bool stunned = false; public bool running = false; public bool unbalanced = false; public void Reset() { this.dodging = false; this.dodgingRecovery = false; this.blocking = false; this.attacking = false; this.attackingRecovery = false; this.stunned = false; this.running = false; this.unbalanced = false; } } [AddComponentMenu("DudeWorld/Swordz Dude")] public class SwordzDude : MonoBehaviour { public GameObject baseAbilities; public float maxStamina = 30.0f; public Transform animated; public Transform weaponHand; public Transform offHand; public float followUpWindow = 0.2f; public bool telegraphAttacks = false; public bool cannotBeStunned = false; public float stunResistance = 0.0f; public GameObject telegraphDecal; public float telegraphRate = 0.6f; public DudeState status = new DudeState(); private Dude dude; private DudeController controller; private DudeAttack attackChain; private float followUpTimer = 0.0f; private float attackCooldown = 0.0f; private float attackDelay = 0.0f; // disabled 'cause it kinda sucks private float stamina; private float attackCancelWindow = 0.25f; private const float attackAnimationRatio = 1.0f; // magic number, shouldn't change= private const float defaultStun = 2.0f; private float blockStartTime = 0.0f; private Transform blockDecal; private Transform chargeDecal; private bool disabled = false; private bool cancelable = false; // in a state where actions can cancel into others private Transform head; private Transform hotspot; private Transform mount; private Transform activeTelegraph = null; private Transform activeTelegraphCircle = null; private GameObject circlePrefab; private Vector3 attachPos = Vector3.zero; private Quaternion attachRot = Quaternion.identity; private bool alwaysFollowUp = false; private Color originalTelegraphColor; public int swingNumber { get; private set; } public bool followUpQueued { get; private set; } void Awake() { dude = gameObject.GetComponent<Dude>(); attackChain = GetComponent<DudeAttack>(); mount = weaponHand;//weaponHand.Find("weaponMount"); hotspot = transform.Find("weapon_hotspot"); swingNumber = 0; followUpQueued = false; } void Start () { controller = gameObject.GetComponent(typeof(DudeController)) as DudeController; blockDecal = transform.Find("blockDecal"); chargeDecal = transform.Find("chargeDecal"); if(mount == null) { Debug.Log(gameObject.name + " is missing its mount hand!"); } circlePrefab = Resources.Load("Effects/effect_telegraphCircle") as GameObject; //if(gameObject.CompareTag("EnemyMob")) // alwaysFollowUp = true; attachRot.eulerAngles = new Vector3(0.0f, -180.0f, 30.0f); if(blockDecal != null) blockDecal.active = false; if(chargeDecal != null) chargeDecal.active = false; stamina = maxStamina; head = animated.Find("torso/head"); if(telegraphAttacks && telegraphDecal != null) { var clone = Instantiate(telegraphDecal, hotspot.transform.position, hotspot.transform.rotation) as GameObject; clone.transform.parent = transform; activeTelegraph = clone.transform; /* var circle = Instantiate(circlePrefab, transform.position, transform.rotation) as GameObject; circle.transform.parent = transform; activeTelegraphCircle = circle.transform; */ // save original material for resetting later originalTelegraphColor = activeTelegraph.GetComponentInChildren<MeshRenderer>().sharedMaterial.GetColor("_TintColor"); activeTelegraph.gameObject.SetActive(false); //activeTelegraphCircle.gameObject.SetActive(false); } } void FixedUpdate () { if(status.dodging && !status.dodgingRecovery) { //var finalMove = transform.forward * dodgeSpeed; //dude.RawMovement(finalMove, false); } if(followUpTimer > 0.0f) followUpTimer -= Time.fixedDeltaTime; if(attackCooldown > 0.0f) attackCooldown -= Time.fixedDeltaTime; var staminaRecovery = 1.0f; if(stamina < maxStamina) { stamina += Time.fixedDeltaTime * staminaRecovery; if(stamina > maxStamina) stamina = maxStamina; } /* if(status.blocking) { var scale = (mainWeapon.blockPower / mainWeapon.maxBlockPower) + 0.1f; blockDecal.localScale = new Vector3(scale,scale,scale); } */ } public void OnShot(DamageEvent d) { if(dude != null && d.team == dude.team) return; // see if I'm blocking in the correct direction /* if(blocking) { Instantiate(blockEffect, Util.flatten(transform.position), transform.rotation); gameObject.BroadcastMessage("OnShotBlocked", d); return; } */ /* if(hitEffect != null) Instantiate(hitEffect, Util.flatten(transform.position), transform.rotation); */ // do stun damage stamina -= d.knockback;//d.damage; if(stamina <= 0) { //StartCoroutine("OnStun", 3.0f); } } public void OnBash() { /* if(disabled || status.dodging || status.attacking) return; OnBlockEnd(); StartCoroutine( "doBash" ); */ } public bool OnAttack() { // actually just see if I'm disabled or not if(dude.blocking || status.stunned || attackCooldown > 0.0f) return false; if(status.dodging) dude.velocity = Vector3.zero; int maxSwings = 3; // in certain states, if attack is pressed, // queue up another attack if(disabled && !status.stunned && (status.attacking || status.attackingRecovery || status.dodging))// && followUpTimer <= followUpWindow/2) { if( swingNumber+1 < maxSwings) followUpQueued = true; else followUpQueued = false; //dude.Look(); return false; } if(swingNumber <= maxSwings && alwaysFollowUp) { followUpQueued = true; } //gameObject.BroadcastMessage("OnFire"); if( true ) //mainWeapon.CanFire() ) { // ran out of time for follow-up swings, so act like this is the first if(followUpTimer <= 0.0f) { swingNumber = 0; followUpTimer = followUpWindow + 0.001f; } // 1st swing if(followUpTimer > 0.0f && swingNumber < maxSwings) { swingNumber += 1; SwingEvent swing = attackChain.comboChain[0]; //SwingEvent swing = new SwingEvent(); // it would be better to move this logic to the weapon /* if(mainWeapon.lastSwingStuns && swingNumber == maxSwings) { swing.damage.effects["OnStun"] = mainWeapon.stunPower; } */ StartCoroutine( "doSwing", swing ); if(swingNumber < maxSwings) { followUpTimer = swing.rate + followUpWindow; } else { // final swing -- reset swinging swingNumber = 0; followUpTimer = 0.0f; followUpQueued = false; attackCooldown = attackDelay; } return true; } } return false; } public void OnBlock() { //if(status.attacking || status.dodging || status.running || mainWeapon.blockPower <= 0) return; if(status.dodging) { dude.velocity = Vector3.zero; } status.blocking = true; blockStartTime = Time.time; blockDecal.active = true; dude.blocking = true; } public void OnBlockEnd() { if(status.dodging || status.running || status.attacking) return; status.blocking = false; blockStartTime = 0.0f; if(blockDecal != null) blockDecal.active = false; dude.blocking = false; //animated.animation["bjorn_block"].normalizedTime = 1.0f; //animated.animation["bjorn_block"].speed = -1; //animated.animation.Play("bjorn_block"); ResetAnimation(); } IEnumerator doSwing(SwingEvent swingEvent) { if(status.dodging) { //animated.animation.Stop();// Stop("bjorn_dodge"); //animated.animation.Play("bjorn_idle"); status.dodging = false; // dumb hack because Unity animation system is dumb dumb dumb //yield return new WaitForSeconds(0.02f); } /* bool stunAttack = (swingEvent.damage.effects.ContainsKey("OnStun")); if(stunAttack) { var fx = Resources.Load("Effects/effect_fire_sword") as GameObject; var fireEffect = Instantiate(fx, mainWeapon.transform.position, mainWeapon.transform.rotation) as GameObject; fireEffect.transform.parent = mainWeapon.transform; fireEffect.name = "stunEffect"; } */ status.attacking = true; gameObject.BroadcastMessage("OnDisable"); if(telegraphAttacks && swingNumber <= 1) { animated.animation.Play(swingEvent.animation.name + "_telegraph"); activeTelegraph.gameObject.SetActive(true); //activeTelegraphCircle.gameObject.SetActive(true); //activeTelegraphCircle.localScale = Vector3.one; //activeTelegraphCircle.SendMessage("OnTelegraph", telegraphRate * 2.0f); yield return new WaitForSeconds( telegraphRate - 0.2f ); // this is a bit heavy and shouldn't be living here foreach(Transform decalChild in activeTelegraph) { decalChild.renderer.material.SetColor("_TintColor", Color.white); } status.unbalanced = true; yield return new WaitForSeconds( 0.2f ); } // if we don't telegraph, set unbalanced for the duration of the attack status.unbalanced = true; // don't remove telegraph until the attack chain is over int maxSwings = 1;//mainWeapon.swingPrefabs.Length; if(activeTelegraph != null && (swingNumber == maxSwings || maxSwings <= 1)) { activeTelegraph.gameObject.SetActive(false); //activeTelegraphCircle.gameObject.SetActive(false); foreach(Transform decalChild in activeTelegraph) { decalChild.renderer.material.SetColor("_TintColor", originalTelegraphColor); } } // step into the attack //iTween.MoveTo(gameObject, transform.position + (transform.forward * 10.0f), 0.2f); dude.AddForce(transform.forward * swingEvent.step * Time.fixedDeltaTime); // fire actual weapon gameObject.SendMessage("OnFire"); /* if(mainWeapon.swingSound != null) { float originalPitch = audio.pitch; audio.pitch = (1.0f - swingEvent.rate);// + 0.5f; //audio.PlayOneShot(mainWeapon.swingSound); audio.pitch = originalPitch; } */ // dumb hack because Unity animation system is dumb dumb dumb //animated.animation.Stop(); //animated.animation.Play("bjorn_idle"); //yield return new WaitForSeconds(0.02f); yield return new WaitForEndOfFrame(); //string animName = mainWeapon.swingAnimations[swingNumber - 1].name; if(swingEvent.animation != null) { string animName = swingEvent.animation.name; animated.animation[animName].speed = attackAnimationRatio / swingEvent.rate; animated.animation.Play(animName, PlayMode.StopAll);//CrossFade(animName); } yield return new WaitForSeconds( swingEvent.rate * (1.0f - attackCancelWindow) ); if(swingNumber < maxSwings) { status.attacking = false; status.unbalanced = false; status.attackingRecovery = true; } yield return new WaitForSeconds( swingEvent.rate * attackCancelWindow ); gameObject.BroadcastMessage("OnEnable"); status.attacking = false; status.unbalanced = false; status.attackingRecovery = false; /* if(stunAttack) { Transform fx = mainWeapon.transform.FindChild("stunEffect"); fx.particleEmitter.emit = false; fx.parent = null; } */ // reset swing animation entirely ResetAnimation(); gameObject.SendMessage("OnFollowUp"); } void ResetAnimation() { // reset swing animation entirely animated.animation.Stop(); animated.animation.Play("idle"); } public void OnKill() { Transform corpse = transform.Find("graphics"); if(corpse != null && animated != null) { corpse.parent = null; corpse.gameObject.AddComponent<Rigidbody>(); var launchVec = Vector3.up * 400.0f; var deviation = Random.insideUnitCircle * 400f; launchVec.x += deviation.x; launchVec.z += deviation.y; corpse.rigidbody.AddForce(launchVec); corpse.rigidbody.AddTorque(Random.insideUnitSphere * 1000f); Destroy(corpse.gameObject, 3.0f); } Director.Instance.OnDeath(GetComponent<Damageable>()); } public void OnStopAttack() { dude.velocity = Vector3.zero; animated.animation.Stop(); animated.animation.Play("bjorn_idle"); StopCoroutine("doSwing"); gameObject.BroadcastMessage("OnEnable"); status.attacking = false; status.unbalanced = false; } public void OnInterrupt() { gameObject.SendMessage("OnStun", -0.3f); } public IEnumerator OnStun(float stunDuration) { if(status.stunned || cannotBeStunned) yield break; if(stunDuration == 0.0f) stunDuration = defaultStun; // HACK: stunDuration of < 0 means "force a stun of this amount" if(stunDuration < 0.0f) { stunDuration *= -1.0f; } else { stunDuration -= stunResistance; if(stunDuration <= 0.0f) stunDuration = 0.5f; //yield break; // tell the Director to maintain the bloodlust meter var fakeData = new DamageEvent(); fakeData.damage = 20; var director = GameObject.FindGameObjectWithTag("Director"); if(director != null) { director.SendMessage("OnDamageDealt", fakeData); } } var trailEffect = Instantiate( Resources.Load("Effects/effect_stun") as GameObject, Vector3.zero, Quaternion.identity ) as GameObject; trailEffect.transform.parent = transform; trailEffect.transform.localPosition = Vector3.zero; if(stunDuration >= 1.0f) { animated.animation["bjorn_die"].speed = 1; animated.animation.Play("bjorn_die"); //animated.parent.SendMessage("DoEffect", stunDuration); } // stop all active processes gameObject.BroadcastMessage("OnDisable"); StopCoroutine("doSwing"); if(activeTelegraph != null) { activeTelegraph.gameObject.SetActive(false); //activeTelegraphCircle.gameObject.SetActive(false); } this.status.stunned = true; yield return new WaitForSeconds( stunDuration ); Destroy(trailEffect); if(stunDuration >= 1.0f) { // get up animated.animation["bjorn_die"].normalizedTime = 1.0f; animated.animation["bjorn_die"].speed = -1; animated.animation.Play("bjorn_die"); yield return new WaitForSeconds( 0.5f ); } gameObject.BroadcastMessage("OnEnable"); this.status.stunned = false; // have to reset other statuses as well // I really shouldn't have to do this... this.status.Reset(); } /* //public void OnCollisionEnter(Collision c) public void OnControllerColliderHit(ControllerColliderHit c) //public void OnTriggerEnter(Collider c) { // push back enemies if you run into them while blocking if(this.status.blocking)// && c.gameObject.CompareTag("EnemyMob")) { Debug.Log("bash : " + c.gameObject.tag); // counter test var otherDude = c.gameObject.GetComponent(typeof(Dude)) as Dude; if(otherDude != null) { var knockbackForce = 10;//mainWeapon.swingKnockback[0]; var forceVec = (otherDude.transform.position - transform.position).normalized; otherDude.AddForce(forceVec * knockbackForce); } } } */ public void OnFollowUp() { var currentFacing = transform.forward; if(controller != null) { currentFacing = controller.GetCurrentMoveVec(); } if(followUpQueued && !disabled && !status.stunned) { dude.Look(currentFacing); /* var attackChain = mainWeapon.GetComponent<MeleeAttackChain>(); if(false)//attackChain != null) { attackChain.charge = 1.0f; attackChain.OnChargeAttack(); } else { OnAttack(); } */ OnAttack(); if(!alwaysFollowUp) followUpQueued = false; } } public void OnCancel() { this.followUpQueued = false; } public void OnEnable() { disabled = false; } public void OnDisable() { disabled = true; } public bool isDisabled { get{ return disabled; } } }
using System; using System.Collections.Concurrent; using System.Diagnostics; using System.IO.Pipes; using System.Threading; using System.Threading.Tasks; using W; using W.Logging; namespace W.IO.Pipes { /// <summary> /// Synchronizes the process of transmitting and receiving data over a named pipe /// </summary> public class PipeTransceiver<TDataType> : Disposable where TDataType : class { private const int RECEIVE_BUFFER_SIZE = 256; private const int SEND_BUFFER_SIZE = 256; private ManualResetEventSlim _mreWriteComplete = new ManualResetEventSlim(true); private readonly ConcurrentQueue<byte[]> _writeQueue = new ConcurrentQueue<byte[]>(); private W.Threading.Thread _thread = null; /// <summary> /// The PipeStream associated with this PipeTransceiver /// </summary> protected Lockable<PipeStream> Stream { get; } = new Lockable<PipeStream>(); /// <summary> /// Override to customize received data before exposing it via the MessageReceived callback /// </summary> /// <param name="message">The received data</param> /// <returns>The formatted data</returns> protected virtual TDataType FormatReceivedMessage(byte[] message) { return message.As<TDataType>(); } /// <summary> /// Override to customize the data before transmission /// </summary> /// <param name="message">The unaltered data to send</param> /// <returns>The formatted data</returns> protected virtual byte[] FormatMessageToSend(TDataType message) { return message.As<byte[]>(); } /// <summary> /// Override to handle a disconnect /// </summary> /// <param name="e">The exception, if one occurred</param> /// <remarks>This method is called when a disconnect has been detected by a failed ReadAsync</remarks> protected virtual void OnDisconnected(Exception e = null) { } /// <summary> /// Called when a message has been received /// </summary> public Action<object, TDataType> MessageReceived { get; set; } /// <summary> /// Set to True if the client is running server-side /// </summary> /// <remarks>This value is informational only; no logic depends on it</remarks> protected bool IsServerSide { get; set; } = false; /// <summary> /// Can be useful for large data sets. Set to True to use compression, otherwise False /// </summary> /// <remarks>Make sure both server and client have the same value</remarks> public bool UseCompression { get; set; } private void SendMessages(CancellationToken token) { //write all available messages while (!_writeQueue.IsEmpty) { Debug.WriteLine("Sending message(s)"); if (_writeQueue.TryDequeue(out byte[] message)) { System.Diagnostics.Debug.WriteLine("Sending: " + message.AsString()); if (UseCompression) message = message.AsCompressed(); PipeStreamMethods.WriteMessageAsync(Stream.Value, message, SEND_BUFFER_SIZE, token).Wait(); //WriteMessageToStream(message, SEND_BUFFER_SIZE); } } _mreWriteComplete.Set(); //can be null if the thread was aborted } private void ReadMessages(CancellationToken token) { //read a message if one is available var messageSize = PipeStreamMethods.GetMessageSize(Stream.Value, 1000); //while (messageSize > 0 )//&& !token.IsCancellationRequested) if (messageSize > 0) { //try //{ if (PipeStreamMethods.ReadMessage(Stream.Value, messageSize, RECEIVE_BUFFER_SIZE, out byte[] message, 5000)) //if (message != null) { if (UseCompression) message = message.FromCompressed(); var formattedMessage = FormatReceivedMessage(message); MessageReceived?.BeginInvoke(this, formattedMessage, ar => MessageReceived.EndInvoke(ar), null); } //} //catch (OperationCanceledException) //the read timed out //{ // System.Diagnostics.Debugger.Break(); //} } } private void ThreadProc(CancellationToken token) { while (token != null && !token.IsCancellationRequested) { try { //W.Threading.Thread.Sleep(1); SendMessages(token); ReadMessages(token); } //#if NET45 || NETSTANDARD1_4 || NETCOREAPP1_0 || WINDOWS_UWP // catch (System.MissingMethodException e) // { // System.Diagnostics.Debug.WriteLine(e.ToString()); // System.Diagnostics.Debugger.Break(); // } //#endif //#if NETSTANDARD1_4 //Tungsten.IO.Pipes.Standard is 1.4 // catch (System.Threading.Tasks.TaskCanceledException) // { // //do nothing // } //#else // catch (System.Threading.ThreadAbortException) // { // System.Threading.Thread.ResetAbort(); // } //#endif //catch (ObjectDisposedException) //{ // //ignore - this can happen if the PipeTransceiver is disposed after ReadMessageSize or ReadMessage are initiated //} //catch (AggregateException) //{ // //ignore - this happens when ReadMessageSize times out //} catch (InvalidOperationException e) { //ignore - pipe was closed OnDisconnected(e); //added 10.29.2017 } catch (System.IO.IOException e) //Pipe closed or shut down? { //System.Diagnostics.Debug.WriteLine("SynchronizedReadWrite.GetMessageSize Exception: {0}", e.Message); OnDisconnected(e); } catch (Exception e) { System.Diagnostics.Debugger.Break(); OnDisconnected(e); System.Diagnostics.Debug.WriteLine(e.ToString()); System.Diagnostics.Debugger.Break(); //Log.e(e); } finally { _mreWriteComplete.Set(); //in case an exception occurred while sending messages } W.Threading.Thread.Sleep(W.Threading.CPUProfileEnum.SpinWait1); } } /// <summary> /// Disposes the PipeTransceiver and release resources /// </summary> protected override void OnDispose() { _mreWriteComplete.Wait(); _mreWriteComplete.Dispose(); _thread?.Dispose(); //check for null just in case it was never assigned } /// <summary> /// Waits for all the messages to be written /// </summary> public void WaitForWriteComplete() { _mreWriteComplete.Wait(); } /// <summary> /// Waits for all the messages to be written or times out after the specified time /// </summary> /// <param name="msTimeout">The number of milliseconds to wait before a timeout occurs</param> /// <returns>True if all messages were sent, otherwise False</returns> public bool WaitForWriteComplete(int msTimeout) { return _mreWriteComplete.Wait(msTimeout); } /// <summary> /// Queues a message to send over the pipe /// </summary> /// <param name="message"></param> public void Write(TDataType message) { _mreWriteComplete.Reset();//10.29.2017 - moved this above the FormatMessageToSend var formatted = FormatMessageToSend(message); _writeQueue.Enqueue(formatted); //Console.WriteLine("There are {0} items to write", _writeQueue.Count); } /// <summary> /// Initialize the PipeTransceiver with the given PipeStream /// </summary> /// <param name="stream">The PipeStream to use</param> /// <param name="isServerSide">If True, this indicates a server-side client (primarily used for debugging purposes)</param> public void Initialize(PipeStream stream, bool isServerSide) { IsServerSide = isServerSide; Stream.Value = stream; //NetStandard doesn't support Read Timeouts, so we can't use that. //Our ReadMessageSize uses the Async method and CancellationTokenSource to timeout _thread = W.Threading.Thread.Create(ThreadProc); } /// <summary> /// Deconstructs the PipeTransceiver and calls Dispose /// </summary> ~PipeTransceiver() { Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; using Google.OrTools.ConstraintSolver; class Task { public Task(int taskId, int jobId, int duration, int machine) { TaskId = taskId; JobId = jobId; Duration = duration; Machine = machine; Name = "T" + taskId + "J" + jobId + "M" + machine + "D" + duration; } public int TaskId {get; set;} public int JobId {get; set;} public int Machine {get; set;} public int Duration {get; set;} public string Name {get;} } class FlexibleJobshop { //Number of machines. public const int machinesCount = 3; //horizon is the upper bound of the start time of all tasks. public const int horizon = 300; //this will be set to the size of myJobList variable. public static int jobsCount; /*Search time limit in milliseconds. if it's equal to 0, then no time limit will be used.*/ public const int timeLimitInMs = 0; public static List<List<Task>> myJobList = new List<List<Task>>(); public static void InitTaskList() { List<Task> taskList = new List<Task>(); taskList.Add(new Task(0, 0, 65, 0)); taskList.Add(new Task(1 ,0, 5, 1)); taskList.Add(new Task(2 ,0, 15, 2)); myJobList.Add(taskList); taskList = new List<Task>(); taskList.Add(new Task(0, 1, 15, 0)); taskList.Add(new Task(1 ,1, 25, 1)); taskList.Add(new Task(2 ,1, 10, 2)); myJobList.Add(taskList); taskList = new List<Task>(); taskList.Add(new Task(0 ,2, 25, 0)); taskList.Add(new Task(1 ,2, 30, 1)); taskList.Add(new Task(2 ,2, 40, 2)); myJobList.Add(taskList); taskList = new List<Task>(); taskList.Add(new Task(0, 3, 20, 0)); taskList.Add(new Task(1 ,3, 35, 1)); taskList.Add(new Task(2 ,3, 10, 2)); myJobList.Add(taskList); taskList = new List<Task>(); taskList.Add(new Task(0, 4, 15, 0)); taskList.Add(new Task(1 ,4, 25, 1)); taskList.Add(new Task(2 ,4, 10, 2)); myJobList.Add(taskList); taskList = new List<Task>(); taskList.Add(new Task(0, 5, 25, 0)); taskList.Add(new Task(1 ,5, 30, 1)); taskList.Add(new Task(2 ,5, 40, 2)); myJobList.Add(taskList); taskList = new List<Task>(); taskList.Add(new Task(0, 6, 20, 0)); taskList.Add(new Task(1 ,6, 35, 1)); taskList.Add(new Task(2 ,6, 10, 2)); myJobList.Add(taskList); taskList = new List<Task>(); taskList.Add(new Task(0, 7, 10, 0)); taskList.Add(new Task(1 ,7, 15, 1)); taskList.Add(new Task(2 ,7, 50, 2)); myJobList.Add(taskList); taskList = new List<Task>(); taskList.Add(new Task(0, 8, 50, 0)); taskList.Add(new Task(1 ,8, 10, 1)); taskList.Add(new Task(2 ,8, 20, 2)); myJobList.Add(taskList); jobsCount = myJobList.Count; } public static void Main(String[] args) { InitTaskList(); Solver solver = new Solver("Jobshop"); // ----- Creates all Intervals and vars ----- // All tasks List<IntervalVar> allTasks = new List<IntervalVar>(); // Stores all tasks attached interval variables per job. List<List<IntervalVar>> jobsToTasks = new List<List<IntervalVar>>(jobsCount); // machinesToTasks stores the same interval variables as above, but // grouped my machines instead of grouped by jobs. List<List<IntervalVar>> machinesToTasks = new List<List<IntervalVar>>(machinesCount); for (int i=0; i<machinesCount; i++) { machinesToTasks.Add(new List<IntervalVar>()); } // Creates all individual interval variables. foreach (List<Task> job in myJobList) { jobsToTasks.Add(new List<IntervalVar>()); foreach (Task task in job) { IntervalVar oneTask = solver.MakeFixedDurationIntervalVar( 0, horizon, task.Duration, false, task.Name); jobsToTasks[task.JobId].Add(oneTask); allTasks.Add(oneTask); machinesToTasks[task.Machine].Add(oneTask); } } // ----- Creates model ----- // Creates precedences inside jobs. foreach (List<IntervalVar> jobToTask in jobsToTasks) { int tasksCount = jobToTask.Count; for (int task_index = 0; task_index < tasksCount - 1; ++task_index) { IntervalVar t1 = jobToTask[task_index]; IntervalVar t2 = jobToTask[task_index + 1]; Constraint prec = solver.MakeIntervalVarRelation(t2, Solver.STARTS_AFTER_END, t1); solver.Add(prec); } } // Adds disjunctive constraints on unary resources, and creates // sequence variables. A sequence variable is a dedicated variable // whose job is to sequence interval variables. SequenceVar[] allSequences = new SequenceVar[machinesCount]; for (int machineId = 0; machineId < machinesCount; ++machineId) { string name = "Machine_" + machineId; DisjunctiveConstraint ct = solver.MakeDisjunctiveConstraint(machinesToTasks[machineId].ToArray(), name); solver.Add(ct); allSequences[machineId] = ct.SequenceVar(); } // Creates array of end_times of jobs. IntVar[] allEnds = new IntVar[jobsCount]; for (int i=0; i<jobsCount; i++) { IntervalVar task = jobsToTasks[i].Last(); allEnds[i] = task.EndExpr().Var(); } // Objective: minimize the makespan (maximum end times of all tasks) // of the problem. IntVar objectiveVar = solver.MakeMax(allEnds).Var(); OptimizeVar objectiveMonitor = solver.MakeMinimize(objectiveVar, 1); // ----- Search monitors and decision builder ----- // This decision builder will rank all tasks on all machines. DecisionBuilder sequencePhase = solver.MakePhase(allSequences, Solver.SEQUENCE_DEFAULT); // After the ranking of tasks, the schedule is still loose and any // task can be postponed at will. But, because the problem is now a PERT // (http://en.wikipedia.org/wiki/Program_Evaluation_and_Review_Technique), // we can schedule each task at its earliest start time. This iscs // conveniently done by fixing the objective variable to its // minimum value. DecisionBuilder objPhase = solver.MakePhase( objectiveVar, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); // The main decision builder (ranks all tasks, then fixes the // objectiveVariable). DecisionBuilder mainPhase = solver.Compose(sequencePhase, objPhase); // Search log. const int kLogFrequency = 1000000; SearchMonitor searchLog = solver.MakeSearchLog(kLogFrequency, objectiveMonitor); SearchLimit limit = null; if (timeLimitInMs > 0) { limit = solver.MakeTimeLimit(timeLimitInMs); } SolutionCollector collector = solver.MakeLastSolutionCollector(); collector.Add(allSequences); collector.Add(allTasks.ToArray()); // Search. bool solutionFound = solver.Solve(mainPhase, searchLog, objectiveMonitor, limit, collector); if(solutionFound) { //The index of the solution from the collector const int SOLUTION_INDEX = 0; Assignment solution = collector.Solution(SOLUTION_INDEX); for (int m = 0; m < machinesCount; ++m) { Console.WriteLine("Machine " + m + " :"); SequenceVar seq = allSequences[m]; int[] storedSequence = collector.ForwardSequence(SOLUTION_INDEX, seq); foreach (int taskIndex in storedSequence) { IntervalVar task = seq.Interval(taskIndex); long startMin = solution.StartMin(task); long startMax = solution.StartMax(task); if(startMin == startMax) { Console.WriteLine("Task " + task.Name() + " starts at " + startMin + "."); } else { Console.WriteLine("Task " + task.Name() + " starts between " + startMin + " and " + startMax + "."); } } } } else { Console.WriteLine("No solution found!"); } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// An array of email notifications that specifies the email the user receives when they are a sender. When the specific email notification is set to true, the user receives those types of email notifications from DocuSign. The user inherits the default account sender email notification settings when the user is created. /// </summary> [DataContract] public partial class SignerEmailNotifications : IEquatable<SignerEmailNotifications>, IValidatableObject { public SignerEmailNotifications() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="SignerEmailNotifications" /> class. /// </summary> /// <param name="AgentNotification">When set to **true**, the user receives agent notification emails..</param> /// <param name="CarbonCopyNotification">When set to **true**, the user receives notifications of carbon copy deliveries..</param> /// <param name="CertifiedDeliveryNotification">When set to **true**, the user receives notifications of certified deliveries..</param> /// <param name="CommentsOnlyPrivateAndMention">CommentsOnlyPrivateAndMention.</param> /// <param name="CommentsReceiveAll">CommentsReceiveAll.</param> /// <param name="DocumentMarkupActivation">When set to **true**, the user receives notification that document markup has been activated..</param> /// <param name="EnvelopeActivation">When set to **true**, the user receives notification that the envelope has been activated..</param> /// <param name="EnvelopeComplete">When set to **true**, the user receives notification that the envelope has been completed..</param> /// <param name="EnvelopeCorrected">When set to **true**, the user receives notification that the envelope has been corrected..</param> /// <param name="EnvelopeDeclined">When set to **true**, the user receives notification that the envelope has been declined..</param> /// <param name="EnvelopeVoided">When set to **true**, the user receives notification that the envelope has been voided..</param> /// <param name="FaxReceived">Reserved:.</param> /// <param name="OfflineSigningFailed">When set to **true**, the user receives notification if the offline signing failed..</param> /// <param name="PurgeDocuments">When set to **true**, the user receives notification of document purges..</param> /// <param name="ReassignedSigner">When set to **true**, the user receives notification that the envelope has been reassigned..</param> /// <param name="WhenSigningGroupMember">WhenSigningGroupMember.</param> public SignerEmailNotifications(string AgentNotification = default(string), string CarbonCopyNotification = default(string), string CertifiedDeliveryNotification = default(string), string CommentsOnlyPrivateAndMention = default(string), string CommentsReceiveAll = default(string), string DocumentMarkupActivation = default(string), string EnvelopeActivation = default(string), string EnvelopeComplete = default(string), string EnvelopeCorrected = default(string), string EnvelopeDeclined = default(string), string EnvelopeVoided = default(string), string FaxReceived = default(string), string OfflineSigningFailed = default(string), string PurgeDocuments = default(string), string ReassignedSigner = default(string), string WhenSigningGroupMember = default(string)) { this.AgentNotification = AgentNotification; this.CarbonCopyNotification = CarbonCopyNotification; this.CertifiedDeliveryNotification = CertifiedDeliveryNotification; this.CommentsOnlyPrivateAndMention = CommentsOnlyPrivateAndMention; this.CommentsReceiveAll = CommentsReceiveAll; this.DocumentMarkupActivation = DocumentMarkupActivation; this.EnvelopeActivation = EnvelopeActivation; this.EnvelopeComplete = EnvelopeComplete; this.EnvelopeCorrected = EnvelopeCorrected; this.EnvelopeDeclined = EnvelopeDeclined; this.EnvelopeVoided = EnvelopeVoided; this.FaxReceived = FaxReceived; this.OfflineSigningFailed = OfflineSigningFailed; this.PurgeDocuments = PurgeDocuments; this.ReassignedSigner = ReassignedSigner; this.WhenSigningGroupMember = WhenSigningGroupMember; } /// <summary> /// When set to **true**, the user receives agent notification emails. /// </summary> /// <value>When set to **true**, the user receives agent notification emails.</value> [DataMember(Name="agentNotification", EmitDefaultValue=false)] public string AgentNotification { get; set; } /// <summary> /// When set to **true**, the user receives notifications of carbon copy deliveries. /// </summary> /// <value>When set to **true**, the user receives notifications of carbon copy deliveries.</value> [DataMember(Name="carbonCopyNotification", EmitDefaultValue=false)] public string CarbonCopyNotification { get; set; } /// <summary> /// When set to **true**, the user receives notifications of certified deliveries. /// </summary> /// <value>When set to **true**, the user receives notifications of certified deliveries.</value> [DataMember(Name="certifiedDeliveryNotification", EmitDefaultValue=false)] public string CertifiedDeliveryNotification { get; set; } /// <summary> /// Gets or Sets CommentsOnlyPrivateAndMention /// </summary> [DataMember(Name="commentsOnlyPrivateAndMention", EmitDefaultValue=false)] public string CommentsOnlyPrivateAndMention { get; set; } /// <summary> /// Gets or Sets CommentsReceiveAll /// </summary> [DataMember(Name="commentsReceiveAll", EmitDefaultValue=false)] public string CommentsReceiveAll { get; set; } /// <summary> /// When set to **true**, the user receives notification that document markup has been activated. /// </summary> /// <value>When set to **true**, the user receives notification that document markup has been activated.</value> [DataMember(Name="documentMarkupActivation", EmitDefaultValue=false)] public string DocumentMarkupActivation { get; set; } /// <summary> /// When set to **true**, the user receives notification that the envelope has been activated. /// </summary> /// <value>When set to **true**, the user receives notification that the envelope has been activated.</value> [DataMember(Name="envelopeActivation", EmitDefaultValue=false)] public string EnvelopeActivation { get; set; } /// <summary> /// When set to **true**, the user receives notification that the envelope has been completed. /// </summary> /// <value>When set to **true**, the user receives notification that the envelope has been completed.</value> [DataMember(Name="envelopeComplete", EmitDefaultValue=false)] public string EnvelopeComplete { get; set; } /// <summary> /// When set to **true**, the user receives notification that the envelope has been corrected. /// </summary> /// <value>When set to **true**, the user receives notification that the envelope has been corrected.</value> [DataMember(Name="envelopeCorrected", EmitDefaultValue=false)] public string EnvelopeCorrected { get; set; } /// <summary> /// When set to **true**, the user receives notification that the envelope has been declined. /// </summary> /// <value>When set to **true**, the user receives notification that the envelope has been declined.</value> [DataMember(Name="envelopeDeclined", EmitDefaultValue=false)] public string EnvelopeDeclined { get; set; } /// <summary> /// When set to **true**, the user receives notification that the envelope has been voided. /// </summary> /// <value>When set to **true**, the user receives notification that the envelope has been voided.</value> [DataMember(Name="envelopeVoided", EmitDefaultValue=false)] public string EnvelopeVoided { get; set; } /// <summary> /// Reserved: /// </summary> /// <value>Reserved:</value> [DataMember(Name="faxReceived", EmitDefaultValue=false)] public string FaxReceived { get; set; } /// <summary> /// When set to **true**, the user receives notification if the offline signing failed. /// </summary> /// <value>When set to **true**, the user receives notification if the offline signing failed.</value> [DataMember(Name="offlineSigningFailed", EmitDefaultValue=false)] public string OfflineSigningFailed { get; set; } /// <summary> /// When set to **true**, the user receives notification of document purges. /// </summary> /// <value>When set to **true**, the user receives notification of document purges.</value> [DataMember(Name="purgeDocuments", EmitDefaultValue=false)] public string PurgeDocuments { get; set; } /// <summary> /// When set to **true**, the user receives notification that the envelope has been reassigned. /// </summary> /// <value>When set to **true**, the user receives notification that the envelope has been reassigned.</value> [DataMember(Name="reassignedSigner", EmitDefaultValue=false)] public string ReassignedSigner { get; set; } /// <summary> /// Gets or Sets WhenSigningGroupMember /// </summary> [DataMember(Name="whenSigningGroupMember", EmitDefaultValue=false)] public string WhenSigningGroupMember { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class SignerEmailNotifications {\n"); sb.Append(" AgentNotification: ").Append(AgentNotification).Append("\n"); sb.Append(" CarbonCopyNotification: ").Append(CarbonCopyNotification).Append("\n"); sb.Append(" CertifiedDeliveryNotification: ").Append(CertifiedDeliveryNotification).Append("\n"); sb.Append(" CommentsOnlyPrivateAndMention: ").Append(CommentsOnlyPrivateAndMention).Append("\n"); sb.Append(" CommentsReceiveAll: ").Append(CommentsReceiveAll).Append("\n"); sb.Append(" DocumentMarkupActivation: ").Append(DocumentMarkupActivation).Append("\n"); sb.Append(" EnvelopeActivation: ").Append(EnvelopeActivation).Append("\n"); sb.Append(" EnvelopeComplete: ").Append(EnvelopeComplete).Append("\n"); sb.Append(" EnvelopeCorrected: ").Append(EnvelopeCorrected).Append("\n"); sb.Append(" EnvelopeDeclined: ").Append(EnvelopeDeclined).Append("\n"); sb.Append(" EnvelopeVoided: ").Append(EnvelopeVoided).Append("\n"); sb.Append(" FaxReceived: ").Append(FaxReceived).Append("\n"); sb.Append(" OfflineSigningFailed: ").Append(OfflineSigningFailed).Append("\n"); sb.Append(" PurgeDocuments: ").Append(PurgeDocuments).Append("\n"); sb.Append(" ReassignedSigner: ").Append(ReassignedSigner).Append("\n"); sb.Append(" WhenSigningGroupMember: ").Append(WhenSigningGroupMember).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as SignerEmailNotifications); } /// <summary> /// Returns true if SignerEmailNotifications instances are equal /// </summary> /// <param name="other">Instance of SignerEmailNotifications to be compared</param> /// <returns>Boolean</returns> public bool Equals(SignerEmailNotifications other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.AgentNotification == other.AgentNotification || this.AgentNotification != null && this.AgentNotification.Equals(other.AgentNotification) ) && ( this.CarbonCopyNotification == other.CarbonCopyNotification || this.CarbonCopyNotification != null && this.CarbonCopyNotification.Equals(other.CarbonCopyNotification) ) && ( this.CertifiedDeliveryNotification == other.CertifiedDeliveryNotification || this.CertifiedDeliveryNotification != null && this.CertifiedDeliveryNotification.Equals(other.CertifiedDeliveryNotification) ) && ( this.CommentsOnlyPrivateAndMention == other.CommentsOnlyPrivateAndMention || this.CommentsOnlyPrivateAndMention != null && this.CommentsOnlyPrivateAndMention.Equals(other.CommentsOnlyPrivateAndMention) ) && ( this.CommentsReceiveAll == other.CommentsReceiveAll || this.CommentsReceiveAll != null && this.CommentsReceiveAll.Equals(other.CommentsReceiveAll) ) && ( this.DocumentMarkupActivation == other.DocumentMarkupActivation || this.DocumentMarkupActivation != null && this.DocumentMarkupActivation.Equals(other.DocumentMarkupActivation) ) && ( this.EnvelopeActivation == other.EnvelopeActivation || this.EnvelopeActivation != null && this.EnvelopeActivation.Equals(other.EnvelopeActivation) ) && ( this.EnvelopeComplete == other.EnvelopeComplete || this.EnvelopeComplete != null && this.EnvelopeComplete.Equals(other.EnvelopeComplete) ) && ( this.EnvelopeCorrected == other.EnvelopeCorrected || this.EnvelopeCorrected != null && this.EnvelopeCorrected.Equals(other.EnvelopeCorrected) ) && ( this.EnvelopeDeclined == other.EnvelopeDeclined || this.EnvelopeDeclined != null && this.EnvelopeDeclined.Equals(other.EnvelopeDeclined) ) && ( this.EnvelopeVoided == other.EnvelopeVoided || this.EnvelopeVoided != null && this.EnvelopeVoided.Equals(other.EnvelopeVoided) ) && ( this.FaxReceived == other.FaxReceived || this.FaxReceived != null && this.FaxReceived.Equals(other.FaxReceived) ) && ( this.OfflineSigningFailed == other.OfflineSigningFailed || this.OfflineSigningFailed != null && this.OfflineSigningFailed.Equals(other.OfflineSigningFailed) ) && ( this.PurgeDocuments == other.PurgeDocuments || this.PurgeDocuments != null && this.PurgeDocuments.Equals(other.PurgeDocuments) ) && ( this.ReassignedSigner == other.ReassignedSigner || this.ReassignedSigner != null && this.ReassignedSigner.Equals(other.ReassignedSigner) ) && ( this.WhenSigningGroupMember == other.WhenSigningGroupMember || this.WhenSigningGroupMember != null && this.WhenSigningGroupMember.Equals(other.WhenSigningGroupMember) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.AgentNotification != null) hash = hash * 59 + this.AgentNotification.GetHashCode(); if (this.CarbonCopyNotification != null) hash = hash * 59 + this.CarbonCopyNotification.GetHashCode(); if (this.CertifiedDeliveryNotification != null) hash = hash * 59 + this.CertifiedDeliveryNotification.GetHashCode(); if (this.CommentsOnlyPrivateAndMention != null) hash = hash * 59 + this.CommentsOnlyPrivateAndMention.GetHashCode(); if (this.CommentsReceiveAll != null) hash = hash * 59 + this.CommentsReceiveAll.GetHashCode(); if (this.DocumentMarkupActivation != null) hash = hash * 59 + this.DocumentMarkupActivation.GetHashCode(); if (this.EnvelopeActivation != null) hash = hash * 59 + this.EnvelopeActivation.GetHashCode(); if (this.EnvelopeComplete != null) hash = hash * 59 + this.EnvelopeComplete.GetHashCode(); if (this.EnvelopeCorrected != null) hash = hash * 59 + this.EnvelopeCorrected.GetHashCode(); if (this.EnvelopeDeclined != null) hash = hash * 59 + this.EnvelopeDeclined.GetHashCode(); if (this.EnvelopeVoided != null) hash = hash * 59 + this.EnvelopeVoided.GetHashCode(); if (this.FaxReceived != null) hash = hash * 59 + this.FaxReceived.GetHashCode(); if (this.OfflineSigningFailed != null) hash = hash * 59 + this.OfflineSigningFailed.GetHashCode(); if (this.PurgeDocuments != null) hash = hash * 59 + this.PurgeDocuments.GetHashCode(); if (this.ReassignedSigner != null) hash = hash * 59 + this.ReassignedSigner.GetHashCode(); if (this.WhenSigningGroupMember != null) hash = hash * 59 + this.WhenSigningGroupMember.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Lucene.Net.Store { /// <summary>A Directory is a flat list of files. Files may be written once, when they /// are created. Once a file is created it may only be opened for read, or /// deleted. Random access is permitted both when reading and writing. /// /// <p> Java's i/o APIs not used directly, but rather all i/o is /// through this API. This permits things such as: <ul> /// <li> implementation of RAM-based indices; /// <li> implementation indices stored in a database, via JDBC; /// <li> implementation of an index as a single file; /// </ul> /// /// Directory locking is implemented by an instance of {@link /// LockFactory}, and can be changed for each Directory /// instance using {@link #setLockFactory}. /// /// </summary> /// <author> Doug Cutting /// </author> [Serializable] public abstract class Directory { protected internal volatile bool isOpen = true; /// <summary>Holds the LockFactory instance (implements locking for /// this Directory instance). /// </summary> [NonSerialized] protected internal LockFactory lockFactory; /// <summary>Returns an array of strings, one for each file in the /// directory. This method may return null (for example for /// {@link FSDirectory} if the underlying directory doesn't /// exist in the filesystem or there are permissions /// problems). /// </summary> public abstract System.String[] List(); /// <summary>Returns true iff a file with the given name exists. </summary> public abstract bool FileExists(System.String name); /// <summary>Returns the time the named file was last modified. </summary> public abstract long FileModified(System.String name); /// <summary>Set the modified time of an existing file to now. </summary> public abstract void TouchFile(System.String name); /// <summary>Removes an existing file in the directory. </summary> public abstract void DeleteFile(System.String name); /// <summary>Renames an existing file in the directory. /// If a file already exists with the new name, then it is replaced. /// This replacement is not guaranteed to be atomic. /// </summary> /// <deprecated> /// </deprecated> public abstract void RenameFile(System.String from, System.String to); /// <summary>Returns the length of a file in the directory. </summary> public abstract long FileLength(System.String name); /// <summary>Creates a new, empty file in the directory with the given name. /// Returns a stream writing this file. /// </summary> public abstract IndexOutput CreateOutput(System.String name); /// <summary> /// Ensure that any writes to the file are moved to /// stable storage. Lucene uses this to properly commit /// chages to the index, to prevent a machine/OS crash /// from corrupting the index. /// </summary> /// <param name="name"></param> public virtual void Sync(String name) { } /// <summary>Returns a stream reading an existing file. </summary> public abstract IndexInput OpenInput(System.String name); /// <summary>Returns a stream reading an existing file, with the /// specified read buffer size. The particular Directory /// implementation may ignore the buffer size. Currently /// the only Directory implementations that respect this /// parameter are {@link FSDirectory} and {@link /// Lucene.Net.Index.CompoundFileReader}. /// </summary> public virtual IndexInput OpenInput(System.String name, int bufferSize) { return OpenInput(name); } /// <summary>Construct a {@link Lock}.</summary> /// <param name="name">the name of the lock file /// </param> public virtual Lock MakeLock(System.String name) { return lockFactory.MakeLock(name); } /// <summary> Attempt to clear (forcefully unlock and remove) the /// specified lock. Only call this at a time when you are /// certain this lock is no longer in use. /// </summary> /// <param name="name">name of the lock to be cleared. /// </param> public virtual void ClearLock(System.String name) { if (lockFactory != null) { lockFactory.ClearLock(name); } } /// <summary>Closes the store. </summary> public abstract void Close(); /// <summary> Set the LockFactory that this Directory instance should /// use for its locking implementation. Each * instance of /// LockFactory should only be used for one directory (ie, /// do not share a single instance across multiple /// Directories). /// /// </summary> /// <param name="lockFactory">instance of {@link LockFactory}. /// </param> public virtual void SetLockFactory(LockFactory lockFactory) { this.lockFactory = lockFactory; lockFactory.SetLockPrefix(this.GetLockID()); } /// <summary> Get the LockFactory that this Directory instance is /// using for its locking implementation. Note that this /// may be null for Directory implementations that provide /// their own locking implementation. /// </summary> public virtual LockFactory GetLockFactory() { return this.lockFactory; } /// <summary> Return a string identifier that uniquely differentiates /// this Directory instance from other Directory instances. /// This ID should be the same if two Directory instances /// (even in different JVMs and/or on different machines) /// are considered "the same index". This is how locking /// "scopes" to the right index. /// </summary> public virtual System.String GetLockID() { return this.ToString(); } /// <summary> Copy contents of a directory src to a directory dest. /// If a file in src already exists in dest then the /// one in dest will be blindly overwritten. /// /// </summary> /// <param name="src">source directory /// </param> /// <param name="dest">destination directory /// </param> /// <param name="closeDirSrc">if <code>true</code>, call {@link #close()} method on source directory /// </param> /// <throws> IOException </throws> public static void Copy(Directory src, Directory dest, bool closeDirSrc) { System.String[] files = src.List(); if (files == null) { throw new System.IO.IOException("cannot read directory " + src + ": list() returned null"); } byte[] buf = new byte[BufferedIndexOutput.BUFFER_SIZE]; for (int i = 0; i < files.Length; i++) { IndexOutput os = null; IndexInput is_Renamed = null; try { // create file in dest directory os = dest.CreateOutput(files[i]); // read current file is_Renamed = src.OpenInput(files[i]); // and copy to dest directory long len = is_Renamed.Length(); long readCount = 0; while (readCount < len) { int toRead = readCount + BufferedIndexOutput.BUFFER_SIZE > len ? (int) (len - readCount) : BufferedIndexOutput.BUFFER_SIZE; is_Renamed.ReadBytes(buf, 0, toRead); os.WriteBytes(buf, toRead); readCount += toRead; } } finally { // graceful cleanup try { if (os != null) os.Close(); } finally { if (is_Renamed != null) is_Renamed.Close(); } } } if (closeDirSrc) src.Close(); } /// <summary> /// Throws AlreadyClosedException if this Directory is closed. /// </summary> protected internal virtual void EnsureOpen() { if (!isOpen) throw new AlreadyClosedException("this Directory is closed"); } } }
// Copyright 2014 Jacob Trimble // // 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.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using ModMaker.Lua.Runtime.LuaValues; namespace ModMaker.Lua.Runtime { static partial class LuaStaticLibraries { class OS { readonly Stopwatch _stop = Stopwatch.StartNew(); readonly ILuaEnvironment _env; public OS(ILuaEnvironment env) { _env = env; } public void Initialize() { ILuaTable os = new LuaTable(); Register(_env, os, (Func<double>)clock); Register(_env, os, (Func<string, object, object>)date); Register(_env, os, (Func<double, double, double>)difftime); Register(_env, os, (Action<object, object>)exit); Register(_env, os, (Func<string, string>)getenv); Register(_env, os, (Func<string, object[]>)remove); Register(_env, os, (Func<string, string, object[]>)rename); Register(_env, os, (Func<string, string>)setlocale); Register(_env, os, (Func<object, double>)time); Register(_env, os, (Func<string>)tmpname); _env.GlobalsTable.SetItemRaw(new LuaString("os"), os); } double clock() { return _stop.Elapsed.TotalSeconds; } object date(string format = "%c", object source = null) { DateTime time; if (source is double d) { time = new DateTime((long)d); } else if (source is DateTime dt) { time = dt; } else { time = DateTime.Now; } if (format.StartsWith("!")) { format = format.Substring(1); time = time.ToUniversalTime(); } if (format == "*t") { ILuaTable table = new LuaTable(); Action<string, int> set = (a, b) => { table.SetItemRaw(new LuaString(a), LuaNumber.Create(b)); }; set("year", time.Year); set("month", time.Month); set("day", time.Day); set("hour", time.Hour); set("min", time.Minute); set("sec", time.Second); set("wday", ((int)time.DayOfWeek) + 1); set("yday", time.DayOfYear); return table; } StringBuilder ret = new StringBuilder(); for (int i = 0; i < format.Length; i++) { if (format[i] == '%') { i++; switch (format[i]) { case 'a': ret.Append(time.ToString("ddd", CultureInfo.CurrentCulture)); break; case 'A': ret.Append(time.ToString("dddd", CultureInfo.CurrentCulture)); break; case 'b': ret.Append(time.ToString("MMM", CultureInfo.CurrentCulture)); break; case 'B': ret.Append(time.ToString("MMMM", CultureInfo.CurrentCulture)); break; case 'c': ret.Append(time.ToString("F", CultureInfo.CurrentCulture)); break; case 'd': ret.Append(time.ToString("dd", CultureInfo.CurrentCulture)); break; case 'H': ret.Append(time.ToString("HH", CultureInfo.CurrentCulture)); break; case 'I': ret.Append(time.ToString("hh", CultureInfo.CurrentCulture)); break; case 'j': ret.Append(time.DayOfYear.ToString("d3", CultureInfo.CurrentCulture)); break; case 'm': ret.Append(time.Month.ToString("d2", CultureInfo.CurrentCulture)); break; case 'M': ret.Append(time.Minute.ToString("d2", CultureInfo.CurrentCulture)); break; case 'p': ret.Append(time.ToString("tt", CultureInfo.CurrentCulture)); break; case 'S': ret.Append(time.ToString("ss", CultureInfo.CurrentCulture)); break; case 'U': { // See strftime DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo; ret.AppendFormat( "{0:02}", dfi.Calendar.GetWeekOfYear( time, CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday)); break; } case 'V': { // See strftime DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo; ret.AppendFormat( "{0:02}", dfi.Calendar.GetWeekOfYear( time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)); break; } case 'w': ret.Append((int)time.DayOfWeek); break; case 'W': { // See strftime DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo; ret.AppendFormat( "{0:02}", dfi.Calendar.GetWeekOfYear( time, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday)); break; } case 'x': ret.Append(time.ToString("d", CultureInfo.CurrentCulture)); break; case 'X': ret.Append(time.ToString("T", CultureInfo.CurrentCulture)); break; case 'y': ret.Append(time.ToString("yy", CultureInfo.CurrentCulture)); break; case 'Y': ret.Append(time.ToString("yyyy", CultureInfo.CurrentCulture)); break; case 'Z': ret.Append(time.ToString("%K", CultureInfo.CurrentCulture)); break; case '%': ret.Append('%'); break; default: throw new ArgumentException( $"Unrecognized format specifier %{format[i]} in function 'os.date'."); } } else { ret.Append(format[i]); } } return ret.ToString(); } double difftime(double time1, double time2) { return time2 - time1; } void exit(object code = null, object close = null) { _env.Settings._callQuit(_env, code, close); } string getenv(string name) { return System.Environment.GetEnvironmentVariable(name); } [MultipleReturn] object[] remove(string path) { if (File.Exists(path)) { try { File.Delete(path); return new object[] { true }; } catch (Exception e) { return new object[] { null, e.Message, e }; } } else if (Directory.Exists(path)) { if (Directory.EnumerateFileSystemEntries(path).Any()) { return new object[] { null, "Specified directory is not empty." }; } try { Directory.Delete(path); return new object[] { true }; } catch (Exception e) { return new object[] { null, e.Message, e }; } } else { return new object[] { null, "Specified filename does not exist." }; } } [MultipleReturn] object[] rename(string old, string new_) { if (File.Exists(old)) { try { File.Move(old, new_); return new object[] { true }; } catch (Exception e) { return new object[] { null, e.Message, e }; } } else if (Directory.Exists(old)) { try { Directory.Move(old, new_); return new object[] { true }; } catch (Exception e) { return new object[] { null, e.Message, e }; } } else { return new object[] { null, "Specified path does not exist." }; } } string setlocale(string name) { try { CultureInfo ci = CultureInfo.GetCultureInfo(name); if (ci == null) { return null; } Thread.CurrentThread.CurrentCulture = ci; return ci.Name; } catch (Exception) { return null; } } double time(object source) { DateTime time; if (source is ILuaTable table) { int year, month, day, hour, min, sec; Func<string, bool, int> get = (name, req) => { ILuaValue value = table.GetItemRaw(new LuaString(name)); if (value == null || value.ValueType != LuaValueType.Number) { if (req) { throw new ArgumentException( "First argument to function 'os.time' is not a valid time table."); } else { return 0; } } else { return value.As<int>(); } }; year = get("year", true); month = get("month", true); day = get("day", true); hour = get("hour", false); min = get("min", false); sec = get("sec", false); time = new DateTime(year, month, day, hour, min, sec); } else if (source is DateTime dt) { time = dt; } else if (source is DateTimeOffset dto) { time = dto.LocalDateTime; } else if (source != null) { throw new ArgumentException("First argument to function 'os.time' must be a table."); } else { time = DateTime.Now; } return time.Ticks; } string tmpname() { return Path.GetTempFileName(); } } } }
// 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.IO; using System.Collections.Generic; using System.Text; using System.Reflection; using stress.execution; namespace stress.codegen { public class ExecutionFileGeneratorLinux : ISourceFileGenerator { /* * scriptName - name of the script to be generated, this should include the path * testName - the name of the test executable * arguments - arguments to be passed to the test executable * envVars - dictionary of environment variables and their values * host (optional) - needed for hosted runtimes */ public void GenerateSourceFile(LoadTestInfo loadTestInfo) { string lldbInspectionFileName = "inspectCoreWithLLDB.py"; string shellScriptPath = Path.Combine(loadTestInfo.SourceDirectory, "stress.sh"); using (TextWriter stressScript = new StreamWriter(shellScriptPath, false)) { // set the line ending for shell scripts stressScript.NewLine = "\n"; stressScript.WriteLine("!# /bin/sh"); stressScript.WriteLine(); stressScript.WriteLine(); stressScript.WriteLine("# stress script for {0}", loadTestInfo.TestName); stressScript.WriteLine(); stressScript.WriteLine(); stressScript.WriteLine("# environment section"); // first take care of the environment variables foreach (KeyValuePair<string, string> kvp in loadTestInfo.EnvironmentVariables) { stressScript.WriteLine("export {0}={1}", kvp.Key, kvp.Value); } stressScript.WriteLine(); stressScript.WriteLine(); // The default limit for coredumps on Linux and Mac is 0 and needs to be reset to allow core dumps to be created stressScript.WriteLine("# The default limit for coredumps on Linux and Mac is 0 and this needs to be reset to allow core dumps to be created"); stressScript.WriteLine("echo calling [ulimit -c unlimited]"); stressScript.WriteLine("ulimit -c unlimited"); // report the current limits (in theory this should get into the test log) stressScript.WriteLine("echo calling [ulimit -a]"); stressScript.WriteLine("ulimit -a"); stressScript.WriteLine(); stressScript.WriteLine(); // Prepare the test execution line string testCommandLine = loadTestInfo.TestName + ".exe"; // If there is a host then prepend it to the test command line if (!String.IsNullOrEmpty(loadTestInfo.SuiteConfig.Host)) { testCommandLine = loadTestInfo.SuiteConfig.Host + " " + testCommandLine; // If the command line isn't a full path or ./ for current directory then add it to ensure we're using the host in the current directory if ((!loadTestInfo.SuiteConfig.Host.StartsWith("/")) && (!loadTestInfo.SuiteConfig.Host.StartsWith("./"))) { testCommandLine = "./" + testCommandLine; } } stressScript.WriteLine("# test execution"); stressScript.WriteLine("echo calling [{0}]", testCommandLine); stressScript.WriteLine(testCommandLine); // Save off the exit code stressScript.WriteLine("export _EXITCODE=$?"); stressScript.WriteLine("echo test exited with ExitCode: $_EXITCODE"); // Check the return code stressScript.WriteLine("if [ $_EXITCODE != 0 ]"); stressScript.WriteLine("then"); stressScript.WriteLine(" echo Work item failed zipping work item data for coredump analysis"); stressScript.WriteLine($" echo EXEC: $HELIX_PYTHONPATH $HELIX_SCRIPT_ROOT/zip_script.py $HELIX_WORKITEM_ROOT/../{loadTestInfo.TestName}.zip $HELIX_WORKITEM_ROOT $HELIX_WORKITEM_ROOT/execution $HELIX_WORKITEM_ROOT/core_root"); stressScript.WriteLine($" $HELIX_PYTHONPATH $HELIX_SCRIPT_ROOT/zip_script.py -zipFile $HELIX_WORKITEM_ROOT/../{loadTestInfo.TestName}.zip $HELIX_WORKITEM_ROOT $HELIX_WORKITEM_ROOT/execution $HELIX_WORKITEM_ROOT/core_root"); stressScript.WriteLine($" echo uploading coredump zip to $HELIX_RESULTS_CONTAINER_URI{loadTestInfo.TestName}.zip analysis"); stressScript.WriteLine($" echo EXEC: $HELIX_PYTHONPATH $HELIX_SCRIPT_ROOT/upload_result.py -result $HELIX_WORKITEM_ROOT/../{loadTestInfo.TestName}.zip -result_name {loadTestInfo.TestName}.zip -upload_client_type Blob"); stressScript.WriteLine($" $HELIX_PYTHONPATH $HELIX_SCRIPT_ROOT/upload_result.py -result $HELIX_WORKITEM_ROOT/../{loadTestInfo.TestName}.zip -result_name {loadTestInfo.TestName}.zip -upload_client_type Blob"); stressScript.WriteLine("fi"); //// stressScript.WriteLine("zip -r {0}.zip .", testName); //// stressScript.WriteLine("else"); //// stressScript.WriteLine(" echo JRS - Test Passed. Report the pass."); //stressScript.WriteLine("fi"); //stressScript.WriteLine(); //stressScript.WriteLine(); // exit the script with the return code stressScript.WriteLine("exit $_EXITCODE"); } // Add the shell script to the source files loadTestInfo.SourceFiles.Add(new SourceFileInfo(shellScriptPath, SourceFileAction.Binplace)); var shimAssmPath = Assembly.GetAssembly(typeof(StressTestShim)).Location; var shimAssm = Path.GetFileName(shimAssmPath); string shimRefPath = Path.Combine(loadTestInfo.SourceDirectory, shimAssm); File.Copy(shimAssmPath, shimRefPath); loadTestInfo.SourceFiles.Add(new SourceFileInfo(shimAssmPath, SourceFileAction.Binplace)); // Generate the python script, figure out if the run script is being generated into // a specific directory, if so then generate the LLDB python script there as well GenerateLLDBPythonScript(lldbInspectionFileName, loadTestInfo); } // The reason for the spacing and begin/end blocks is that python relies on whitespace instead of things // like being/ends each nested block increases the spaces by 2 public void GenerateLLDBPythonScript(string scriptName, LoadTestInfo loadTestInfo) { // If the application is hosted then the debuggee is the host, otherwise it is the test exe string debuggee = String.IsNullOrEmpty(loadTestInfo.SuiteConfig.Host) ? loadTestInfo.TestName + ".exe" : loadTestInfo.SuiteConfig.Host; // the name of the core file (should be in the current directory) string coreFileName = "core"; // LastEvent.txt will contain the ClrStack, native callstack and last exception (if I can get it) string lastEventFile = "LastEvent.txt"; // LLDBError.txt will contain any error messages from failures to LLDB string lldbErrorFile = "LLDBError.txt"; // Threads.txt will contain full native callstacks for each threads (equivalent of bt all) string threadsFile = "Threads.txt"; string scriptNameWithPath = Path.Combine(loadTestInfo.SourceDirectory, scriptName); using (TextWriter lldbScript = new StreamWriter(scriptNameWithPath, false)) { // set the line ending for linux/mac lldbScript.NewLine = "\n"; lldbScript.WriteLine("import lldb"); // Create the debugger object lldbScript.WriteLine("debugger = lldb.SBDebugger.Create()"); // Create the return object. This contains the return informaton (success/failure, output or error text etc) from the debugger call lldbScript.WriteLine("retobj = lldb.SBCommandReturnObject()"); // Load the SOS plugin lldbScript.WriteLine("debugger.GetCommandInterpreter().HandleCommand(\"plugin load libsosplugin.so\", retobj)"); // Create the target lldbScript.WriteLine("target = debugger.CreateTarget('{0}')", debuggee); // If the target was created successfully lldbScript.WriteLine("if target:"); { // Load the core lldbScript.WriteLine(" process = target.LoadCore('{0}')", coreFileName); { // lldbScript.WriteLine(" debugger.GetCommandInterpreter().HandleCommand(\"sos ClrStack\", retobj)"); lldbScript.WriteLine(" if retobj.Succeeded():"); { lldbScript.WriteLine(" LastEventFile = open('{0}', 'w')", lastEventFile); lldbScript.WriteLine(" LastEventFile.write(retobj.GetOutput())"); lldbScript.WriteLine(" thread = process.GetSelectedThread()"); lldbScript.WriteLine(@" LastEventFile.write('\n'.join(str(frame) for frame in thread))"); lldbScript.WriteLine(" LastEventFile.close()"); } lldbScript.WriteLine(" else:"); { lldbScript.WriteLine(" LLDBErrorFile = open('{0}', 'w')", lldbErrorFile); lldbScript.WriteLine(" LLDBErrorFile.write(retobj.GetError())"); lldbScript.WriteLine(" LLDBErrorFile.close()"); } lldbScript.WriteLine(" ThreadsFile = open('{0}', 'w')", threadsFile); lldbScript.WriteLine(" for thread in process:"); { lldbScript.WriteLine(@" ThreadsFile.write('Thread %s:\n' % str(thread.GetThreadID()))"); lldbScript.WriteLine(" for frame in thread:"); { lldbScript.WriteLine(@" ThreadsFile.write(str(frame)+'\n')"); } } lldbScript.WriteLine(" ThreadsFile.close()"); } } } // Add the python script to the source files loadTestInfo.SourceFiles.Add(new SourceFileInfo(scriptNameWithPath, SourceFileAction.Binplace)); } } public class ExecutionFileGeneratorWindows : ISourceFileGenerator { public void GenerateSourceFile(LoadTestInfo loadTestInfo)// (string scriptName, string testName, Dictionary<string, string> envVars, string host = null) { string batchScriptPath = Path.Combine(loadTestInfo.SourceDirectory, "stress.bat"); using (TextWriter stressScript = new StreamWriter(batchScriptPath, false)) { stressScript.WriteLine("@echo off"); stressScript.WriteLine("REM stress script for " + loadTestInfo.TestName); stressScript.WriteLine(); stressScript.WriteLine(); stressScript.WriteLine("REM environment section"); // first take care of the environment variables foreach (KeyValuePair<string, string> kvp in loadTestInfo.EnvironmentVariables) { stressScript.WriteLine("set {0}={1}", kvp.Key, kvp.Value); } stressScript.WriteLine(); stressScript.WriteLine(); // Prepare the test execution line string testCommandLine = loadTestInfo.TestName + ".exe"; // If there is a host then prepend it to the test command line if (!String.IsNullOrEmpty(loadTestInfo.SuiteConfig.Host)) { testCommandLine = loadTestInfo.SuiteConfig.Host + " " + testCommandLine; } stressScript.WriteLine("REM test execution"); stressScript.WriteLine("echo calling [{0}]", testCommandLine); stressScript.WriteLine(testCommandLine); // Save off the exit code stressScript.WriteLine("set _EXITCODE=%ERRORLEVEL%"); stressScript.WriteLine("echo test exited with ExitCode: %_EXITCODE%"); stressScript.WriteLine(); stressScript.WriteLine(); // // Check the return code // stressScript.WriteLine("if %_EXITCODE% EQU 0 goto :REPORT_PASS"); // stressScript.WriteLine("REM error processing"); // stressScript.WriteLine("echo JRS - Test Failed. Report the failure, call to do the initial dump analysis, zip up the directory and return that along with an event"); // stressScript.WriteLine("goto :END"); // stressScript.WriteLine(); // stressScript.WriteLine(); // // stressScript.WriteLine(":REPORT_PASS"); // stressScript.WriteLine("echo JRS - Test Passed. Report the pass."); // stressScript.WriteLine(); // stressScript.WriteLine(); // exit the script with the exit code from the process stressScript.WriteLine(":END"); stressScript.WriteLine("exit /b %_EXITCODE%"); } // Add the batch script to the source files loadTestInfo.SourceFiles.Add(new SourceFileInfo(batchScriptPath, SourceFileAction.Binplace)); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Authorization; using Microsoft.Azure.Management.Authorization.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Authorization { /// <summary> /// Get resource or resource group permissions (see http://TBD for more /// information) /// </summary> internal partial class PermissionOperations : IServiceOperations<AuthorizationManagementClient>, IPermissionOperations { public const string APIVersion = "api-version=2015-07-01"; /// <summary> /// Initializes a new instance of the PermissionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PermissionOperations(AuthorizationManagementClient client) { this._client = client; } private AuthorizationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Authorization.AuthorizationManagementClient. /// </summary> public AuthorizationManagementClient Client { get { return this._client; } } /// <summary> /// Gets a resource permissions. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Permissions information. /// </returns> public async Task<PermissionGetResult> ListForResourceAsync(string resourceGroupName, ResourceIdentity identity, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (identity == null) { throw new ArgumentNullException("identity"); } if (identity.ResourceName == null) { throw new ArgumentNullException("identity."); } if (identity.ResourceProviderNamespace == null) { throw new ArgumentNullException("identity."); } if (identity.ResourceType == null) { throw new ArgumentNullException("identity."); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("identity", identity); TracingAdapter.Enter(invocationId, this, "ListForResourceAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(identity.ResourceProviderNamespace); url = url + "/"; if (identity.ParentResourcePath != null) { url = url + identity.ParentResourcePath; } url = url + "/"; url = url + identity.ResourceType; url = url + "/"; url = url + Uri.EscapeDataString(identity.ResourceName); url = url + "/providers/Microsoft.Authorization/permissions"; List<string> queryParameters = new List<string>(); queryParameters.Add(APIVersion); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result PermissionGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PermissionGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Permission permissionInstance = new Permission(); result.Permissions.Add(permissionInstance); JToken actionsArray = valueValue["actions"]; if (actionsArray != null && actionsArray.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray)) { permissionInstance.Actions.Add(((string)actionsValue)); } } JToken notActionsArray = valueValue["notActions"]; if (notActionsArray != null && notActionsArray.Type != JTokenType.Null) { foreach (JToken notActionsValue in ((JArray)notActionsArray)) { permissionInstance.NotActions.Add(((string)notActionsValue)); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a resource group permissions. /// </summary> /// <param name='resourceGroupName'> /// Required. Name of the resource group to get the permissions for.The /// name is case insensitive. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Permissions information. /// </returns> public async Task<PermissionGetResult> ListForResourceGroupAsync(string resourceGroupName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); TracingAdapter.Enter(invocationId, this, "ListForResourceGroupAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.Authorization/permissions"; List<string> queryParameters = new List<string>(); queryParameters.Add(APIVersion); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result PermissionGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PermissionGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Permission permissionInstance = new Permission(); result.Permissions.Add(permissionInstance); JToken actionsArray = valueValue["actions"]; if (actionsArray != null && actionsArray.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray)) { permissionInstance.Actions.Add(((string)actionsValue)); } } JToken notActionsArray = valueValue["notActions"]; if (notActionsArray != null && notActionsArray.Type != JTokenType.Null) { foreach (JToken notActionsValue in ((JArray)notActionsArray)) { permissionInstance.NotActions.Add(((string)notActionsValue)); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; #if !(NET20 || NET35 || PORTABLE40 || PORTABLE || ASPNETCORE50) using System.Numerics; #endif using System.Runtime.Serialization; using System.Text; #if !(NET20 || NET35) using System.Threading.Tasks; #endif using System.Xml; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.Serialization; using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Utilities; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #elif ASPNETCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif namespace Newtonsoft.Json.Tests { [TestFixture] public class JsonConvertTest : TestFixtureBase { [Test] public void DefaultSettings() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; string json = JsonConvert.SerializeObject(new { test = new[] { 1, 2, 3 } }); StringAssert.AreEqual(@"{ ""test"": [ 1, 2, 3 ] }", json); } finally { JsonConvert.DefaultSettings = null; } } public class NameTableTestClass { public string Value { get; set; } } public class NameTableTestClassConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { reader.Read(); reader.Read(); JsonTextReader jsonTextReader = (JsonTextReader)reader; Assert.IsNotNull(jsonTextReader.NameTable); string s = serializer.Deserialize<string>(reader); Assert.AreEqual("hi", s); Assert.IsNotNull(jsonTextReader.NameTable); NameTableTestClass o = new NameTableTestClass { Value = s }; return o; } public override bool CanConvert(Type objectType) { return objectType == typeof(NameTableTestClass); } } [Test] public void NameTableTest() { StringReader sr = new StringReader("{'property':'hi'}"); JsonTextReader jsonTextReader = new JsonTextReader(sr); Assert.IsNull(jsonTextReader.NameTable); JsonSerializer serializer = new JsonSerializer(); serializer.Converters.Add(new NameTableTestClassConverter()); NameTableTestClass o = serializer.Deserialize<NameTableTestClass>(jsonTextReader); Assert.IsNull(jsonTextReader.NameTable); Assert.AreEqual("hi", o.Value); } [Test] public void DefaultSettings_Example() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented, ContractResolver = new CamelCasePropertyNamesContractResolver() }; Employee e = new Employee { FirstName = "Eric", LastName = "Example", BirthDate = new DateTime(1980, 4, 20, 0, 0, 0, DateTimeKind.Utc), Department = "IT", JobTitle = "Web Dude" }; string json = JsonConvert.SerializeObject(e); // { // "firstName": "Eric", // "lastName": "Example", // "birthDate": "1980-04-20T00:00:00Z", // "department": "IT", // "jobTitle": "Web Dude" // } StringAssert.AreEqual(@"{ ""firstName"": ""Eric"", ""lastName"": ""Example"", ""birthDate"": ""1980-04-20T00:00:00Z"", ""department"": ""IT"", ""jobTitle"": ""Web Dude"" }", json); } finally { JsonConvert.DefaultSettings = null; } } [Test] public void DefaultSettings_Override() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; string json = JsonConvert.SerializeObject(new { test = new[] { 1, 2, 3 } }, new JsonSerializerSettings { Formatting = Formatting.None }); Assert.AreEqual(@"{""test"":[1,2,3]}", json); } finally { JsonConvert.DefaultSettings = null; } } [Test] public void DefaultSettings_Override_JsonConverterOrder() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented, Converters = { new IsoDateTimeConverter { DateTimeFormat = "yyyy" } } }; string json = JsonConvert.SerializeObject(new[] { new DateTime(2000, 12, 12, 4, 2, 4, DateTimeKind.Utc) }, new JsonSerializerSettings { Formatting = Formatting.None, Converters = { // should take precedence new JavaScriptDateTimeConverter(), new IsoDateTimeConverter { DateTimeFormat = "dd" } } }); Assert.AreEqual(@"[new Date(976593724000)]", json); } finally { JsonConvert.DefaultSettings = null; } } [Test] public void DefaultSettings_Create() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; IList<int> l = new List<int> { 1, 2, 3 }; StringWriter sw = new StringWriter(); JsonSerializer serializer = JsonSerializer.CreateDefault(); serializer.Serialize(sw, l); StringAssert.AreEqual(@"[ 1, 2, 3 ]", sw.ToString()); sw = new StringWriter(); serializer.Formatting = Formatting.None; serializer.Serialize(sw, l); Assert.AreEqual(@"[1,2,3]", sw.ToString()); sw = new StringWriter(); serializer = new JsonSerializer(); serializer.Serialize(sw, l); Assert.AreEqual(@"[1,2,3]", sw.ToString()); sw = new StringWriter(); serializer = JsonSerializer.Create(); serializer.Serialize(sw, l); Assert.AreEqual(@"[1,2,3]", sw.ToString()); } finally { JsonConvert.DefaultSettings = null; } } [Test] public void DefaultSettings_CreateWithSettings() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; IList<int> l = new List<int> { 1, 2, 3 }; StringWriter sw = new StringWriter(); JsonSerializer serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings { Converters = { new IntConverter() } }); serializer.Serialize(sw, l); StringAssert.AreEqual(@"[ 2, 4, 6 ]", sw.ToString()); sw = new StringWriter(); serializer.Converters.Clear(); serializer.Serialize(sw, l); StringAssert.AreEqual(@"[ 1, 2, 3 ]", sw.ToString()); sw = new StringWriter(); serializer = JsonSerializer.Create(new JsonSerializerSettings { Formatting = Formatting.Indented }); serializer.Serialize(sw, l); StringAssert.AreEqual(@"[ 1, 2, 3 ]", sw.ToString()); } finally { JsonConvert.DefaultSettings = null; } } public class IntConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { int i = (int)value; writer.WriteValue(i * 2); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanConvert(Type objectType) { return objectType == typeof(int); } } [Test] public void DeserializeObject_EmptyString() { object result = JsonConvert.DeserializeObject(string.Empty); Assert.IsNull(result); } [Test] public void DeserializeObject_Integer() { object result = JsonConvert.DeserializeObject("1"); Assert.AreEqual(1L, result); } [Test] public void DeserializeObject_Integer_EmptyString() { int? value = JsonConvert.DeserializeObject<int?>(""); Assert.IsNull(value); } [Test] public void DeserializeObject_Decimal_EmptyString() { decimal? value = JsonConvert.DeserializeObject<decimal?>(""); Assert.IsNull(value); } [Test] public void DeserializeObject_DateTime_EmptyString() { DateTime? value = JsonConvert.DeserializeObject<DateTime?>(""); Assert.IsNull(value); } [Test] public void EscapeJavaScriptString() { string result; result = JavaScriptUtils.ToEscapedJavaScriptString("How now brown cow?", '"', true); Assert.AreEqual(@"""How now brown cow?""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("How now 'brown' cow?", '"', true); Assert.AreEqual(@"""How now 'brown' cow?""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("How now <brown> cow?", '"', true); Assert.AreEqual(@"""How now <brown> cow?""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("How \r\nnow brown cow?", '"', true); Assert.AreEqual(@"""How \r\nnow brown cow?""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007", '"', true); Assert.AreEqual(@"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013", '"', true); Assert.AreEqual(@"""\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013""", result); result = JavaScriptUtils.ToEscapedJavaScriptString( "\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f ", '"', true); Assert.AreEqual(@"""\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f """, result); result = JavaScriptUtils.ToEscapedJavaScriptString( "!\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]", '"', true); Assert.AreEqual(@"""!\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("^_`abcdefghijklmnopqrstuvwxyz{|}~", '"', true); Assert.AreEqual(@"""^_`abcdefghijklmnopqrstuvwxyz{|}~""", result); string data = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; string expected = @"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""; result = JavaScriptUtils.ToEscapedJavaScriptString(data, '"', true); Assert.AreEqual(expected, result); result = JavaScriptUtils.ToEscapedJavaScriptString("Fred's cat.", '\'', true); Assert.AreEqual(result, @"'Fred\'s cat.'"); result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are you gentlemen?"" said Cats.", '"', true); Assert.AreEqual(result, @"""\""How are you gentlemen?\"" said Cats."""); result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are' you gentlemen?"" said Cats.", '"', true); Assert.AreEqual(result, @"""\""How are' you gentlemen?\"" said Cats."""); result = JavaScriptUtils.ToEscapedJavaScriptString(@"Fred's ""cat"".", '\'', true); Assert.AreEqual(result, @"'Fred\'s ""cat"".'"); result = JavaScriptUtils.ToEscapedJavaScriptString("\u001farray\u003caddress", '"', true); Assert.AreEqual(result, @"""\u001farray<address"""); } [Test] public void EscapeJavaScriptString_UnicodeLinefeeds() { string result; result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u0085' + "after", '"', true); Assert.AreEqual(@"""before\u0085after""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2028' + "after", '"', true); Assert.AreEqual(@"""before\u2028after""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2029' + "after", '"', true); Assert.AreEqual(@"""before\u2029after""", result); } [Test] public void ToStringInvalid() { ExceptionAssert.Throws<ArgumentException>(() => { JsonConvert.ToString(new Version(1, 0)); }, "Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation."); } [Test] public void GuidToString() { Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D"); string json = JsonConvert.ToString(guid); Assert.AreEqual(@"""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""", json); } [Test] public void EnumToString() { string json = JsonConvert.ToString(StringComparison.CurrentCultureIgnoreCase); Assert.AreEqual("1", json); } [Test] public void ObjectToString() { object value; value = 1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = 1.1; Assert.AreEqual("1.1", JsonConvert.ToString(value)); value = 1.1m; Assert.AreEqual("1.1", JsonConvert.ToString(value)); value = (float)1.1; Assert.AreEqual("1.1", JsonConvert.ToString(value)); value = (short)1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = (long)1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = (byte)1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = (uint)1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = (ushort)1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = (sbyte)1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = (ulong)1; Assert.AreEqual("1", JsonConvert.ToString(value)); value = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc); Assert.AreEqual(@"""1970-01-01T00:00:00Z""", JsonConvert.ToString(value)); value = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc); Assert.AreEqual(@"""\/Date(0)\/""", JsonConvert.ToString((DateTime)value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind)); #if !NET20 value = new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero); Assert.AreEqual(@"""1970-01-01T00:00:00+00:00""", JsonConvert.ToString(value)); value = new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero); Assert.AreEqual(@"""\/Date(0+0000)\/""", JsonConvert.ToString((DateTimeOffset)value, DateFormatHandling.MicrosoftDateFormat)); #endif value = null; Assert.AreEqual("null", JsonConvert.ToString(value)); #if !(NETFX_CORE || PORTABLE || ASPNETCORE50 || PORTABLE40) value = DBNull.Value; Assert.AreEqual("null", JsonConvert.ToString(value)); #endif value = "I am a string"; Assert.AreEqual(@"""I am a string""", JsonConvert.ToString(value)); value = true; Assert.AreEqual("true", JsonConvert.ToString(value)); value = 'c'; Assert.AreEqual(@"""c""", JsonConvert.ToString(value)); } [Test] public void TestInvalidStrings() { ExceptionAssert.Throws<JsonReaderException>(() => { string orig = @"this is a string ""that has quotes"" "; string serialized = JsonConvert.SerializeObject(orig); // *** Make string invalid by stripping \" \" serialized = serialized.Replace(@"\""", "\""); JsonConvert.DeserializeObject<string>(serialized); }, "Additional text encountered after finished reading JSON content: t. Path '', line 1, position 19."); } [Test] public void DeserializeValueObjects() { int i = JsonConvert.DeserializeObject<int>("1"); Assert.AreEqual(1, i); #if !NET20 DateTimeOffset d = JsonConvert.DeserializeObject<DateTimeOffset>(@"""\/Date(-59011455539000+0000)\/"""); Assert.AreEqual(new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)), d); #endif bool b = JsonConvert.DeserializeObject<bool>("true"); Assert.AreEqual(true, b); object n = JsonConvert.DeserializeObject<object>("null"); Assert.AreEqual(null, n); object u = JsonConvert.DeserializeObject<object>("undefined"); Assert.AreEqual(null, u); } [Test] public void FloatToString() { Assert.AreEqual("1.1", JsonConvert.ToString(1.1)); Assert.AreEqual("1.11", JsonConvert.ToString(1.11)); Assert.AreEqual("1.111", JsonConvert.ToString(1.111)); Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111)); Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111)); Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111)); Assert.AreEqual("1.0", JsonConvert.ToString(1.0)); Assert.AreEqual("1.0", JsonConvert.ToString(1d)); Assert.AreEqual("-1.0", JsonConvert.ToString(-1d)); Assert.AreEqual("1.01", JsonConvert.ToString(1.01)); Assert.AreEqual("1.001", JsonConvert.ToString(1.001)); Assert.AreEqual(JsonConvert.PositiveInfinity, JsonConvert.ToString(Double.PositiveInfinity)); Assert.AreEqual(JsonConvert.NegativeInfinity, JsonConvert.ToString(Double.NegativeInfinity)); Assert.AreEqual(JsonConvert.NaN, JsonConvert.ToString(Double.NaN)); } [Test] public void DecimalToString() { Assert.AreEqual("1.1", JsonConvert.ToString(1.1m)); Assert.AreEqual("1.11", JsonConvert.ToString(1.11m)); Assert.AreEqual("1.111", JsonConvert.ToString(1.111m)); Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111m)); Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111m)); Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111m)); Assert.AreEqual("1.0", JsonConvert.ToString(1.0m)); Assert.AreEqual("-1.0", JsonConvert.ToString(-1.0m)); Assert.AreEqual("-1.0", JsonConvert.ToString(-1m)); Assert.AreEqual("1.0", JsonConvert.ToString(1m)); Assert.AreEqual("1.01", JsonConvert.ToString(1.01m)); Assert.AreEqual("1.001", JsonConvert.ToString(1.001m)); Assert.AreEqual("79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MaxValue)); Assert.AreEqual("-79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MinValue)); } [Test] public void StringEscaping() { string v = "It's a good day\r\n\"sunshine\""; string json = JsonConvert.ToString(v); Assert.AreEqual(@"""It's a good day\r\n\""sunshine\""""", json); } [Test] public void ToStringStringEscapeHandling() { string v = "<b>hi " + '\u20AC' + "</b>"; string json = JsonConvert.ToString(v, '"'); Assert.AreEqual(@"""<b>hi " + '\u20AC' + @"</b>""", json); json = JsonConvert.ToString(v, '"', StringEscapeHandling.EscapeHtml); Assert.AreEqual(@"""\u003cb\u003ehi " + '\u20AC' + @"\u003c/b\u003e""", json); json = JsonConvert.ToString(v, '"', StringEscapeHandling.EscapeNonAscii); Assert.AreEqual(@"""<b>hi \u20ac</b>""", json); } [Test] public void WriteDateTime() { DateTimeResult result = null; result = TestDateTime("DateTime Max", DateTime.MaxValue); Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateRoundtrip); Assert.AreEqual("9999-12-31T23:59:59.9999999" + GetOffset(DateTime.MaxValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateUnspecified); Assert.AreEqual("9999-12-31T23:59:59.9999999Z", result.IsoDateUtc); Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(253402300799999" + GetOffset(DateTime.MaxValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUtc); DateTime year2000local = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local); string localToUtcDate = year2000local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK"); result = TestDateTime("DateTime Local", year2000local); Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip); Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified); Assert.AreEqual(localToUtcDate, result.IsoDateUtc); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + @")\/", result.MsDateUtc); DateTime millisecondsLocal = new DateTime(2000, 1, 1, 1, 1, 1, 999, DateTimeKind.Local); localToUtcDate = millisecondsLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK"); result = TestDateTime("DateTime Local with milliseconds", millisecondsLocal); Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip); Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("2000-01-01T01:01:01.999", result.IsoDateUnspecified); Assert.AreEqual(localToUtcDate, result.IsoDateUtc); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + @")\/", result.MsDateUtc); DateTime ticksLocal = new DateTime(634663873826822481, DateTimeKind.Local); localToUtcDate = ticksLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK"); result = TestDateTime("DateTime Local with ticks", ticksLocal); Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip); Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("2012-03-03T16:03:02.6822481", result.IsoDateUnspecified); Assert.AreEqual(localToUtcDate, result.IsoDateUtc); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + @")\/", result.MsDateUtc); DateTime year2000Unspecified = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified); result = TestDateTime("DateTime Unspecified", year2000Unspecified); Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateRoundtrip); Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000Unspecified, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified); Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified.ToLocalTime()) + @")\/", result.MsDateUtc); DateTime year2000Utc = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc); string utcTolocalDate = year2000Utc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss"); result = TestDateTime("DateTime Utc", year2000Utc); Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateRoundtrip); Assert.AreEqual(utcTolocalDate + GetOffset(year2000Utc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified); Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc); Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(946688461000" + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(year2000Utc, DateTimeKind.Unspecified)) + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateUtc); DateTime unixEpoc = new DateTime(621355968000000000, DateTimeKind.Utc); utcTolocalDate = unixEpoc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss"); result = TestDateTime("DateTime Unix Epoc", unixEpoc); Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateRoundtrip); Assert.AreEqual(utcTolocalDate + GetOffset(unixEpoc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("1970-01-01T00:00:00", result.IsoDateUnspecified); Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateUtc); Assert.AreEqual(@"\/Date(0)\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(0" + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(unixEpoc, DateTimeKind.Unspecified)) + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(0)\/", result.MsDateUtc); result = TestDateTime("DateTime Min", DateTime.MinValue); Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip); Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(DateTime.MinValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified); Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc); Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(DateTime.MinValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc); result = TestDateTime("DateTime Default", default(DateTime)); Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip); Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(default(DateTime), DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified); Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc); Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip); Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(default(DateTime), DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified); Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc); #if !NET20 result = TestDateTime("DateTimeOffset TimeSpan Zero", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); Assert.AreEqual("2000-01-01T01:01:01+00:00", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(946688461000+0000)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset TimeSpan 1 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1))); Assert.AreEqual("2000-01-01T01:01:01+01:00", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(946684861000+0100)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset TimeSpan 1.5 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1.5))); Assert.AreEqual("2000-01-01T01:01:01+01:30", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(946683061000+0130)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset TimeSpan 13 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13))); Assert.AreEqual("2000-01-01T01:01:01+13:00", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(946641661000+1300)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset TimeSpan with ticks", new DateTimeOffset(634663873826822481, TimeSpan.Zero)); Assert.AreEqual("2012-03-03T16:03:02.6822481+00:00", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(1330790582682+0000)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset Min", DateTimeOffset.MinValue); Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset Max", DateTimeOffset.MaxValue); Assert.AreEqual("9999-12-31T23:59:59.9999999+00:00", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(253402300799999+0000)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset Default", default(DateTimeOffset)); Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip); Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip); #endif } public class DateTimeResult { public string IsoDateRoundtrip { get; set; } public string IsoDateLocal { get; set; } public string IsoDateUnspecified { get; set; } public string IsoDateUtc { get; set; } public string MsDateRoundtrip { get; set; } public string MsDateLocal { get; set; } public string MsDateUnspecified { get; set; } public string MsDateUtc { get; set; } } private DateTimeResult TestDateTime<T>(string name, T value) { Console.WriteLine(name); DateTimeResult result = new DateTimeResult(); result.IsoDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); if (value is DateTime) { result.IsoDateLocal = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Local); result.IsoDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Unspecified); result.IsoDateUtc = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Utc); } result.MsDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind); if (value is DateTime) { result.MsDateLocal = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Local); result.MsDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Unspecified); result.MsDateUtc = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Utc); } TestDateTimeFormat(value, new IsoDateTimeConverter()); #if !NETFX_CORE if (value is DateTime) { Console.WriteLine(XmlConvert.ToString((DateTime)(object)value, XmlDateTimeSerializationMode.RoundtripKind)); } else { Console.WriteLine(XmlConvert.ToString((DateTimeOffset)(object)value)); } #endif #if !NET20 MemoryStream ms = new MemoryStream(); DataContractSerializer s = new DataContractSerializer(typeof(T)); s.WriteObject(ms, value); string json = Encoding.UTF8.GetString(ms.ToArray(), 0, Convert.ToInt32(ms.Length)); Console.WriteLine(json); #endif Console.WriteLine(); return result; } private static string TestDateTimeFormat<T>(T value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { string date = null; if (value is DateTime) { date = JsonConvert.ToString((DateTime)(object)value, format, timeZoneHandling); } else { #if !NET20 date = JsonConvert.ToString((DateTimeOffset)(object)value, format); #endif } Console.WriteLine(format.ToString("g") + "-" + timeZoneHandling.ToString("g") + ": " + date); if (timeZoneHandling == DateTimeZoneHandling.RoundtripKind) { T parsed = JsonConvert.DeserializeObject<T>(date); try { Assert.AreEqual(value, parsed); } catch (Exception) { long valueTicks = GetTicks(value); long parsedTicks = GetTicks(parsed); valueTicks = (valueTicks / 10000) * 10000; Assert.AreEqual(valueTicks, parsedTicks); } } return date.Trim('"'); } private static void TestDateTimeFormat<T>(T value, JsonConverter converter) { string date = Write(value, converter); Console.WriteLine(converter.GetType().Name + ": " + date); T parsed = Read<T>(date, converter); try { Assert.AreEqual(value, parsed); } catch (Exception) { // JavaScript ticks aren't as precise, recheck after rounding long valueTicks = GetTicks(value); long parsedTicks = GetTicks(parsed); valueTicks = (valueTicks / 10000) * 10000; Assert.AreEqual(valueTicks, parsedTicks); } } public static long GetTicks(object value) { return (value is DateTime) ? ((DateTime)value).Ticks : ((DateTimeOffset)value).Ticks; } public static string Write(object value, JsonConverter converter) { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); converter.WriteJson(writer, value, null); writer.Flush(); return sw.ToString(); } public static T Read<T>(string text, JsonConverter converter) { JsonTextReader reader = new JsonTextReader(new StringReader(text)); reader.ReadAsString(); return (T)converter.ReadJson(reader, typeof(T), null, null); } #if !(NET20 || NET35 || PORTABLE40) [Test] public void Async() { Task<string> task = null; #pragma warning disable 612,618 task = JsonConvert.SerializeObjectAsync(42); #pragma warning restore 612,618 task.Wait(); Assert.AreEqual("42", task.Result); #pragma warning disable 612,618 task = JsonConvert.SerializeObjectAsync(new[] { 1, 2, 3, 4, 5 }, Formatting.Indented); #pragma warning restore 612,618 task.Wait(); StringAssert.AreEqual(@"[ 1, 2, 3, 4, 5 ]", task.Result); #pragma warning disable 612,618 task = JsonConvert.SerializeObjectAsync(DateTime.MaxValue, Formatting.None, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat }); #pragma warning restore 612,618 task.Wait(); Assert.AreEqual(@"""\/Date(253402300799999)\/""", task.Result); #pragma warning disable 612,618 var taskObject = JsonConvert.DeserializeObjectAsync("[]"); #pragma warning restore 612,618 taskObject.Wait(); CollectionAssert.AreEquivalent(new JArray(), (JArray)taskObject.Result); #pragma warning disable 612,618 Task<object> taskVersionArray = JsonConvert.DeserializeObjectAsync("['2.0']", typeof(Version[]), new JsonSerializerSettings { Converters = { new VersionConverter() } }); #pragma warning restore 612,618 taskVersionArray.Wait(); Version[] versionArray = (Version[])taskVersionArray.Result; Assert.AreEqual(1, versionArray.Length); Assert.AreEqual(2, versionArray[0].Major); #pragma warning disable 612,618 Task<int> taskInt = JsonConvert.DeserializeObjectAsync<int>("5"); #pragma warning restore 612,618 taskInt.Wait(); Assert.AreEqual(5, taskInt.Result); #pragma warning disable 612,618 var taskVersion = JsonConvert.DeserializeObjectAsync<Version>("'2.0'", new JsonSerializerSettings { Converters = { new VersionConverter() } }); #pragma warning restore 612,618 taskVersion.Wait(); Assert.AreEqual(2, taskVersion.Result.Major); Movie p = new Movie(); p.Name = "Existing,"; #pragma warning disable 612,618 Task taskVoid = JsonConvert.PopulateObjectAsync("{'Name':'Appended'}", p, new JsonSerializerSettings { Converters = new List<JsonConverter> { new StringAppenderConverter() } }); #pragma warning restore 612,618 taskVoid.Wait(); Assert.AreEqual("Existing,Appended", p.Name); } #endif [Test] public void SerializeObjectDateTimeZoneHandling() { string json = JsonConvert.SerializeObject( new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified), new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); Assert.AreEqual(@"""2000-01-01T01:01:01Z""", json); } [Test] public void DeserializeObject() { string json = @"{ 'Name': 'Bad Boys', 'ReleaseDate': '1995-4-7T00:00:00', 'Genres': [ 'Action', 'Comedy' ] }"; Movie m = JsonConvert.DeserializeObject<Movie>(json); string name = m.Name; // Bad Boys Assert.AreEqual("Bad Boys", m.Name); } #if !NET20 [Test] public void TestJsonDateTimeOffsetRoundtrip() { var now = DateTimeOffset.Now; var dict = new Dictionary<string, object> { { "foo", now } }; var settings = new JsonSerializerSettings(); settings.DateFormatHandling = DateFormatHandling.IsoDateFormat; settings.DateParseHandling = DateParseHandling.DateTimeOffset; settings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; var json = JsonConvert.SerializeObject(dict, settings); Console.WriteLine(json); var newDict = new Dictionary<string, object>(); JsonConvert.PopulateObject(json, newDict, settings); var date = newDict["foo"]; Assert.AreEqual(date, now); } [Test] public void MaximumDateTimeOffsetLength() { DateTimeOffset dt = new DateTimeOffset(2000, 12, 31, 20, 59, 59, new TimeSpan(0, 11, 33, 0, 0)); dt = dt.AddTicks(9999999); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(dt); writer.Flush(); Console.WriteLine(sw.ToString()); Console.WriteLine(sw.ToString().Length); } #endif [Test] public void MaximumDateTimeLength() { DateTime dt = new DateTime(2000, 12, 31, 20, 59, 59, DateTimeKind.Local); dt = dt.AddTicks(9999999); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(dt); writer.Flush(); Console.WriteLine(sw.ToString()); Console.WriteLine(sw.ToString().Length); } [Test] public void MaximumDateTimeMicrosoftDateFormatLength() { DateTime dt = DateTime.MaxValue; StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; writer.WriteValue(dt); writer.Flush(); Console.WriteLine(sw.ToString()); Console.WriteLine(sw.ToString().Length); } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE || ASPNETCORE50) [Test] public void IntegerLengthOverflows() { // Maximum javascript number length (in characters) is 380 JObject o = JObject.Parse(@"{""biginteger"":" + new String('9', 380) + "}"); JValue v = (JValue)o["biginteger"]; Assert.AreEqual(JTokenType.Integer, v.Type); Assert.AreEqual(typeof(BigInteger), v.Value.GetType()); Assert.AreEqual(BigInteger.Parse(new String('9', 380)), (BigInteger)v.Value); ExceptionAssert.Throws<JsonReaderException>(() => JObject.Parse(@"{""biginteger"":" + new String('9', 381) + "}"), "JSON integer " + new String('9', 381) + " is too large to parse. Path 'biginteger', line 1, position 395."); } #endif [Test] public void ParseIsoDate() { StringReader sr = new StringReader(@"""2014-02-14T14:25:02-13:00"""); JsonReader jsonReader = new JsonTextReader(sr); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(typeof(DateTime), jsonReader.ValueType); } //[Test] public void StackOverflowTest() { StringBuilder sb = new StringBuilder(); int depth = 900; for (int i = 0; i < depth; i++) { sb.Append("{'A':"); } // invalid json sb.Append("{***}"); for (int i = 0; i < depth; i++) { sb.Append("}"); } string json = sb.ToString(); JsonSerializer serializer = new JsonSerializer() { }; serializer.Deserialize<Nest>(new JsonTextReader(new StringReader(json))); } public class Nest { public Nest A { get; set; } } [Test] public void ParametersPassedToJsonConverterConstructor() { ClobberMyProperties clobber = new ClobberMyProperties { One = "Red", Two = "Green", Three = "Yellow", Four = "Black" }; string json = JsonConvert.SerializeObject(clobber); Assert.AreEqual("{\"One\":\"Uno-1-Red\",\"Two\":\"Dos-2-Green\",\"Three\":\"Tres-1337-Yellow\",\"Four\":\"Black\"}", json); } public class ClobberMyProperties { [JsonConverter(typeof(ClobberingJsonConverter), "Uno", 1)] public string One { get; set; } [JsonConverter(typeof(ClobberingJsonConverter), "Dos", 2)] public string Two { get; set; } [JsonConverter(typeof(ClobberingJsonConverter), "Tres")] public string Three { get; set; } public string Four { get; set; } } public class ClobberingJsonConverter : JsonConverter { public string ClobberValueString { get; private set; } public int ClobberValueInt { get; private set; } public ClobberingJsonConverter(string clobberValueString, int clobberValueInt) { ClobberValueString = clobberValueString; ClobberValueInt = clobberValueInt; } public ClobberingJsonConverter(string clobberValueString) : this(clobberValueString, 1337) { } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(ClobberValueString + "-" + ClobberValueInt.ToString() + "-" + value.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanConvert(Type objectType) { return objectType == typeof(string); } } [Test] public void WrongParametersPassedToJsonConvertConstructorShouldThrow() { IncorrectJsonConvertParameters value = new IncorrectJsonConvertParameters { One = "Boom" }; ExceptionAssert.Throws<JsonException>(() => { JsonConvert.SerializeObject(value); }); } public class IncorrectJsonConvertParameters { /// <summary> /// We deliberately use the wrong number/type of arguments for ClobberingJsonConverter to ensure an /// exception is thrown. /// </summary> [JsonConverter(typeof(ClobberingJsonConverter), "Uno", "Blammo")] public string One { get; set; } } [Test] public void CustomDoubleRounding() { var measurements = new Measurements { Loads = new List<double> { 23283.567554707258, 23224.849899771067, 23062.5, 22846.272519910868, 22594.281246368635 }, Positions = new List<double> { 57.724227689317019, 60.440934405753069, 63.444192925248643, 66.813119113482557, 70.4496501404433 }, Gain = 12345.67895111213 }; string json = JsonConvert.SerializeObject(measurements); Assert.AreEqual("{\"Positions\":[57.72,60.44,63.44,66.81,70.45],\"Loads\":[23284.0,23225.0,23062.0,22846.0,22594.0],\"Gain\":12345.679}", json); } public class Measurements { [JsonProperty(ItemConverterType = typeof(RoundingJsonConverter))] public List<double> Positions { get; set; } [JsonProperty(ItemConverterType = typeof(RoundingJsonConverter), ItemConverterParameters = new object[] { 0, MidpointRounding.ToEven })] public List<double> Loads { get; set; } [JsonConverter(typeof(RoundingJsonConverter), 4)] public double Gain { get; set; } } public class RoundingJsonConverter : JsonConverter { int _precision; MidpointRounding _rounding; public RoundingJsonConverter() : this(2) { } public RoundingJsonConverter(int precision) : this(precision, MidpointRounding.AwayFromZero) { } public RoundingJsonConverter(int precision, MidpointRounding rounding) { _precision = precision; _rounding = rounding; } public override bool CanRead { get { return false; } } public override bool CanConvert(Type objectType) { return objectType == typeof(double); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(Math.Round((double)value, _precision, _rounding)); } } } }
// 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.Security.Cryptography.Asn1; using System.Security.Cryptography.Pkcs.Asn1; using System.Security.Cryptography.X509Certificates; using Internal.Cryptography; namespace System.Security.Cryptography.Pkcs { internal partial class CmsSignature { static partial void PrepareRegistrationRsa(Dictionary<string, CmsSignature> lookup) { lookup.Add(Oids.Rsa, new RSAPkcs1CmsSignature(null, null)); lookup.Add(Oids.RsaPkcs1Sha1, new RSAPkcs1CmsSignature(Oids.RsaPkcs1Sha1, HashAlgorithmName.SHA1)); lookup.Add(Oids.RsaPkcs1Sha256, new RSAPkcs1CmsSignature(Oids.RsaPkcs1Sha256, HashAlgorithmName.SHA256)); lookup.Add(Oids.RsaPkcs1Sha384, new RSAPkcs1CmsSignature(Oids.RsaPkcs1Sha384, HashAlgorithmName.SHA384)); lookup.Add(Oids.RsaPkcs1Sha512, new RSAPkcs1CmsSignature(Oids.RsaPkcs1Sha512, HashAlgorithmName.SHA512)); lookup.Add(Oids.RsaPss, new RSAPssCmsSignature()); } private abstract class RSACmsSignature : CmsSignature { private readonly string _signatureAlgorithm; private readonly HashAlgorithmName? _expectedDigest; protected RSACmsSignature(string signatureAlgorithm, HashAlgorithmName? expectedDigest) { _signatureAlgorithm = signatureAlgorithm; _expectedDigest = expectedDigest; } protected override bool VerifyKeyType(AsymmetricAlgorithm key) { return (key as RSA) != null; } internal override bool VerifySignature( #if NETCOREAPP || NETSTANDARD2_1 ReadOnlySpan<byte> valueHash, ReadOnlyMemory<byte> signature, #else byte[] valueHash, byte[] signature, #endif string digestAlgorithmOid, HashAlgorithmName digestAlgorithmName, ReadOnlyMemory<byte>? signatureParameters, X509Certificate2 certificate) { if (_expectedDigest.HasValue && _expectedDigest.Value != digestAlgorithmName) { throw new CryptographicException( SR.Format( SR.Cryptography_Cms_InvalidSignerHashForSignatureAlg, digestAlgorithmOid, _signatureAlgorithm)); } RSASignaturePadding padding = GetSignaturePadding( signatureParameters, digestAlgorithmOid, digestAlgorithmName, valueHash.Length); RSA publicKey = certificate.GetRSAPublicKey(); if (publicKey == null) { return false; } return publicKey.VerifyHash( valueHash, #if NETCOREAPP || NETSTANDARD2_1 signature.Span, #else signature, #endif digestAlgorithmName, padding); } protected abstract RSASignaturePadding GetSignaturePadding( ReadOnlyMemory<byte>? signatureParameters, string digestAlgorithmOid, HashAlgorithmName digestAlgorithmName, int digestValueLength); } private sealed class RSAPkcs1CmsSignature : RSACmsSignature { public RSAPkcs1CmsSignature(string signatureAlgorithm, HashAlgorithmName? expectedDigest) : base(signatureAlgorithm, expectedDigest) { } protected override RSASignaturePadding GetSignaturePadding( ReadOnlyMemory<byte>? signatureParameters, string digestAlgorithmOid, HashAlgorithmName digestAlgorithmName, int digestValueLength) { if (signatureParameters == null) { return RSASignaturePadding.Pkcs1; } Span<byte> expectedParameters = stackalloc byte[2]; expectedParameters[0] = 0x05; expectedParameters[1] = 0x00; if (expectedParameters.SequenceEqual(signatureParameters.Value.Span)) { return RSASignaturePadding.Pkcs1; } throw new CryptographicException(SR.Cryptography_Pkcs_InvalidSignatureParameters); } protected override bool Sign( #if NETCOREAPP || NETSTANDARD2_1 ReadOnlySpan<byte> dataHash, #else byte[] dataHash, #endif HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm key, bool silent, out Oid signatureAlgorithm, out byte[] signatureValue) { RSA certPublicKey = certificate.GetRSAPublicKey(); // If there's no private key, fall back to the public key for a "no private key" exception. RSA privateKey = key as RSA ?? PkcsPal.Instance.GetPrivateKeyForSigning<RSA>(certificate, silent) ?? certPublicKey; if (privateKey == null) { signatureAlgorithm = null; signatureValue = null; return false; } signatureAlgorithm = new Oid(Oids.Rsa, Oids.Rsa); #if NETCOREAPP || NETSTANDARD2_1 byte[] signature = new byte[privateKey.KeySize / 8]; bool signed = privateKey.TrySignHash( dataHash, signature, hashAlgorithmName, RSASignaturePadding.Pkcs1, out int bytesWritten); if (signed && signature.Length == bytesWritten) { signatureValue = signature; if (key != null && !certPublicKey.VerifyHash(dataHash, signatureValue, hashAlgorithmName, RSASignaturePadding.Pkcs1)) { // key did not match certificate signatureValue = null; return false; } return true; } #endif signatureValue = privateKey.SignHash( #if NETCOREAPP || NETSTANDARD2_1 dataHash.ToArray(), #else dataHash, #endif hashAlgorithmName, RSASignaturePadding.Pkcs1); if (key != null && !certPublicKey.VerifyHash(dataHash, signatureValue, hashAlgorithmName, RSASignaturePadding.Pkcs1)) { // key did not match certificate signatureValue = null; return false; } return true; } } private class RSAPssCmsSignature : RSACmsSignature { public RSAPssCmsSignature() : base(null, null) { } protected override RSASignaturePadding GetSignaturePadding( ReadOnlyMemory<byte>? signatureParameters, string digestAlgorithmOid, HashAlgorithmName digestAlgorithmName, int digestValueLength) { if (signatureParameters == null) { throw new CryptographicException(SR.Cryptography_Pkcs_PssParametersMissing); } PssParamsAsn pssParams = PssParamsAsn.Decode(signatureParameters.Value, AsnEncodingRules.DER); if (pssParams.HashAlgorithm.Algorithm.Value != digestAlgorithmOid) { throw new CryptographicException( SR.Format( SR.Cryptography_Pkcs_PssParametersHashMismatch, pssParams.HashAlgorithm.Algorithm.Value, digestAlgorithmOid)); } if (pssParams.TrailerField != 1) { throw new CryptographicException(SR.Cryptography_Pkcs_InvalidSignatureParameters); } if (pssParams.SaltLength != digestValueLength) { throw new CryptographicException( SR.Format( SR.Cryptography_Pkcs_PssParametersSaltMismatch, pssParams.SaltLength, digestAlgorithmName.Name)); } if (pssParams.MaskGenAlgorithm.Algorithm.Value != Oids.Mgf1) { throw new CryptographicException( SR.Cryptography_Pkcs_PssParametersMgfNotSupported, pssParams.MaskGenAlgorithm.Algorithm.Value); } if (pssParams.MaskGenAlgorithm.Parameters == null) { throw new CryptographicException(SR.Cryptography_Pkcs_InvalidSignatureParameters); } AlgorithmIdentifierAsn mgfParams = AlgorithmIdentifierAsn.Decode( pssParams.MaskGenAlgorithm.Parameters.Value, AsnEncodingRules.DER); if (mgfParams.Algorithm.Value != digestAlgorithmOid) { throw new CryptographicException( SR.Format( SR.Cryptography_Pkcs_PssParametersMgfHashMismatch, mgfParams.Algorithm.Value, digestAlgorithmOid)); } // When RSASignaturePadding supports custom salt sizes this return will look different. return RSASignaturePadding.Pss; } protected override bool Sign( #if NETCOREAPP || NETSTANDARD2_1 ReadOnlySpan<byte> dataHash, #else byte[] dataHash, #endif HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm key, bool silent, out Oid signatureAlgorithm, out byte[] signatureValue) { Debug.Fail("RSA-PSS requires building parameters, which has no API."); throw new CryptographicException(); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.MediaServices; using Microsoft.WindowsAzure.Management.MediaServices.Models; using Newtonsoft.Json.Linq; namespace Microsoft.WindowsAzure.Management.MediaServices { internal partial class AccountOperations : IServiceOperations<MediaServicesManagementClient>, IAccountOperations { /// <summary> /// Initializes a new instance of the AccountOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal AccountOperations(MediaServicesManagementClient client) { this._client = client; } private MediaServicesManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.MediaServices.MediaServicesManagementClient. /// </summary> public MediaServicesManagementClient Client { get { return this._client; } } /// <summary> /// The Create Media Services Account operation creates a new media /// services account in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn194267.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Parameters supplied to the Create Media Services Account operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Create Media Services Account operation response. /// </returns> public async Task<MediaServicesAccountCreateResponse> CreateAsync(MediaServicesAccountCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.AccountName == null) { throw new ArgumentNullException("parameters.AccountName"); } if (parameters.AccountName.Length < 3) { throw new ArgumentOutOfRangeException("parameters.AccountName"); } if (parameters.AccountName.Length > 24) { throw new ArgumentOutOfRangeException("parameters.AccountName"); } if (parameters.BlobStorageEndpointUri == null) { throw new ArgumentNullException("parameters.BlobStorageEndpointUri"); } if (parameters.Region == null) { throw new ArgumentNullException("parameters.Region"); } if (parameters.Region.Length < 3) { throw new ArgumentOutOfRangeException("parameters.Region"); } if (parameters.Region.Length > 256) { throw new ArgumentOutOfRangeException("parameters.Region"); } if (parameters.StorageAccountKey == null) { throw new ArgumentNullException("parameters.StorageAccountKey"); } if (parameters.StorageAccountKey.Length < 14) { throw new ArgumentOutOfRangeException("parameters.StorageAccountKey"); } if (parameters.StorageAccountKey.Length > 256) { throw new ArgumentOutOfRangeException("parameters.StorageAccountKey"); } if (parameters.StorageAccountName == null) { throw new ArgumentNullException("parameters.StorageAccountName"); } if (parameters.StorageAccountName.Length < 3) { throw new ArgumentOutOfRangeException("parameters.StorageAccountName"); } if (parameters.StorageAccountName.Length > 24) { throw new ArgumentOutOfRangeException("parameters.StorageAccountName"); } foreach (char storageAccountNameChar in parameters.StorageAccountName) { if (char.IsLower(storageAccountNameChar) == false && char.IsDigit(storageAccountNameChar) == false) { throw new ArgumentOutOfRangeException("parameters.StorageAccountName"); } } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/mediaservices/Accounts"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement accountCreationRequestElement = new XElement(XName.Get("AccountCreationRequest", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models")); requestDoc.Add(accountCreationRequestElement); XElement accountNameElement = new XElement(XName.Get("AccountName", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models")); accountNameElement.Value = parameters.AccountName; accountCreationRequestElement.Add(accountNameElement); XElement blobStorageEndpointUriElement = new XElement(XName.Get("BlobStorageEndpointUri", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models")); blobStorageEndpointUriElement.Value = parameters.BlobStorageEndpointUri.ToString(); accountCreationRequestElement.Add(blobStorageEndpointUriElement); XElement regionElement = new XElement(XName.Get("Region", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models")); regionElement.Value = parameters.Region; accountCreationRequestElement.Add(regionElement); XElement storageAccountKeyElement = new XElement(XName.Get("StorageAccountKey", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models")); storageAccountKeyElement.Value = parameters.StorageAccountKey; accountCreationRequestElement.Add(storageAccountKeyElement); XElement storageAccountNameElement = new XElement(XName.Get("StorageAccountName", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models")); storageAccountNameElement.Value = parameters.StorageAccountName; accountCreationRequestElement.Add(storageAccountNameElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Json); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result MediaServicesAccountCreateResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new MediaServicesAccountCreateResponse(); JToken responseDoc = JToken.Parse(responseContent); if (responseDoc != null) { MediaServicesCreatedAccount accountInstance = new MediaServicesCreatedAccount(); result.Account = accountInstance; JToken accountIdValue = responseDoc["AccountId"]; if (accountIdValue != null) { string accountIdInstance = (string)accountIdValue; accountInstance.AccountId = accountIdInstance; } JToken accountNameValue = responseDoc["AccountName"]; if (accountNameValue != null) { string accountNameInstance = (string)accountNameValue; accountInstance.AccountName = accountNameInstance; } JToken subscriptionValue = responseDoc["Subscription"]; if (subscriptionValue != null) { string subscriptionInstance = (string)subscriptionValue; accountInstance.SubscriptionId = subscriptionInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Delete Media Services Account operation deletes an existing /// media services account in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn194273.aspx /// for more information) /// </summary> /// <param name='accountName'> /// The name of the media services account. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<OperationResponse> DeleteAsync(string accountName, CancellationToken cancellationToken) { // Validate if (accountName == null) { throw new ArgumentNullException("accountName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("accountName", accountName); Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/mediaservices/Accounts/" + accountName; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Get Media Services Account operation gets detailed information /// about a media services account in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn166974.aspx /// for more information) /// </summary> /// <param name='accountName'> /// The name of the Media Services account. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Media Services Account operation response. /// </returns> public async Task<MediaServicesAccountGetResponse> GetAsync(string accountName, CancellationToken cancellationToken) { // Validate if (accountName == null) { throw new ArgumentNullException("accountName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("accountName", accountName); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/mediaservices/Accounts/" + accountName; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Json); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result MediaServicesAccountGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new MediaServicesAccountGetResponse(); JToken responseDoc = JToken.Parse(responseContent); if (responseDoc != null) { MediaServicesAccount accountInstance = new MediaServicesAccount(); result.Account = accountInstance; JToken accountNameValue = responseDoc["AccountName"]; if (accountNameValue != null) { string accountNameInstance = (string)accountNameValue; accountInstance.AccountName = accountNameInstance; } JToken accountKeyValue = responseDoc["AccountKey"]; if (accountKeyValue != null) { string accountKeyInstance = (string)accountKeyValue; accountInstance.AccountKey = accountKeyInstance; } JToken accountKeysValue = responseDoc["AccountKeys"]; if (accountKeysValue != null) { MediaServicesAccount.AccountKeys accountKeysInstance = new MediaServicesAccount.AccountKeys(); accountInstance.StorageAccountKeys = accountKeysInstance; JToken primaryValue = accountKeysValue["Primary"]; if (primaryValue != null) { string primaryInstance = (string)primaryValue; accountKeysInstance.Primary = primaryInstance; } JToken secondaryValue = accountKeysValue["Secondary"]; if (secondaryValue != null) { string secondaryInstance = (string)secondaryValue; accountKeysInstance.Secondary = secondaryInstance; } } JToken accountRegionValue = responseDoc["AccountRegion"]; if (accountRegionValue != null) { string accountRegionInstance = (string)accountRegionValue; accountInstance.AccountRegion = accountRegionInstance; } JToken storageAccountNameValue = responseDoc["StorageAccountName"]; if (storageAccountNameValue != null) { string storageAccountNameInstance = (string)storageAccountNameValue; accountInstance.StorageAccountName = storageAccountNameInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List Media Services Account operation gets information about /// all existing media services accounts associated with the current /// subscription in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn166989.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Media Accounts operation response. /// </returns> public async Task<MediaServicesAccountListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/mediaservices/Accounts"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result MediaServicesAccountListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new MediaServicesAccountListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement serviceResourcesSequenceElement = responseDoc.Element(XName.Get("ServiceResources", "http://schemas.microsoft.com/windowsazure")); if (serviceResourcesSequenceElement != null) { foreach (XElement serviceResourcesElement in serviceResourcesSequenceElement.Elements(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"))) { MediaServicesAccountListResponse.MediaServiceAccount serviceResourceInstance = new MediaServicesAccountListResponse.MediaServiceAccount(); result.Accounts.Add(serviceResourceInstance); XElement nameElement = serviceResourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; serviceResourceInstance.Name = nameInstance; } XElement typeElement = serviceResourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement != null) { string typeInstance = typeElement.Value; serviceResourceInstance.Type = typeInstance; } XElement stateElement = serviceResourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; serviceResourceInstance.State = stateInstance; } XElement selfLinkElement = serviceResourcesElement.Element(XName.Get("SelfLink", "http://schemas.microsoft.com/windowsazure")); if (selfLinkElement != null) { Uri selfLinkInstance = TypeConversion.TryParseUri(selfLinkElement.Value); serviceResourceInstance.Uri = selfLinkInstance; } XElement parentLinkElement = serviceResourcesElement.Element(XName.Get("ParentLink", "http://schemas.microsoft.com/windowsazure")); if (parentLinkElement != null) { Uri parentLinkInstance = TypeConversion.TryParseUri(parentLinkElement.Value); serviceResourceInstance.ParentUri = parentLinkInstance; } XElement accountIdElement = serviceResourcesElement.Element(XName.Get("AccountId", "http://schemas.microsoft.com/windowsazure")); if (accountIdElement != null) { string accountIdInstance = accountIdElement.Value; serviceResourceInstance.AccountId = accountIdInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Regenerate Media Services Account Key operation regenerates an /// account key for the given Media Services account in Windows Azure. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn167010.aspx /// for more information) /// </summary> /// <param name='accountName'> /// The name of the Media Services Account. /// </param> /// <param name='keyType'> /// The type of key to regenerate (primary or secondary) /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<OperationResponse> RegenerateKeyAsync(string accountName, MediaServicesKeyType keyType, CancellationToken cancellationToken) { // Validate if (accountName == null) { throw new ArgumentNullException("accountName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("accountName", accountName); tracingParameters.Add("keyType", keyType); Tracing.Enter(invocationId, this, "RegenerateKeyAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/mediaservices/Accounts/" + accountName + "/AccountKeys/" + keyType + "/Regenerate"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
namespace StockSharp.Algo.Candles.Compression { using System; using System.Collections.Generic; using StockSharp.Messages; /// <summary> /// The interface that describes data transformation of the <see cref="ICandleBuilder"/> source. /// </summary> public interface ICandleBuilderValueTransform { /// <summary> /// Which market-data type is used as a source value. /// </summary> DataType BuildFrom { get; } /// <summary> /// Process message to update current state. /// </summary> /// <param name="message">Message.</param> /// <returns><see langword="true" />, if the message was processed, otherwise, <see langword="false" />.</returns> bool Process(Message message); /// <summary> /// The time of new data occurrence. /// </summary> DateTimeOffset Time { get; } /// <summary> /// Price. /// </summary> decimal Price { get; } /// <summary> /// Volume. /// </summary> decimal? Volume { get; } /// <summary> /// Side. /// </summary> Sides? Side { get; } /// <summary> /// Open interest. /// </summary> decimal? OpenInterest { get; } /// <summary> /// Price levels. /// </summary> IEnumerable<CandlePriceLevel> PriceLevels { get; } } /// <summary> /// The base data source transformation for <see cref="ICandleBuilder"/>. /// </summary> public abstract class BaseCandleBuilderValueTransform : ICandleBuilderValueTransform { /// <summary> /// Initializes a new instance of the <see cref="BaseCandleBuilderValueTransform"/>. /// </summary> /// <param name="buildFrom">Which market-data type is used as a source value.</param> protected BaseCandleBuilderValueTransform(DataType buildFrom) { _buildFrom = buildFrom; } private readonly DataType _buildFrom; DataType ICandleBuilderValueTransform.BuildFrom => _buildFrom; /// <inheritdoc /> public virtual bool Process(Message message) { if (message is ResetMessage) { _time = default; _price = 0; _volume = null; _side = null; } return false; } /// <summary> /// Update latest values. /// </summary> /// <param name="time">Time.</param> /// <param name="price">Price.</param> /// <param name="volume">Volume.</param> /// <param name="side">Side.</param> /// <param name="openInterest">Open interest.</param> /// <param name="priceLevels">Price levels.</param> protected void Update(DateTimeOffset time, decimal price, decimal? volume, Sides? side, decimal? openInterest, IEnumerable<CandlePriceLevel> priceLevels) { _time = time; _price = price; _volume = volume; _side = side; _openInterest = openInterest; _priceLevels = priceLevels; } private DateTimeOffset _time; DateTimeOffset ICandleBuilderValueTransform.Time => _time; private decimal _price; decimal ICandleBuilderValueTransform.Price => _price; private decimal? _volume; decimal? ICandleBuilderValueTransform.Volume => _volume; private Sides? _side; Sides? ICandleBuilderValueTransform.Side => _side; private decimal? _openInterest; decimal? ICandleBuilderValueTransform.OpenInterest => _openInterest; private IEnumerable<CandlePriceLevel> _priceLevels; IEnumerable<CandlePriceLevel> ICandleBuilderValueTransform.PriceLevels => _priceLevels; } /// <summary> /// The tick based data source transformation for <see cref="ICandleBuilder"/>. /// </summary> public class TickCandleBuilderValueTransform : BaseCandleBuilderValueTransform { /// <summary> /// Initializes a new instance of the <see cref="TickCandleBuilderValueTransform"/>. /// </summary> public TickCandleBuilderValueTransform() : base(DataType.Ticks) { } /// <inheritdoc /> public override bool Process(Message message) { if (message is not ExecutionMessage tick || tick.ExecutionType != ExecutionTypes.Tick) return base.Process(message); Update(tick.ServerTime, tick.TradePrice.Value, tick.TradeVolume, tick.OriginSide, tick.OpenInterest, null); return true; } } /// <summary> /// The order book based data source transformation for <see cref="ICandleBuilder"/>. /// </summary> public class QuoteCandleBuilderValueTransform : BaseCandleBuilderValueTransform { /// <summary> /// Initializes a new instance of the <see cref="QuoteCandleBuilderValueTransform"/>. /// </summary> public QuoteCandleBuilderValueTransform() : base(DataType.MarketDepth) { } /// <summary> /// Type of candle based data. /// </summary> public Level1Fields Type { get; set; } = Level1Fields.SpreadMiddle; /// <inheritdoc /> public override bool Process(Message message) { if (message is not QuoteChangeMessage md) return base.Process(message); switch (Type) { case Level1Fields.BestBidPrice: { var quote = md.GetBestBid(); if (quote == null) return false; Update(md.ServerTime, quote.Value.Price, quote.Value.Volume, Sides.Buy, null, null); return true; } case Level1Fields.BestAskPrice: { var quote = md.GetBestAsk(); if (quote == null) return false; Update(md.ServerTime, quote.Value.Price, quote.Value.Volume, Sides.Sell, null, null); return true; } //case Level1Fields.SpreadMiddle: default: { var price = md.GetSpreadMiddle(); if (price == null) return false; Update(md.ServerTime, price.Value, null, null, null, null); return true; } //default: // throw new ArgumentOutOfRangeException(nameof(Type), Type, LocalizedStrings.Str1219); } } } /// <summary> /// The level1 based data source transformation for <see cref="ICandleBuilder"/>. /// </summary> public class Level1CandleBuilderValueTransform : BaseCandleBuilderValueTransform { private decimal? _prevBestBid; private decimal? _prevBestAsk; /// <summary> /// Initializes a new instance of the <see cref="Level1CandleBuilderValueTransform"/>. /// </summary> public Level1CandleBuilderValueTransform() : base(DataType.Level1) { } /// <summary> /// Type of candle based data. /// </summary> public Level1Fields Type { get; set; } = Level1Fields.LastTradePrice; /// <inheritdoc /> public override bool Process(Message message) { if (message is not Level1ChangeMessage l1) { if (message.Type == MessageTypes.Reset) { _prevBestBid = _prevBestAsk = null; } return base.Process(message); } var time = l1.ServerTime; switch (Type) { case Level1Fields.BestBidPrice: { var price = l1.TryGetDecimal(Type); if (price == null) return false; Update(time, price.Value, l1.TryGetDecimal(Level1Fields.BestBidVolume), Sides.Buy, null, null); return true; } case Level1Fields.BestAskPrice: { var price = l1.TryGetDecimal(Type); if (price == null) return false; Update(time, price.Value, l1.TryGetDecimal(Level1Fields.BestAskVolume), Sides.Sell, null, null); return true; } case Level1Fields.LastTradePrice: { var price = l1.GetLastTradePrice(); if (price == null) return false; Update(time, price.Value, l1.TryGetDecimal(Level1Fields.LastTradeVolume), (Sides?)l1.TryGet(Level1Fields.LastTradeOrigin), l1.TryGetDecimal(Level1Fields.OpenInterest), null); return true; } //case Level1Fields.SpreadMiddle: default: { var currBidPrice = l1.TryGetDecimal(Level1Fields.BestBidPrice); var currAskPrice = l1.TryGetDecimal(Level1Fields.BestAskPrice); _prevBestBid = currBidPrice ?? _prevBestBid; _prevBestAsk = currAskPrice ?? _prevBestAsk; var spreadMiddle = l1.TryGetDecimal(Level1Fields.SpreadMiddle); if (spreadMiddle == null) { if (currBidPrice == null && currAskPrice == null) return false; if (_prevBestBid == null || _prevBestAsk == null) return false; spreadMiddle = _prevBestBid.Value.GetSpreadMiddle(_prevBestAsk.Value); } Update(time, spreadMiddle.Value, null, null, null, null); return true; } //default: // throw new ArgumentOutOfRangeException(nameof(Type), Type, LocalizedStrings.Str1219); } } } /// <summary> /// The order log based data source transformation for <see cref="ICandleBuilder"/>. /// </summary> public class OrderLogCandleBuilderValueTransform : BaseCandleBuilderValueTransform { /// <summary> /// Initializes a new instance of the <see cref="OrderLogCandleBuilderValueTransform"/>. /// </summary> public OrderLogCandleBuilderValueTransform() : base(DataType.OrderLog) { } /// <summary> /// Type of candle based data. /// </summary> public Level1Fields Type { get; set; } = Level1Fields.LastTradePrice; /// <inheritdoc /> public override bool Process(Message message) { if (message is not ExecutionMessage ol || ol.ExecutionType != ExecutionTypes.OrderLog) return base.Process(message); switch (Type) { case Level1Fields.PriceBook: { Update(ol.ServerTime, ol.OrderPrice, ol.OrderVolume, ol.Side, ol.OpenInterest, null); return true; } //case Level1Fields.LastTradePrice: default: { var price = ol.TradePrice; if (price == null) return false; Update(ol.ServerTime, price.Value, ol.TradeVolume, ol.OriginSide, ol.OpenInterest, null); return true; } //default: // throw new ArgumentOutOfRangeException(nameof(Type), Type, LocalizedStrings.Str1219); } } } }
// Spart License (zlib/png) // // // Copyright (c) 2003 Jonathan de Halleux // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from // the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software in a // product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // // Author: Jonathan de Halleuxusing System; using System; using Spart.Parsers.Primitives; namespace Spart.Parsers { /// <summary> /// Static helper class to create primitive parsers /// </summary> public class Prims { /// <summary> /// Creates a parser that matches a single character /// </summary> /// <param name="matchCharacter">character to match</param> /// <returns></returns> public static CharParser Ch(Char matchCharacter) { return new CharParser(delegate(Char c) { return matchCharacter == c; }); } /// <summary> /// Creates a parser that matches a string /// </summary> /// <param name="s">string to match</param> /// <returns></returns> public static StringParser Str(String s) { return new StringParser(s); } /// <summary> /// Creates a parser that matches a range of character /// </summary> /// <param name="first"></param> /// <param name="last"></param> /// <returns></returns> public static CharParser Range(Char first, Char last) { if (last < first) { throw new ArgumentOutOfRangeException("last", "last character < first character"); } return new CharParser(delegate(char c) { return c >= first && c <= last; }); } /// <summary> /// Creates a parser that matches any character /// </summary> public static CharParser AnyChar { get { return new CharParser(AnyCharTester); } } /// <summary> /// Recognizes all characters /// </summary> /// <param name="c">the character to try to recognize</param> /// <returns>always true</returns> static private bool AnyCharTester(Char c) { return true; } /// <summary> /// Creates a parser that matches control characters /// </summary> public static CharParser Control { get { return new CharParser(Char.IsControl); } } /// <summary> /// Creates a parser that matches digit characters /// </summary> public static CharParser Digit { get { return new CharParser(Char.IsDigit); } } /// <summary> /// Creates a parser that matches hexadecimal digit characters /// </summary> public static CharParser HexDigit { get { return new CharParser(HexDigitCharTester); } } /// <summary> /// Recognizes a hexadecimal digit (0..9 a..f A..F) /// </summary> /// <param name="c">the character to try to recognize</param> /// <returns>true if recognized, false if not</returns> static private bool HexDigitCharTester(char c) { return Char.IsDigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } /// <summary> /// Creates a parser that matches letter characters /// </summary> public static CharParser Letter { get { return new CharParser(Char.IsLetter); } } /// <summary> /// Creates a parser that matches letter or digit characters /// </summary> public static CharParser LetterOrDigit { get { return new CharParser(Char.IsLetterOrDigit); } } /// <summary> /// Creates a parser that matches lower case characters /// </summary> public static CharParser Lower { get { return new CharParser(Char.IsLower); } } /// <summary> /// Creates a parser that matches punctuation characters /// </summary> public static CharParser Punctuation { get { return new CharParser(Char.IsPunctuation); } } /// <summary> /// Creates a parser that matches separator characters /// </summary> public static CharParser Separator { get { return new CharParser(Char.IsSeparator); } } /// <summary> /// Creates a parser that matches symbol characters /// </summary> public static CharParser Symbol { get { return new CharParser(Char.IsSymbol); } } /// <summary> /// Creates a parser that matches upper case characters /// </summary> public static CharParser Upper { get { return new CharParser(Char.IsUpper); } } /// <summary> /// Creates a parser that matches whitespace characters /// </summary> public static CharParser WhiteSpace { get { return new CharParser(Char.IsWhiteSpace); } } /// <summary> /// Creates a parser that matches and end of line /// </summary> public static EolParser Eol { get { return new EolParser(); } } /// <summary> /// Creates a parser that matches the end of the input /// </summary> public static EndParser End { get { return new EndParser(); } } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Cassandra.MetadataHelpers; using Cassandra.Tasks; namespace Cassandra { public class KeyspaceMetadata { private readonly ConcurrentDictionary<string, TableMetadata> _tables = new ConcurrentDictionary<string, TableMetadata>(); private readonly ConcurrentDictionary<string, MaterializedViewMetadata> _views = new ConcurrentDictionary<string, MaterializedViewMetadata>(); private readonly ConcurrentDictionary<Tuple<string, string>, FunctionMetadata> _functions = new ConcurrentDictionary<Tuple<string, string>, FunctionMetadata>(); private readonly ConcurrentDictionary<Tuple<string, string>, AggregateMetadata> _aggregates = new ConcurrentDictionary<Tuple<string, string>, AggregateMetadata>(); private readonly Metadata _parent; /// <summary> /// Gets the name of this keyspace. /// </summary> /// <returns>the name of this CQL keyspace.</returns> public string Name { get; } /// <summary> /// Gets a value indicating whether durable writes are set on this keyspace. /// </summary> /// <returns><c>true</c> if durable writes are set on this keyspace /// , <c>false</c> otherwise.</returns> public bool DurableWrites { get; } /// <summary> /// Gets the Strategy Class of this keyspace. /// </summary> /// <returns>name of StrategyClass of this keyspace.</returns> public string StrategyClass { get; } /// <summary> /// Returns the replication options for this keyspace. /// </summary> /// /// <returns>a dictionary containing the keyspace replication strategy options.</returns> public IDictionary<string, int> Replication { get; } /// <summary> /// Returns the replication options for this keyspace. /// </summary> /// /// <returns>a dictionary containing the keyspace replication strategy options.</returns> private IDictionary<string, string> ReplicationOptions { get; } /// <summary> /// Determines whether the keyspace is a virtual keyspace or not. /// </summary> public bool IsVirtual { get; } /// <summary> /// Returns the graph engine associated with this keyspace. Returns null if there isn't one. /// </summary> public string GraphEngine { get; } internal IReplicationStrategy Strategy { get; } internal KeyspaceMetadata( Metadata parent, string name, bool durableWrites, string strategyClass, IDictionary<string, string> replicationOptions, IReplicationStrategyFactory replicationStrategyFactory, string graphEngine, bool isVirtual = false) { //Can not directly reference to schemaParser as it might change _parent = parent; Name = name; DurableWrites = durableWrites; if (strategyClass != null && strategyClass.StartsWith("org.apache.cassandra.locator.")) { strategyClass = strategyClass.Replace("org.apache.cassandra.locator.", ""); } StrategyClass = strategyClass; var parsedReplicationOptions = replicationOptions == null ? null : ParseReplicationFactors(replicationOptions); Replication = parsedReplicationOptions == null ? null : ConvertReplicationOptionsToLegacy(parsedReplicationOptions); ReplicationOptions = replicationOptions; IsVirtual = isVirtual; Strategy = (strategyClass == null || parsedReplicationOptions == null) ? null : replicationStrategyFactory.Create(StrategyClass, parsedReplicationOptions); GraphEngine = graphEngine; } /// <summary> /// Returns metadata of specified table in this keyspace. /// </summary> /// <param name="tableName"> the name of table to retrieve </param> /// <returns>the metadata for table <c>tableName</c> in this keyspace if it /// exists, <c>null</c> otherwise.</returns> public TableMetadata GetTableMetadata(string tableName) { return TaskHelper.WaitToComplete( GetTableMetadataAsync(tableName), _parent.Configuration.DefaultRequestOptions.GetQueryAbortTimeout(2)); } internal async Task<TableMetadata> GetTableMetadataAsync(string tableName) { if (_tables.TryGetValue(tableName, out var tableMetadata)) { //The table metadata is available in local cache return tableMetadata; } var table = await _parent.SchemaParser.GetTableAsync(Name, tableName).ConfigureAwait(false); if (table == null) { return null; } //Cache it _tables.AddOrUpdate(tableName, table, (k, o) => table); return table; } /// <summary> /// Returns metadata of specified view in this keyspace. /// </summary> /// <param name="viewName">the name of view to retrieve </param> /// <returns>the metadata for view <c>viewName</c> in this keyspace if it /// exists, <c>null</c> otherwise.</returns> public MaterializedViewMetadata GetMaterializedViewMetadata(string viewName) { return TaskHelper.WaitToComplete( GetMaterializedViewMetadataAsync(viewName), _parent.Configuration.DefaultRequestOptions.GetQueryAbortTimeout(2)); } private async Task<MaterializedViewMetadata> GetMaterializedViewMetadataAsync(string viewName) { if (_views.TryGetValue(viewName, out var v)) { //The table metadata is available in local cache return v; } var view = await _parent.SchemaParser.GetViewAsync(Name, viewName).ConfigureAwait(false); if (view == null) { return null; } //Cache it _views.AddOrUpdate(viewName, view, (k, o) => view); return view; } /// <summary> /// Removes table metadata forcing refresh the next time the table metadata is retrieved /// </summary> internal void ClearTableMetadata(string tableName) { _tables.TryRemove(tableName, out _); } /// <summary> /// Removes the view metadata forcing refresh the next time the view metadata is retrieved /// </summary> internal void ClearViewMetadata(string name) { _views.TryRemove(name, out _); } /// <summary> /// Removes function metadata forcing refresh the next time the function metadata is retrieved /// </summary> internal void ClearFunction(string name, string[] signature) { _functions.TryRemove(KeyspaceMetadata.GetFunctionKey(name, signature), out _); } /// <summary> /// Removes aggregate metadata forcing refresh the next time the function metadata is retrieved /// </summary> internal void ClearAggregate(string name, string[] signature) { _aggregates.TryRemove(KeyspaceMetadata.GetFunctionKey(name, signature), out _); } /// <summary> /// Returns metadata of all tables defined in this keyspace. /// </summary> /// <returns>an IEnumerable of TableMetadata for the tables defined in this /// keyspace.</returns> public IEnumerable<TableMetadata> GetTablesMetadata() { var tableNames = GetTablesNames(); return tableNames.Select(GetTableMetadata); } /// <summary> /// Returns names of all tables defined in this keyspace. /// </summary> /// /// <returns>a collection of all, defined in this /// keyspace tables names.</returns> public ICollection<string> GetTablesNames() { return TaskHelper.WaitToComplete(_parent.SchemaParser.GetTableNamesAsync(Name)); } /// <summary> /// <para> /// Deprecated. Please use <see cref="AsCqlQuery"/>. /// </para> /// <para> /// Returns a CQL query representing this keyspace. This method returns a single /// 'CREATE KEYSPACE' query with the options corresponding to this name /// definition. /// </para> /// </summary> /// <returns>the 'CREATE KEYSPACE' query corresponding to this name.</returns> public string ExportAsString() { var sb = new StringBuilder(); sb.Append(AsCqlQuery()).Append("\n"); return sb.ToString(); } /// <summary> /// Returns a CQL query representing this keyspace. This method returns a single /// 'CREATE KEYSPACE' query with the options corresponding to this name /// definition. /// </summary> /// <returns>the 'CREATE KEYSPACE' query corresponding to this name.</returns> public string AsCqlQuery() { var sb = new StringBuilder(); sb.Append("CREATE KEYSPACE ").Append(CqlQueryTools.QuoteIdentifier(Name)).Append(" WITH "); sb.Append("REPLICATION = { 'class' : '").Append(StrategyClass).Append("'"); foreach (var rep in ReplicationOptions) { if (rep.Key == "class") { continue; } sb.Append(", '").Append(rep.Key).Append("': '").Append(rep.Value).Append("'"); } sb.Append(" } AND DURABLE_WRITES = ").Append(DurableWrites); sb.Append(";"); return sb.ToString(); } /// <summary> /// Gets the definition of a User defined type /// </summary> internal UdtColumnInfo GetUdtDefinition(string typeName) { return TaskHelper.WaitToComplete(GetUdtDefinitionAsync(typeName), _parent.Configuration.DefaultRequestOptions.QueryAbortTimeout); } /// <summary> /// Gets the definition of a User defined type asynchronously /// </summary> internal Task<UdtColumnInfo> GetUdtDefinitionAsync(string typeName) { return _parent.SchemaParser.GetUdtDefinitionAsync(Name, typeName); } /// <summary> /// Gets a CQL function by name and signature /// </summary> /// <returns>The function metadata or null if not found.</returns> public FunctionMetadata GetFunction(string functionName, string[] signature) { return TaskHelper.WaitToComplete( GetFunctionAsync(functionName, signature), _parent.Configuration.DefaultRequestOptions.QueryAbortTimeout); } private async Task<FunctionMetadata> GetFunctionAsync(string functionName, string[] signature) { if (signature == null) { signature = new string[0]; } var key = KeyspaceMetadata.GetFunctionKey(functionName, signature); if (_functions.TryGetValue(key, out var func)) { return func; } var signatureString = _parent.SchemaParser.ComputeFunctionSignatureString(signature); var f = await _parent.SchemaParser.GetFunctionAsync(Name, functionName, signatureString).ConfigureAwait(false); if (f == null) { return null; } _functions.AddOrUpdate(key, f, (k, v) => f); return f; } /// <summary> /// Gets a CQL aggregate by name and signature /// </summary> /// <returns>The aggregate metadata or null if not found.</returns> public AggregateMetadata GetAggregate(string aggregateName, string[] signature) { return TaskHelper.WaitToComplete( GetAggregateAsync(aggregateName, signature), _parent.Configuration.DefaultRequestOptions.QueryAbortTimeout); } private async Task<AggregateMetadata> GetAggregateAsync(string aggregateName, string[] signature) { if (signature == null) { signature = new string[0]; } var key = KeyspaceMetadata.GetFunctionKey(aggregateName, signature); if (_aggregates.TryGetValue(key, out var aggregate)) { return aggregate; } var signatureString = _parent.SchemaParser.ComputeFunctionSignatureString(signature); var a = await _parent.SchemaParser.GetAggregateAsync(Name, aggregateName, signatureString).ConfigureAwait(false); if (a == null) { return null; } _aggregates.AddOrUpdate(key, a, (k, v) => a); return a; } private static Tuple<string, string> GetFunctionKey(string name, string[] signature) { return Tuple.Create(name, string.Join(",", signature)); } /// <summary> /// This is needed in order to avoid breaking the public API (see <see cref="Replication"/> /// </summary> private IDictionary<string, int> ConvertReplicationOptionsToLegacy(IDictionary<string, ReplicationFactor> replicationOptions) { return replicationOptions.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.AllReplicas); } private Dictionary<string, ReplicationFactor> ParseReplicationFactors(IDictionary<string, string> replicationOptions) { return replicationOptions.ToDictionary(kvp => kvp.Key, kvp => ReplicationFactor.Parse(kvp.Value)); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using VoidEngine.Helpers; namespace VoidEngine.VGame { /// <summary> /// The sprite class for VoidEngine. /// </summary> public class Sprite { /// <summary> /// The sprites animation properties. /// </summary> public struct AnimationSet { /// <summary> /// The name of the animation. /// </summary> public string name; /// <summary> /// The texture of the sprite sheet. /// </summary> public Texture2D texture; /// <summary> /// The size of the frame on the sprite sheet. /// </summary> public Point frameSize; /// <summary> /// The amount of the frames in the animation /// </summary> public Point sheetSize; /// <summary> /// The starting cordinates of the animation of the spritesheet. /// </summary> public Point startPosition; /// <summary> /// The tick of the animation. /// </summary> public int framesPerMillisecond; /// <summary> /// /// </summary> public bool isLooping; /// <summary> /// For creating a new animation set. /// </summary> /// <param name="name">The name of the animation.</param> /// <param name="texture">The texture of the sprite sheet.</param> /// <param name="frameSize">The size of the frame on the sprite sheet.</param> /// <param name="sheetSize">The amount of frames in the animation.</param> /// <param name="startPosition">The starting cordinates of the animation on the spritesheet.</param> /// <param name="framesPerMillisecond">The tick of the animation.</param> public AnimationSet(string name, Texture2D texture, Point frameSize, Point sheetSize, Point startPosition, int framesPerMillisecond, bool isLooping) { this.name = name; this.texture = texture; this.frameSize = frameSize; this.sheetSize = sheetSize; this.startPosition = startPosition; this.framesPerMillisecond = framesPerMillisecond; this.isLooping = isLooping; } } /// <summary> /// The axis of the sprite to flip at. /// </summary> protected float speed; public enum Axis { X, Y, NONE } #region Animations /// <summary> /// Gets the current animation that the sprite is set to. /// </summary> public AnimationSet CurrentAnimation; /// <summary> /// Gets or sets the animation sets. /// Can only be set by child or self. /// </summary> public List<AnimationSet> AnimationSets { get; protected set; } /// <summary> /// The current frame that the sprite is at in its animation. /// </summary> public Point CurrentFrame; /// <summary> /// Gets or sets the animations frame tick time. /// </summary> protected int LastFrameTime { get; set; } /// <summary> /// Gets or sets the SpriteEffects value of the sprite. /// </summary> protected SpriteEffects FlipEffect { get; set; } /// <summary> /// Gets if the sprite is flipped. /// </summary> public bool isFlipped { get { if (FlipEffect != SpriteEffects.None) { return true; } return false; } } /// <summary> /// The offset position of the sprite. /// </summary> public Vector2 Offset = Vector2.Zero; /// <summary> /// Gets ors sets the scale factor of the sprite. /// </summary> public float Scale { get; set; } #endregion #region Movement /// <summary> /// The position that the player is at. /// Can only be used by child or self. /// </summary> protected Vector2 position; /// <summary> /// Gets or sets the position that the sprite is at. /// </summary> public Vector2 Position { get { return position; } set { position = value; } } /// <summary> /// Gets or sets the rotation of the sprite. /// Can only be set by child or self. /// Use values between 0 and 1. /// Ex. 'Rotation = $Degree$ * (float)Math.PI / 180;' /// </summary> public float Rotation { get; protected set; } /// <summary> /// The point to move the sprite from. /// Other wise known as the origin. /// </summary> public Vector2 RotationCenter = Vector2.Zero; #endregion /// <summary> /// Gets the bounding Collisions. /// </summary> public Rectangle BoundingCollisions { get { int left = (int)Math.Round(Position.X) + inbounds.X; int top = (int)Math.Round(Position.Y) + inbounds.Y; return new Rectangle(left, top, inbounds.Width, inbounds.Height); } } /// <summary> /// Gets or sets the inner bounds of the player. /// </summary> public Rectangle Inbounds { get { return inbounds; } set { inbounds = value; } } /// <summary> /// The inner bounds of the player. /// </summary> protected Rectangle inbounds; /// <summary> /// Gets or sets the sprites color. /// Can be only set by child or self. /// </summary> public Color Color { get; protected set; } /// <summary> /// Creates a sprite. /// </summary> /// <param name="position">The stating position of the sprite.</param> /// <param name="color">The color to mask the sprite with.</param> /// <param name="animationSetList">The animation set of the sprite.</param> public Sprite(Vector2 position, Color color, List<AnimationSet> animationSetList) { AnimationSets = new List<AnimationSet>(); AnimationSets = animationSetList; this.position = position; LastFrameTime = 0; Color = color; Scale = 1f; } /// <summary> /// Creates a sprite. /// </summary> /// <param name="position">The stating position of the sprite.</param> /// <param name="color">The color to mask the sprite with.</param> /// <param name="texture">The texture of the sprite.</param> public Sprite(Vector2 position, Color color, Texture2D texture) { AnimationSets = new List<AnimationSet>(); this.position = position; LastFrameTime = 0; Color = color; Scale = 1f; } /// <summary> /// Update's the sprites frames. /// To make custom update functions, add the sprite class as /// a child of a class. Be sure to use 'using VoidEngine;'. /// </summary> /// <param name="gameTime">The game time that the game runs off of.</param> public virtual void Update(GameTime gameTime) { HandleAnimations(gameTime); } /// <summary> /// Used to draw the sprite. /// Put inbetween the spriteBatch.Begin and spriteBatch.End /// </summary> /// <param name="gameTime">The game time, that the game runs off of.</param> /// <param name="spriteBatch">The sprite batch to draw from.</param> public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch) { spriteBatch.Draw(CurrentAnimation.texture, position - Offset, new Rectangle(CurrentAnimation.startPosition.X + (CurrentFrame.X * CurrentAnimation.frameSize.X), CurrentAnimation.startPosition.Y + (CurrentFrame.Y * CurrentAnimation.frameSize.Y), CurrentAnimation.frameSize.X, CurrentAnimation.frameSize.Y), Color, Rotation, RotationCenter, Scale, FlipEffect, 0); } /// <summary> /// Sets the current animation based off of it's name. /// </summary> /// <param name="setName">The name of the animation to set the sprite to.</param> public void SetAnimation(string setName) { if (CurrentAnimation.name != setName) { foreach (AnimationSet a in AnimationSets) { if (a.name == setName) { CurrentAnimation = a; CurrentFrame = Point.Zero; } } } } /// <summary> /// Flips the sprite texture based off a bool and axis. /// To flip back turn isFlip to false or use the second version. /// </summary> /// <param name="axis">The axis to flip on</param> protected void FlipSprite(Axis axis) { if (axis == Axis.Y) { FlipEffect = SpriteEffects.FlipHorizontally; } if (axis == Axis.X) { FlipEffect = SpriteEffects.FlipVertically; } if (axis == Axis.NONE) { FlipEffect = SpriteEffects.None; } } /// <summary> /// Handles the animations for the sprite class. /// </summary> /// <param name="gameTime">The GameTime that the game is running off of.</param> protected virtual void HandleAnimations(GameTime gameTime) { LastFrameTime += gameTime.ElapsedGameTime.Milliseconds; if (LastFrameTime >= CurrentAnimation.framesPerMillisecond) { CurrentFrame.X++; if (CurrentFrame.X >= CurrentAnimation.sheetSize.X) { CurrentFrame.Y++; if (CurrentAnimation.isLooping) { CurrentFrame.X = 0; } else { CurrentFrame.X = CurrentAnimation.sheetSize.X; } if (CurrentFrame.Y >= CurrentAnimation.sheetSize.Y) { CurrentFrame.Y = 0; } } LastFrameTime = 0; } } /// <summary> /// Another way to add an animation indiviually. /// </summary> /// <param name="name">The name of the animation set.</param> /// <param name="texture">The sprite sheet of the animation.</param> /// <param name="frameSize">The frame size of the animation.</param> /// <param name="sheetSize">The sheet size of the animation.</param> /// <param name="startPosition">The start position of the animation.</param> /// <param name="framesPerMillisecond">The frames per milliscond between each frame.</param> /// <param name="isLooping">Sets if the animation loops.</param> protected virtual void AddAnimation(string name, Texture2D texture, Point frameSize, Point sheetSize, Point startPosition, int framesPerMillisecond, bool isLooping) { AnimationSets.Add(new AnimationSet(name, texture, frameSize, sheetSize, startPosition, framesPerMillisecond, isLooping)); } /// <summary> /// Another way to add the animations to the sprites. /// </summary> /// <param name="texture">The texture of the sprite.</param> protected virtual void AddAnimations(Texture2D texture) { } public static void DrawBoundingCollisions(Texture2D line, Rectangle boundingCollisions, Color color, SpriteBatch spriteBatch) { spriteBatch.Draw(line, new Rectangle(boundingCollisions.X, boundingCollisions.Y, boundingCollisions.Width, 1), color); spriteBatch.Draw(line, new Rectangle(boundingCollisions.Right - 1, boundingCollisions.Y, 1, boundingCollisions.Height), color); spriteBatch.Draw(line, new Rectangle(boundingCollisions.X, boundingCollisions.Bottom - 1, boundingCollisions.Width, 1), color); spriteBatch.Draw(line, new Rectangle(boundingCollisions.X, boundingCollisions.Y, 1, boundingCollisions.Height), color); } public bool CheckInRadius(Vector2 position, float radius) { if (CollisionHelper.Magnitude(position - this.Position) < radius) { return true; } return false; } } }
/* * Copyright 2008 ZXing authors * * 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.Text; using ZXing.Common; namespace ZXing.OneD { /// <summary> /// <p>Decodes Code 128 barcodes.</p> /// /// <author>Sean Owen</author> /// </summary> public sealed class Code128Reader : OneDReader { internal static int[][] CODE_PATTERNS = { new[] {2, 1, 2, 2, 2, 2}, // 0 new[] {2, 2, 2, 1, 2, 2}, new[] {2, 2, 2, 2, 2, 1}, new[] {1, 2, 1, 2, 2, 3}, new[] {1, 2, 1, 3, 2, 2}, new[] {1, 3, 1, 2, 2, 2}, // 5 new[] {1, 2, 2, 2, 1, 3}, new[] {1, 2, 2, 3, 1, 2}, new[] {1, 3, 2, 2, 1, 2}, new[] {2, 2, 1, 2, 1, 3}, new[] {2, 2, 1, 3, 1, 2}, // 10 new[] {2, 3, 1, 2, 1, 2}, new[] {1, 1, 2, 2, 3, 2}, new[] {1, 2, 2, 1, 3, 2}, new[] {1, 2, 2, 2, 3, 1}, new[] {1, 1, 3, 2, 2, 2}, // 15 new[] {1, 2, 3, 1, 2, 2}, new[] {1, 2, 3, 2, 2, 1}, new[] {2, 2, 3, 2, 1, 1}, new[] {2, 2, 1, 1, 3, 2}, new[] {2, 2, 1, 2, 3, 1}, // 20 new[] {2, 1, 3, 2, 1, 2}, new[] {2, 2, 3, 1, 1, 2}, new[] {3, 1, 2, 1, 3, 1}, new[] {3, 1, 1, 2, 2, 2}, new[] {3, 2, 1, 1, 2, 2}, // 25 new[] {3, 2, 1, 2, 2, 1}, new[] {3, 1, 2, 2, 1, 2}, new[] {3, 2, 2, 1, 1, 2}, new[] {3, 2, 2, 2, 1, 1}, new[] {2, 1, 2, 1, 2, 3}, // 30 new[] {2, 1, 2, 3, 2, 1}, new[] {2, 3, 2, 1, 2, 1}, new[] {1, 1, 1, 3, 2, 3}, new[] {1, 3, 1, 1, 2, 3}, new[] {1, 3, 1, 3, 2, 1}, // 35 new[] {1, 1, 2, 3, 1, 3}, new[] {1, 3, 2, 1, 1, 3}, new[] {1, 3, 2, 3, 1, 1}, new[] {2, 1, 1, 3, 1, 3}, new[] {2, 3, 1, 1, 1, 3}, // 40 new[] {2, 3, 1, 3, 1, 1}, new[] {1, 1, 2, 1, 3, 3}, new[] {1, 1, 2, 3, 3, 1}, new[] {1, 3, 2, 1, 3, 1}, new[] {1, 1, 3, 1, 2, 3}, // 45 new[] {1, 1, 3, 3, 2, 1}, new[] {1, 3, 3, 1, 2, 1}, new[] {3, 1, 3, 1, 2, 1}, new[] {2, 1, 1, 3, 3, 1}, new[] {2, 3, 1, 1, 3, 1}, // 50 new[] {2, 1, 3, 1, 1, 3}, new[] {2, 1, 3, 3, 1, 1}, new[] {2, 1, 3, 1, 3, 1}, new[] {3, 1, 1, 1, 2, 3}, new[] {3, 1, 1, 3, 2, 1}, // 55 new[] {3, 3, 1, 1, 2, 1}, new[] {3, 1, 2, 1, 1, 3}, new[] {3, 1, 2, 3, 1, 1}, new[] {3, 3, 2, 1, 1, 1}, new[] {3, 1, 4, 1, 1, 1}, // 60 new[] {2, 2, 1, 4, 1, 1}, new[] {4, 3, 1, 1, 1, 1}, new[] {1, 1, 1, 2, 2, 4}, new[] {1, 1, 1, 4, 2, 2}, new[] {1, 2, 1, 1, 2, 4}, // 65 new[] {1, 2, 1, 4, 2, 1}, new[] {1, 4, 1, 1, 2, 2}, new[] {1, 4, 1, 2, 2, 1}, new[] {1, 1, 2, 2, 1, 4}, new[] {1, 1, 2, 4, 1, 2}, // 70 new[] {1, 2, 2, 1, 1, 4}, new[] {1, 2, 2, 4, 1, 1}, new[] {1, 4, 2, 1, 1, 2}, new[] {1, 4, 2, 2, 1, 1}, new[] {2, 4, 1, 2, 1, 1}, // 75 new[] {2, 2, 1, 1, 1, 4}, new[] {4, 1, 3, 1, 1, 1}, new[] {2, 4, 1, 1, 1, 2}, new[] {1, 3, 4, 1, 1, 1}, new[] {1, 1, 1, 2, 4, 2}, // 80 new[] {1, 2, 1, 1, 4, 2}, new[] {1, 2, 1, 2, 4, 1}, new[] {1, 1, 4, 2, 1, 2}, new[] {1, 2, 4, 1, 1, 2}, new[] {1, 2, 4, 2, 1, 1}, // 85 new[] {4, 1, 1, 2, 1, 2}, new[] {4, 2, 1, 1, 1, 2}, new[] {4, 2, 1, 2, 1, 1}, new[] {2, 1, 2, 1, 4, 1}, new[] {2, 1, 4, 1, 2, 1}, // 90 new[] {4, 1, 2, 1, 2, 1}, new[] {1, 1, 1, 1, 4, 3}, new[] {1, 1, 1, 3, 4, 1}, new[] {1, 3, 1, 1, 4, 1}, new[] {1, 1, 4, 1, 1, 3}, // 95 new[] {1, 1, 4, 3, 1, 1}, new[] {4, 1, 1, 1, 1, 3}, new[] {4, 1, 1, 3, 1, 1}, new[] {1, 1, 3, 1, 4, 1}, new[] {1, 1, 4, 1, 3, 1}, // 100 new[] {3, 1, 1, 1, 4, 1}, new[] {4, 1, 1, 1, 3, 1}, new[] {2, 1, 1, 4, 1, 2}, new[] {2, 1, 1, 2, 1, 4}, new[] {2, 1, 1, 2, 3, 2}, // 105 new[] {2, 3, 3, 1, 1, 1, 2} }; private static int MAX_AVG_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.25f); private static int MAX_INDIVIDUAL_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f); private const int CODE_SHIFT = 98; private const int CODE_CODE_C = 99; private const int CODE_CODE_B = 100; private const int CODE_CODE_A = 101; private const int CODE_FNC_1 = 102; private const int CODE_FNC_2 = 97; private const int CODE_FNC_3 = 96; private const int CODE_FNC_4_A = 101; private const int CODE_FNC_4_B = 100; private const int CODE_START_A = 103; private const int CODE_START_B = 104; private const int CODE_START_C = 105; private const int CODE_STOP = 106; private static int[] findStartPattern(BitArray row) { int width = row.Size; int rowOffset = row.getNextSet(0); int counterPosition = 0; int[] counters = new int[6]; int patternStart = rowOffset; bool isWhite = false; int patternLength = counters.Length; for (int i = rowOffset; i < width; i++) { if (row[i] ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { int bestVariance = MAX_AVG_VARIANCE; int bestMatch = -1; for (int startCode = CODE_START_A; startCode <= CODE_START_C; startCode++) { int variance = patternMatchVariance(counters, CODE_PATTERNS[startCode], MAX_INDIVIDUAL_VARIANCE); if (variance < bestVariance) { bestVariance = variance; bestMatch = startCode; } } if (bestMatch >= 0) { // Look for whitespace before start pattern, >= 50% of width of start pattern if (row.isRange(Math.Max(0, patternStart - (i - patternStart) / 2), patternStart, false)) { return new int[] { patternStart, i, bestMatch }; } } patternStart += counters[0] + counters[1]; Array.Copy(counters, 2, counters, 0, patternLength - 2); counters[patternLength - 2] = 0; counters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } return null; } private static bool decodeCode(BitArray row, int[] counters, int rowOffset, out int code) { code = -1; if (!recordPattern(row, rowOffset, counters)) return false; int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept for (int d = 0; d < CODE_PATTERNS.Length; d++) { int[] pattern = CODE_PATTERNS[d]; int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); if (variance < bestVariance) { bestVariance = variance; code = d; } } // TODO We're overlooking the fact that the STOP pattern has 7 values, not 6. return code >= 0; } override public Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints) { int[] startPatternInfo = findStartPattern(row); if (startPatternInfo == null) return null; int startCode = startPatternInfo[2]; int codeSet; switch (startCode) { case CODE_START_A: codeSet = CODE_CODE_A; break; case CODE_START_B: codeSet = CODE_CODE_B; break; case CODE_START_C: codeSet = CODE_CODE_C; break; default: return null; } bool done = false; bool isNextShifted = false; var result = new StringBuilder(20); var rawCodes = new List<byte>(20); int lastStart = startPatternInfo[0]; int nextStart = startPatternInfo[1]; int[] counters = new int[6]; int lastCode = 0; int code = 0; int checksumTotal = startCode; int multiplier = 0; bool lastCharacterWasPrintable = true; while (!done) { bool unshift = isNextShifted; isNextShifted = false; // Save off last code lastCode = code; // Decode another code from image if (!decodeCode(row, counters, nextStart, out code)) return null; rawCodes.Add((byte)code); // Remember whether the last code was printable or not (excluding CODE_STOP) if (code != CODE_STOP) { lastCharacterWasPrintable = true; } // Add to checksum computation (if not CODE_STOP of course) if (code != CODE_STOP) { multiplier++; checksumTotal += multiplier * code; } // Advance to where the next code will to start lastStart = nextStart; foreach (int counter in counters) { nextStart += counter; } // Take care of illegal start codes switch (code) { case CODE_START_A: case CODE_START_B: case CODE_START_C: return null; } switch (codeSet) { case CODE_CODE_A: if (code < 64) { result.Append((char)(' ' + code)); } else if (code < 96) { result.Append((char)(code - 64)); } else { // Don't let CODE_STOP, which always appears, affect whether whether we think the last // code was printable or not. if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: case CODE_FNC_2: case CODE_FNC_3: case CODE_FNC_4_A: // do nothing? break; case CODE_SHIFT: isNextShifted = true; codeSet = CODE_CODE_B; break; case CODE_CODE_B: codeSet = CODE_CODE_B; break; case CODE_CODE_C: codeSet = CODE_CODE_C; break; case CODE_STOP: done = true; break; } } break; case CODE_CODE_B: if (code < 96) { result.Append((char)(' ' + code)); } else { if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: case CODE_FNC_2: case CODE_FNC_3: case CODE_FNC_4_B: // do nothing? break; case CODE_SHIFT: isNextShifted = true; codeSet = CODE_CODE_A; break; case CODE_CODE_A: codeSet = CODE_CODE_A; break; case CODE_CODE_C: codeSet = CODE_CODE_C; break; case CODE_STOP: done = true; break; } } break; case CODE_CODE_C: if (code < 100) { if (code < 10) { result.Append('0'); } result.Append(code); } else { if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: // do nothing? break; case CODE_CODE_A: codeSet = CODE_CODE_A; break; case CODE_CODE_B: codeSet = CODE_CODE_B; break; case CODE_STOP: done = true; break; } } break; } // Unshift back to another code set if we were shifted if (unshift) { codeSet = codeSet == CODE_CODE_A ? CODE_CODE_B : CODE_CODE_A; } } // Check for ample whitespace following pattern, but, to do this we first need to remember that // we fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left // to read off. Would be slightly better to properly read. Here we just skip it: nextStart = row.getNextUnset(nextStart); if (!row.isRange(nextStart, Math.Min(row.Size, nextStart + (nextStart - lastStart) / 2), false)) { return null; } // Pull out from sum the value of the penultimate check code checksumTotal -= multiplier * lastCode; // lastCode is the checksum then: if (checksumTotal % 103 != lastCode) { return null; } // Need to pull out the check digits from string int resultLength = result.Length; if (resultLength == 0) { // false positive return null; } // Only bother if the result had at least one character, and if the checksum digit happened to // be a printable character. If it was just interpreted as a control code, nothing to remove. if (resultLength > 0 && lastCharacterWasPrintable) { if (codeSet == CODE_CODE_C) { result.Remove(resultLength - 2, 2); } else { result.Remove(resultLength - 1, 1); } } float left = (startPatternInfo[1] + startPatternInfo[0]) / 2.0f; float right = (nextStart + lastStart) / 2.0f; var resultPointCallback = hints == null || !hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK) ? null : (ResultPointCallback)hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK]; if (resultPointCallback != null) { resultPointCallback(new ResultPoint(left, rowNumber)); resultPointCallback(new ResultPoint(right, rowNumber)); } int rawCodesSize = rawCodes.Count; var rawBytes = new byte[rawCodesSize]; for (int i = 0; i < rawCodesSize; i++) { rawBytes[i] = rawCodes[i]; } return new Result( result.ToString(), rawBytes, new [] { new ResultPoint(left, rowNumber), new ResultPoint(right, rowNumber) }, BarcodeFormat.CODE_128); } } }
#region licence/info // OSC.NET - Open Sound Control for .NET // http://luvtechno.net/ // // Copyright (c) 2006, Yoshinori Kawasaki // All rights reserved. // // Changes and improvements: // Copyright (c) 2005-2008 Martin Kaltenbrunner <mkalten@iua.upf.edu> // As included with // http://reactivision.sourceforge.net/ // // Further implementations and specifications: // Copyright (c) 2013 Marko Ritter <marko@intolight.de> // As included with https://github.com/vvvv/vvvv-sdk/// // // 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 "luvtechno.net" 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 licence/info using System; using System.Collections; using System.Drawing; using System.IO; using System.Text; namespace LTag.OSC { /// <summary> /// OSCPacket /// </summary> abstract public class OSCPacket { public static readonly Encoding ASCIIEncoding8Bit; static OSCPacket() { ASCIIEncoding8Bit = Encoding.GetEncoding(1252); } public OSCPacket() { values = new ArrayList(); } protected static void addBytes(ArrayList data, byte[] bytes) { foreach(byte b in bytes) { data.Add(b); } } protected static void padNull(ArrayList data) { byte zero = 0; int pad = 4 - (data.Count % 4); for (int i = 0; i < pad; i++) { data.Add(zero); } } internal static byte[] swapEndian(byte[] data) { byte[] swapped = new byte[data.Length]; for(int i = data.Length - 1, j = 0 ; i >= 0 ; i--, j++) { swapped[j] = data[i]; } return swapped; } protected static byte[] packInt(int value) { byte[] data = BitConverter.GetBytes(value); if(BitConverter.IsLittleEndian) data = swapEndian(data); return data; } protected static byte[] packLong(long value) { byte[] data = BitConverter.GetBytes(value); if(BitConverter.IsLittleEndian) data = swapEndian(data); return data; } protected static byte[] packFloat(float value) { byte[] data = BitConverter.GetBytes(value); if(BitConverter.IsLittleEndian) data = swapEndian(data); return data; } protected static byte[] packDouble(double value) { byte[] data = BitConverter.GetBytes(value); if(BitConverter.IsLittleEndian) data = swapEndian(data); return data; } protected static byte[] packString(string value) { return ASCIIEncoding8Bit.GetBytes(value); } protected static byte[] packChar(char value) { byte[] data = BitConverter.GetBytes(value); if (BitConverter.IsLittleEndian) data = swapEndian(data); return data; } protected static byte[] packBlob(Stream value) { var mem = new MemoryStream(); value.Seek(0, SeekOrigin.Begin); value.CopyTo(mem); byte[] valueData = mem.ToArray(); var lData = new ArrayList(); var length = packInt(valueData.Length); lData.AddRange(length); lData.AddRange(valueData); return (byte[])lData.ToArray(typeof(byte)); } protected static byte[] packTimeTag(DateTime value) { var tag = new OscTimeTag(); tag.Set(value); return tag.ToByteArray(); ; } protected static byte[] packColor(Color value) { double[] rgba = {value.R, value.G, value.B, value.A}; byte[] data = new byte[rgba.Length]; for (int i = 0; i < rgba.Length; i++) data[i] = (byte) Math.Round(rgba[i]*255); if (BitConverter.IsLittleEndian) data = swapEndian(data); return data; } abstract protected void pack(); protected byte[] binaryData; public byte[] BinaryData { get { pack(); return binaryData; } } protected static int unpackInt(byte[] bytes, ref int start) { byte[] data = new byte[4]; for(int i = 0 ; i < 4 ; i++, start++) data[i] = bytes[start]; if(BitConverter.IsLittleEndian) data = swapEndian(data); return BitConverter.ToInt32(data, 0); } protected static long unpackLong(byte[] bytes, ref int start) { byte[] data = new byte[8]; for(int i = 0 ; i < 8 ; i++, start++) data[i] = bytes[start]; if(BitConverter.IsLittleEndian) data = swapEndian(data); return BitConverter.ToInt64(data, 0); } protected static float unpackFloat(byte[] bytes, ref int start) { byte[] data = new byte[4]; for(int i = 0 ; i < 4 ; i++, start++) data[i] = bytes[start]; if(BitConverter.IsLittleEndian) data = swapEndian(data); return BitConverter.ToSingle(data, 0); } protected static double unpackDouble(byte[] bytes, ref int start) { byte[] data = new byte[8]; for(int i = 0 ; i < 8 ; i++, start++) data[i] = bytes[start]; if(BitConverter.IsLittleEndian) data = swapEndian(data); return BitConverter.ToDouble(data, 0); } protected static string unpackString(byte[] bytes, ref int start) { int count= 0; for(int index = start ; bytes[index] != 0 ; index++, count++) ; string s = ASCIIEncoding8Bit.GetString(bytes, start, count); start += count+1; start = (start + 3) / 4 * 4; return s; } protected static char unpackChar(byte[] bytes, ref int start) { byte[] data = {bytes[start]}; return BitConverter.ToChar(data, 0); } protected static Stream unpackBlob(byte[] bytes, ref int start) { int length = unpackInt(bytes, ref start); byte[] buffer = new byte[length]; Array.Copy(bytes, start, buffer, 0, length); start += length; start = (start + 3) / 4 * 4; return new MemoryStream(buffer); } protected static Color unpackColor(byte[] bytes, ref int start) { byte[] data = new byte[4]; for (int i = 0; i < 4; i++, start++) data[i] = bytes[start]; if (BitConverter.IsLittleEndian) data = swapEndian(data); return Color.FromArgb(data[3], data[2], data[1], data[0]); } protected static DateTime unpackTimeTag(byte[] bytes, ref int start) { byte[] data = new byte[8]; for (int i = 0; i < 8; i++, start++) data[i] = bytes[start]; var tag = new OscTimeTag(data); return tag.DateTime; } public static OSCPacket Unpack(byte[] bytes, bool extendedMode = false) { int start = 0; return Unpack(bytes, ref start, bytes.Length, extendedMode); } public static OSCPacket Unpack(byte[] bytes, ref int start, int end, bool extendedMode = false) { if(bytes[start] == '#') return OSCBundle.Unpack(bytes, ref start, end, extendedMode); else return OSCMessage.Unpack(bytes, ref start, extendedMode); } protected string address; public string Address { get { return address; } set { // TODO: validate address = value; } } protected ArrayList values; public ArrayList Values { get { return (ArrayList)values.Clone(); } } abstract public void Append(object value); abstract public bool IsBundle(); } }
using BAG.Common.Data.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace BAG.Common.Data { public partial class UnitOfWork : IDisposable { private Context context; public UnitOfWork() { context = new Context(); } public UnitOfWork(Context context) { this.context = context; } //public bool IsFileContext() //{ // try // { // var cast = (System.Data.Entity.DbContext)context; // } // catch (Exception) // { // return true; // } // return false; //} //public void ClearDatabase() //{ // var list = "Accounts,AccountOptions,Divisions,DivisionLeaders,Companies,ServiceUsers,Services,Projects,Customers,UserOptions,Users,TimeEntries,TravelEntries".Split(','); // foreach (var t in list) // { // try // { // context.Database.ExecuteSqlCommand(string.Format("DELETE FROM [{0}]", t)); // } // catch (Exception ex) // { // } // } // var tableNames = context.Database.SqlQuery<string>("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME NOT LIKE '%Migration%'").ToList(); // foreach (var tableName in tableNames) // { // foreach (var t in tableNames) // { // try // { // if (context.Database.ExecuteSqlCommand(string.Format("TRUNCATE TABLE [{0}]", t)) == 1) // break; // } // catch (Exception ex) // { // } // } // } // context.SaveChanges(); //} //public void DeleteAll() //{ // ClearDatabase(); //} private GenericRepository<User> userRepository; public GenericRepository<User> UserRepository { get { if (this.userRepository == null) this.userRepository = new GenericRepository<User>(context); return userRepository; } } private GenericRepository<Employee> employeeRepository; public GenericRepository<Employee> EmployeeRepository { get { if (this.employeeRepository == null) this.employeeRepository = new GenericRepository<Employee>(context); return employeeRepository; } } private GenericRepository<SiteSetting> siteSettingRepository; public GenericRepository<SiteSetting> SiteSettingRepository { get { if (this.siteSettingRepository == null) this.siteSettingRepository = new GenericRepository<SiteSetting>(context); return siteSettingRepository; } } private GenericRepository<SiteManager> siteManagerRepository; public GenericRepository<SiteManager> SiteManagerRepository { get { if (this.siteManagerRepository == null) this.siteManagerRepository = new GenericRepository<SiteManager>(context); return siteManagerRepository; } } private GenericRepository<WidgetManager> widgetManagerRepository; public GenericRepository<WidgetManager> WidgetManagerRepository { get { if (this.widgetManagerRepository == null) this.widgetManagerRepository = new GenericRepository<WidgetManager>(context); return widgetManagerRepository; } } //private GenericRepository<UserOptions> userOptionsRepository; //public GenericRepository<UserOptions> UserOptionsRepository //{ // get // { // if (this.userOptionsRepository == null) // this.userOptionsRepository = new GenericRepository<UserOptions>(context); // return userOptionsRepository; // } //} int _counter = 0; public void Save() { try { context.SaveChanges(); _counter = 0; } catch (Exception ex) { if (_counter < 10) { _counter++; Thread.Sleep(1000 * _counter); Save(); } else { var octx = context.ObjectContext; if (octx != null) { // Resolve the concurrency conflict by refreshing the // object context before re-saving changes. octx.Refresh(System.Data.Entity.Core.Objects.RefreshMode.ClientWins, context.Users); // Save changes. context.SaveChanges(); Console.WriteLine("OptimisticConcurrencyException " + "handled and changes saved"); } else { throw ex; } } } } private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
// <copyright file="AutoResetEvent.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System; using IX.StandardExtensions.ComponentModel; using IX.StandardExtensions.Contracts; using JetBrains.Annotations; namespace IX.System.Threading { /// <summary> /// A set/reset event class that implements methods to block threads and unblock automatically. /// </summary> /// <seealso cref="IX.System.Threading.ISetResetEvent" /> [PublicAPI] public class AutoResetEvent : DisposableBase, ISetResetEvent { private readonly bool eventLocal; #pragma warning disable IDISP002 // Dispose member. - It is #pragma warning disable IDISP006 // Implement IDisposable. /// <summary> /// The manual reset event. /// </summary> private readonly global::System.Threading.AutoResetEvent sre; #pragma warning restore IDISP006 // Implement IDisposable. #pragma warning restore IDISP002 // Dispose member. /// <summary> /// Initializes a new instance of the <see cref="AutoResetEvent" /> class. /// </summary> public AutoResetEvent() : this(false) { } /// <summary> /// Initializes a new instance of the <see cref="AutoResetEvent" /> class. /// </summary> /// <param name="initialState">The initial signal state.</param> public AutoResetEvent(bool initialState) { this.sre = new global::System.Threading.AutoResetEvent(initialState); this.eventLocal = true; } /// <summary> /// Initializes a new instance of the <see cref="AutoResetEvent" /> class. /// </summary> /// <param name="autoResetEvent">The automatic reset event to wrap around.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="autoResetEvent" /> is <see langword="null" /> ( /// <see langword="Nothing" /> in Visual Basic). /// </exception> public AutoResetEvent(global::System.Threading.AutoResetEvent autoResetEvent) { Contract.RequiresNotNull( ref this.sre, autoResetEvent, nameof(autoResetEvent)); } /// <summary> /// Performs an implicit conversion from <see cref="T:System.Threading.AutoResetEvent" /> to /// <see cref="AutoResetEvent" />. /// </summary> /// <param name="autoResetEvent">The automatic reset event.</param> /// <returns>The result of the conversion.</returns> public static implicit operator AutoResetEvent(global::System.Threading.AutoResetEvent autoResetEvent) => new AutoResetEvent(autoResetEvent); /// <summary> /// Performs an implicit conversion from <see cref="AutoResetEvent" /> to /// <see cref="T:System.Threading.AutoResetEvent" />. /// </summary> /// <param name="autoResetEvent">The automatic reset event.</param> /// <returns>The result of the conversion.</returns> public static implicit operator global::System.Threading.AutoResetEvent(AutoResetEvent autoResetEvent) => autoResetEvent.sre; /// <summary> /// Sets the state of this event instance to non-signaled. Any thread entering a wait from this point will block. /// </summary> /// <returns><see langword="true" /> if the signal has been reset, <see langword="false" /> otherwise.</returns> public bool Reset() => this.sre.Reset(); /// <summary> /// Sets the state of this event instance to signaled. Any waiting thread will unblock. /// </summary> /// <returns><see langword="true" /> if the signal has been set, <see langword="false" /> otherwise.</returns> public bool Set() => this.sre.Set(); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> public void WaitOne() => this.sre.WaitOne(); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public bool WaitOne(int millisecondsTimeout) => this.sre.WaitOne(TimeSpan.FromMilliseconds(millisecondsTimeout)); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public bool WaitOne(double millisecondsTimeout) => this.sre.WaitOne(TimeSpan.FromMilliseconds(millisecondsTimeout)); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="timeout">The timeout period.</param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public bool WaitOne(TimeSpan timeout) => this.sre.WaitOne(timeout); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param> /// <param name="exitSynchronizationDomain"> /// If set to <see langword="true" />, the synchronization domain is exited before /// the call. /// </param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public bool WaitOne( int millisecondsTimeout, bool exitSynchronizationDomain) => #if !STANDARD this.sre.WaitOne( TimeSpan.FromMilliseconds(millisecondsTimeout), exitSynchronizationDomain); #else this.sre.WaitOne(TimeSpan.FromMilliseconds(millisecondsTimeout)); #endif /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param> /// <param name="exitSynchronizationDomain"> /// If set to <see langword="true" />, the synchronization domain is exited before /// the call. /// </param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public bool WaitOne( double millisecondsTimeout, bool exitSynchronizationDomain) => #if !STANDARD this.sre.WaitOne( TimeSpan.FromMilliseconds(millisecondsTimeout), exitSynchronizationDomain); #else this.sre.WaitOne(TimeSpan.FromMilliseconds(millisecondsTimeout)); #endif /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="timeout">The timeout period.</param> /// <param name="exitSynchronizationDomain"> /// If set to <see langword="true" />, the synchronization domain is exited before /// the call. /// </param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public bool WaitOne( TimeSpan timeout, bool exitSynchronizationDomain) => #if !STANDARD this.sre.WaitOne( timeout, exitSynchronizationDomain); #else this.sre.WaitOne(timeout); #endif /// <summary> /// Disposes in the managed context. /// </summary> protected override void DisposeManagedContext() { base.DisposeManagedContext(); if (this.eventLocal) { this.sre.Dispose(); } } } }
// 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.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed class TypeManager { private BSYMMGR _BSymmgr; private PredefinedTypes _predefTypes; private readonly TypeFactory _typeFactory; private readonly TypeTable _typeTable; private SymbolTable _symbolTable; // Special types private readonly VoidType _voidType; private readonly NullType _nullType; private readonly MethodGroupType _typeMethGrp; private readonly ArgumentListType _argListType; private readonly ErrorType _errorType; private readonly StdTypeVarColl _stvcMethod; private readonly StdTypeVarColl _stvcClass; public TypeManager(BSYMMGR bsymmgr, PredefinedTypes predefTypes) { _typeFactory = new TypeFactory(); _typeTable = new TypeTable(); // special types with their own symbol kind. _errorType = _typeFactory.CreateError(null, null, null); _voidType = _typeFactory.CreateVoid(); _nullType = _typeFactory.CreateNull(); _typeMethGrp = _typeFactory.CreateMethodGroup(); _argListType = _typeFactory.CreateArgList(); _errorType.SetErrors(true); _stvcMethod = new StdTypeVarColl(); _stvcClass = new StdTypeVarColl(); _BSymmgr = bsymmgr; _predefTypes = predefTypes; } public void InitTypeFactory(SymbolTable table) { _symbolTable = table; } private sealed class StdTypeVarColl { private readonly List<TypeParameterType> prgptvs; public StdTypeVarColl() { prgptvs = new List<TypeParameterType>(); } //////////////////////////////////////////////////////////////////////////////// // Get the standard type variable (eg, !0, !1, or !!0, !!1). // // iv is the index. // pbsm is the containing symbol manager // fMeth designates whether this is a method type var or class type var // // The standard class type variables are useful during emit, but not for type // comparison when binding. The standard method type variables are useful during // binding for signature comparison. public TypeParameterType GetTypeVarSym(int iv, TypeManager pTypeManager, bool fMeth) { Debug.Assert(iv >= 0); TypeParameterType tpt; if (iv >= this.prgptvs.Count) { TypeParameterSymbol pTypeParameter = new TypeParameterSymbol(); pTypeParameter.SetIsMethodTypeParameter(fMeth); pTypeParameter.SetIndexInOwnParameters(iv); pTypeParameter.SetIndexInTotalParameters(iv); pTypeParameter.SetAccess(ACCESS.ACC_PRIVATE); tpt = pTypeManager.GetTypeParameter(pTypeParameter); this.prgptvs.Add(tpt); } else { tpt = this.prgptvs[iv]; } Debug.Assert(tpt != null); return tpt; } } public ArrayType GetArray(CType elementType, int args, bool isSZArray) { Name name; Debug.Assert(args > 0 && args < 32767); Debug.Assert(args == 1 || !isSZArray); switch (args) { case 1: if (isSZArray) { goto case 2; } else { goto default; } case 2: name = NameManager.GetPredefinedName(PredefinedName.PN_ARRAY0 + args); break; default: name = NameManager.Add("[X" + args + 1); break; } // See if we already have an array type of this element type and rank. ArrayType pArray = _typeTable.LookupArray(name, elementType); if (pArray == null) { // No existing array symbol. Create a new one. pArray = _typeFactory.CreateArray(name, elementType, args, isSZArray); pArray.InitFromParent(); _typeTable.InsertArray(name, elementType, pArray); } else { Debug.Assert(pArray.HasErrors() == elementType.HasErrors()); } Debug.Assert(pArray.rank == args); Debug.Assert(pArray.GetElementType() == elementType); return pArray; } public AggregateType GetAggregate(AggregateSymbol agg, AggregateType atsOuter, TypeArray typeArgs) { Debug.Assert(agg.GetTypeManager() == this); Debug.Assert(atsOuter == null || atsOuter.getAggregate() == agg.Parent, ""); if (typeArgs == null) { typeArgs = BSYMMGR.EmptyTypeArray(); } Debug.Assert(agg.GetTypeVars().Count == typeArgs.Count); Name name = _BSymmgr.GetNameFromPtrs(typeArgs, atsOuter); Debug.Assert(name != null); AggregateType pAggregate = _typeTable.LookupAggregate(name, agg); if (pAggregate == null) { pAggregate = _typeFactory.CreateAggregateType( name, agg, typeArgs, atsOuter ); Debug.Assert(!pAggregate.fConstraintsChecked && !pAggregate.fConstraintError); pAggregate.SetErrors(false); _typeTable.InsertAggregate(name, agg, pAggregate); // If we have a generic type definition, then we need to set the // base class to be our current base type, and use that to calculate // our agg type and its base, then set it to be the generic version of the // base type. This is because: // // Suppose we have Foo<T> : IFoo<T> // // Initially, the BaseType will be IFoo<Foo.T>, which gives us the substitution // that we want to use for our agg type's base type. However, in the Symbol chain, // we want the base type to be IFoo<IFoo.T>. Thats why we need to do this little trick. // // If we don't have a generic type definition, then we just need to set our base // class. This is so that if we have a base type that's generic, we'll be // getting the correctly instantiated base type. var baseType = pAggregate.AssociatedSystemType?.BaseType; if (baseType != null) { // Store the old base class. AggregateType oldBaseType = agg.GetBaseClass(); agg.SetBaseClass(_symbolTable.GetCTypeFromType(baseType) as AggregateType); pAggregate.GetBaseClass(); // Get the base type for the new agg type we're making. agg.SetBaseClass(oldBaseType); } } else { Debug.Assert(!pAggregate.HasErrors()); } Debug.Assert(pAggregate.getAggregate() == agg); Debug.Assert(pAggregate.GetTypeArgsThis() != null && pAggregate.GetTypeArgsAll() != null); Debug.Assert(pAggregate.GetTypeArgsThis() == typeArgs); return pAggregate; } public AggregateType GetAggregate(AggregateSymbol agg, TypeArray typeArgsAll) { Debug.Assert(typeArgsAll != null && typeArgsAll.Count == agg.GetTypeVarsAll().Count); if (typeArgsAll.Count == 0) return agg.getThisType(); AggregateSymbol aggOuter = agg.GetOuterAgg(); if (aggOuter == null) return GetAggregate(agg, null, typeArgsAll); int cvarOuter = aggOuter.GetTypeVarsAll().Count; Debug.Assert(cvarOuter <= typeArgsAll.Count); TypeArray typeArgsOuter = _BSymmgr.AllocParams(cvarOuter, typeArgsAll, 0); TypeArray typeArgsInner = _BSymmgr.AllocParams(agg.GetTypeVars().Count, typeArgsAll, cvarOuter); AggregateType atsOuter = GetAggregate(aggOuter, typeArgsOuter); return GetAggregate(agg, atsOuter, typeArgsInner); } public PointerType GetPointer(CType baseType) { PointerType pPointer = _typeTable.LookupPointer(baseType); if (pPointer == null) { // No existing type. Create a new one. Name namePtr = NameManager.GetPredefinedName(PredefinedName.PN_PTR); pPointer = _typeFactory.CreatePointer(namePtr, baseType); pPointer.InitFromParent(); _typeTable.InsertPointer(baseType, pPointer); } else { Debug.Assert(pPointer.HasErrors() == baseType.HasErrors()); } Debug.Assert(pPointer.GetReferentType() == baseType); return pPointer; } public NullableType GetNullable(CType pUnderlyingType) { if (pUnderlyingType is NullableType nt) { Debug.Fail("Attempt to make nullable of nullable"); return nt; } NullableType pNullableType = _typeTable.LookupNullable(pUnderlyingType); if (pNullableType == null) { Name pName = NameManager.GetPredefinedName(PredefinedName.PN_NUB); pNullableType = _typeFactory.CreateNullable(pName, pUnderlyingType, _BSymmgr, this); pNullableType.InitFromParent(); _typeTable.InsertNullable(pUnderlyingType, pNullableType); } return pNullableType; } public NullableType GetNubFromNullable(AggregateType ats) { Debug.Assert(ats.isPredefType(PredefinedType.PT_G_OPTIONAL)); return GetNullable(ats.GetTypeArgsAll()[0]); } public ParameterModifierType GetParameterModifier(CType paramType, bool isOut) { Name name = NameManager.GetPredefinedName(isOut ? PredefinedName.PN_OUTPARAM : PredefinedName.PN_REFPARAM); ParameterModifierType pParamModifier = _typeTable.LookupParameterModifier(name, paramType); if (pParamModifier == null) { // No existing parammod symbol. Create a new one. pParamModifier = _typeFactory.CreateParameterModifier(name, paramType); pParamModifier.isOut = isOut; pParamModifier.InitFromParent(); _typeTable.InsertParameterModifier(name, paramType, pParamModifier); } else { Debug.Assert(pParamModifier.HasErrors() == paramType.HasErrors()); } Debug.Assert(pParamModifier.GetParameterType() == paramType); return pParamModifier; } public ErrorType GetErrorType( Name nameText, TypeArray typeArgs) { Debug.Assert(nameText != null); if (typeArgs == null) { typeArgs = BSYMMGR.EmptyTypeArray(); } Name name = _BSymmgr.GetNameFromPtrs(nameText, typeArgs); Debug.Assert(name != null); ErrorType pError = _typeTable.LookupError(name); if (pError == null) { // No existing error symbol. Create a new one. pError = _typeFactory.CreateError(name, nameText, typeArgs); pError.SetErrors(true); _typeTable.InsertError(name, pError); } else { Debug.Assert(pError.HasErrors()); Debug.Assert(pError.nameText == nameText); Debug.Assert(pError.typeArgs == typeArgs); } return pError; } public VoidType GetVoid() { return _voidType; } public NullType GetNullType() { return _nullType; } public MethodGroupType GetMethGrpType() { return _typeMethGrp; } public ArgumentListType GetArgListType() { return _argListType; } public ErrorType GetErrorSym() { return _errorType; } public AggregateSymbol GetNullable() => GetPredefAgg(PredefinedType.PT_G_OPTIONAL); private CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst) { if (typeSrc == null) return null; var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst); return ctx.FNop() ? typeSrc : SubstTypeCore(typeSrc, ctx); } public CType SubstType(CType typeSrc, TypeArray typeArgsCls) { return SubstType(typeSrc, typeArgsCls, null, SubstTypeFlags.NormNone); } private CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth) { return SubstType(typeSrc, typeArgsCls, typeArgsMeth, SubstTypeFlags.NormNone); } public TypeArray SubstTypeArray(TypeArray taSrc, SubstContext ctx) { if (taSrc != null && taSrc.Count != 0 && ctx != null && !ctx.FNop()) { CType[] srcs = taSrc.Items; for (int i = 0; i < srcs.Length; i++) { CType src = srcs[i]; CType dst = SubstTypeCore(src, ctx); if (src != dst) { CType[] dsts = new CType[srcs.Length]; Array.Copy(srcs, dsts, i); dsts[i] = dst; while (++i < srcs.Length) { dsts[i] = SubstTypeCore(srcs[i], ctx); } return _BSymmgr.AllocParams(dsts); } } } return taSrc; } public TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth) => taSrc == null || taSrc.Count == 0 ? taSrc : SubstTypeArray(taSrc, new SubstContext(typeArgsCls, typeArgsMeth, SubstTypeFlags.NormNone)); public TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls) => SubstTypeArray(taSrc, typeArgsCls, null); private CType SubstTypeCore(CType type, SubstContext pctx) { CType typeSrc; CType typeDst; switch (type.GetTypeKind()) { default: Debug.Assert(false); return type; case TypeKind.TK_NullType: case TypeKind.TK_VoidType: case TypeKind.TK_MethodGroupType: case TypeKind.TK_ArgumentListType: return type; case TypeKind.TK_ParameterModifierType: ParameterModifierType mod = (ParameterModifierType)type; typeDst = SubstTypeCore(typeSrc = mod.GetParameterType(), pctx); return (typeDst == typeSrc) ? type : GetParameterModifier(typeDst, mod.isOut); case TypeKind.TK_ArrayType: var arr = (ArrayType)type; typeDst = SubstTypeCore(typeSrc = arr.GetElementType(), pctx); return (typeDst == typeSrc) ? type : GetArray(typeDst, arr.rank, arr.IsSZArray); case TypeKind.TK_PointerType: typeDst = SubstTypeCore(typeSrc = ((PointerType)type).GetReferentType(), pctx); return (typeDst == typeSrc) ? type : GetPointer(typeDst); case TypeKind.TK_NullableType: typeDst = SubstTypeCore(typeSrc = ((NullableType)type).GetUnderlyingType(), pctx); return (typeDst == typeSrc) ? type : GetNullable(typeDst); case TypeKind.TK_AggregateType: AggregateType ats = (AggregateType)type; if (ats.GetTypeArgsAll().Count > 0) { TypeArray typeArgs = SubstTypeArray(ats.GetTypeArgsAll(), pctx); if (ats.GetTypeArgsAll() != typeArgs) return GetAggregate(ats.getAggregate(), typeArgs); } return type; case TypeKind.TK_ErrorType: ErrorType err = (ErrorType)type; if (err.HasParent) { Debug.Assert(err.nameText != null && err.typeArgs != null); TypeArray typeArgs = SubstTypeArray(err.typeArgs, pctx); if (typeArgs != err.typeArgs) { return GetErrorType(err.nameText, typeArgs); } } return type; case TypeKind.TK_TypeParameterType: { TypeParameterSymbol tvs = ((TypeParameterType)type).GetTypeParameterSymbol(); int index = tvs.GetIndexInTotalParameters(); if (tvs.IsMethodTypeParameter()) { if ((pctx.grfst & SubstTypeFlags.DenormMeth) != 0 && tvs.parent != null) return type; Debug.Assert(tvs.GetIndexInOwnParameters() == tvs.GetIndexInTotalParameters()); if (index < pctx.ctypeMeth) { Debug.Assert(pctx.prgtypeMeth != null); return pctx.prgtypeMeth[index]; } else { return ((pctx.grfst & SubstTypeFlags.NormMeth) != 0 ? GetStdMethTypeVar(index) : type); } } if ((pctx.grfst & SubstTypeFlags.DenormClass) != 0 && tvs.parent != null) return type; return index < pctx.ctypeCls ? pctx.prgtypeCls[index] : ((pctx.grfst & SubstTypeFlags.NormClass) != 0 ? GetStdClsTypeVar(index) : type); } } } public bool SubstEqualTypes(CType typeDst, CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst) { if (typeDst.Equals(typeSrc)) { Debug.Assert(typeDst.Equals(SubstType(typeSrc, typeArgsCls, typeArgsMeth, grfst))); return true; } var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst); return !ctx.FNop() && SubstEqualTypesCore(typeDst, typeSrc, ctx); } public bool SubstEqualTypeArrays(TypeArray taDst, TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst) { // Handle the simple common cases first. if (taDst == taSrc || (taDst != null && taDst.Equals(taSrc))) { // The following assertion is not always true and indicates a problem where // the signature of override method does not match the one inherited from // the base class. The method match we have found does not take the type // arguments of the base class into account. So actually we are not overriding // the method that we "intend" to. // Debug.Assert(taDst == SubstTypeArray(taSrc, typeArgsCls, typeArgsMeth, grfst)); return true; } if (taDst.Count != taSrc.Count) return false; if (taDst.Count == 0) return true; var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst); if (ctx.FNop()) return false; for (int i = 0; i < taDst.Count; i++) { if (!SubstEqualTypesCore(taDst[i], taSrc[i], ctx)) return false; } return true; } private bool SubstEqualTypesCore(CType typeDst, CType typeSrc, SubstContext pctx) { LRecurse: // Label used for "tail" recursion. if (typeDst == typeSrc || typeDst.Equals(typeSrc)) { return true; } switch (typeSrc.GetTypeKind()) { default: Debug.Assert(false, "Bad Symbol kind in SubstEqualTypesCore"); return false; case TypeKind.TK_NullType: case TypeKind.TK_VoidType: // There should only be a single instance of these. Debug.Assert(typeDst.GetTypeKind() != typeSrc.GetTypeKind()); return false; case TypeKind.TK_ArrayType: ArrayType arrSrc = (ArrayType)typeSrc; if (!(typeDst is ArrayType arrDst) || arrDst.rank != arrSrc.rank || arrDst.IsSZArray != arrSrc.IsSZArray) return false; goto LCheckBases; case TypeKind.TK_ParameterModifierType: if (!(typeDst is ParameterModifierType modDest) || ((pctx.grfst & SubstTypeFlags.NoRefOutDifference) == 0 && modDest.isOut != ((ParameterModifierType)typeSrc).isOut)) return false; goto LCheckBases; case TypeKind.TK_PointerType: case TypeKind.TK_NullableType: if (typeDst.GetTypeKind() != typeSrc.GetTypeKind()) return false; LCheckBases: typeSrc = typeSrc.GetBaseOrParameterOrElementType(); typeDst = typeDst.GetBaseOrParameterOrElementType(); goto LRecurse; case TypeKind.TK_AggregateType: if (!(typeDst is AggregateType atsDst)) return false; { // BLOCK AggregateType atsSrc = (AggregateType)typeSrc; if (atsSrc.getAggregate() != atsDst.getAggregate()) return false; Debug.Assert(atsSrc.GetTypeArgsAll().Count == atsDst.GetTypeArgsAll().Count); // All the args must unify. for (int i = 0; i < atsSrc.GetTypeArgsAll().Count; i++) { if (!SubstEqualTypesCore(atsDst.GetTypeArgsAll()[i], atsSrc.GetTypeArgsAll()[i], pctx)) return false; } } return true; case TypeKind.TK_ErrorType: ErrorType errSrc = (ErrorType)typeSrc; if (!(typeDst is ErrorType errDst) || !errSrc.HasParent || !errDst.HasParent) return false; { Debug.Assert(errSrc.nameText != null && errSrc.typeArgs != null); Debug.Assert(errDst.nameText != null && errDst.typeArgs != null); if (errSrc.nameText != errDst.nameText || errSrc.typeArgs.Count != errDst.typeArgs.Count || errSrc.HasParent != errDst.HasParent) { return false; } // All the args must unify. for (int i = 0; i < errSrc.typeArgs.Count; i++) { if (!SubstEqualTypesCore(errDst.typeArgs[i], errSrc.typeArgs[i], pctx)) return false; } } return true; case TypeKind.TK_TypeParameterType: { // BLOCK TypeParameterSymbol tvs = ((TypeParameterType)typeSrc).GetTypeParameterSymbol(); int index = tvs.GetIndexInTotalParameters(); if (tvs.IsMethodTypeParameter()) { if ((pctx.grfst & SubstTypeFlags.DenormMeth) != 0 && tvs.parent != null) { // typeDst == typeSrc was handled above. Debug.Assert(typeDst != typeSrc); return false; } Debug.Assert(tvs.GetIndexInOwnParameters() == tvs.GetIndexInTotalParameters()); Debug.Assert(pctx.prgtypeMeth == null || tvs.GetIndexInTotalParameters() < pctx.ctypeMeth); if (index < pctx.ctypeMeth && pctx.prgtypeMeth != null) { return typeDst == pctx.prgtypeMeth[index]; } if ((pctx.grfst & SubstTypeFlags.NormMeth) != 0) { return typeDst == GetStdMethTypeVar(index); } } else { if ((pctx.grfst & SubstTypeFlags.DenormClass) != 0 && tvs.parent != null) { // typeDst == typeSrc was handled above. Debug.Assert(typeDst != typeSrc); return false; } Debug.Assert(pctx.prgtypeCls == null || tvs.GetIndexInTotalParameters() < pctx.ctypeCls); if (index < pctx.ctypeCls) return typeDst == pctx.prgtypeCls[index]; if ((pctx.grfst & SubstTypeFlags.NormClass) != 0) return typeDst == GetStdClsTypeVar(index); } } return false; } } public static bool TypeContainsType(CType type, CType typeFind) { LRecurse: // Label used for "tail" recursion. if (type == typeFind || type.Equals(typeFind)) return true; switch (type.GetTypeKind()) { default: Debug.Assert(false, "Bad Symbol kind in TypeContainsType"); return false; case TypeKind.TK_NullType: case TypeKind.TK_VoidType: // There should only be a single instance of these. Debug.Assert(typeFind.GetTypeKind() != type.GetTypeKind()); return false; case TypeKind.TK_ArrayType: case TypeKind.TK_NullableType: case TypeKind.TK_ParameterModifierType: case TypeKind.TK_PointerType: type = type.GetBaseOrParameterOrElementType(); goto LRecurse; case TypeKind.TK_AggregateType: { // BLOCK AggregateType ats = (AggregateType)type; for (int i = 0; i < ats.GetTypeArgsAll().Count; i++) { if (TypeContainsType(ats.GetTypeArgsAll()[i], typeFind)) return true; } } return false; case TypeKind.TK_ErrorType: ErrorType err = (ErrorType)type; if (err.HasParent) { Debug.Assert(err.nameText != null && err.typeArgs != null); for (int i = 0; i < err.typeArgs.Count; i++) { if (TypeContainsType(err.typeArgs[i], typeFind)) return true; } } return false; case TypeKind.TK_TypeParameterType: return false; } } public static bool TypeContainsTyVars(CType type, TypeArray typeVars) { LRecurse: // Label used for "tail" recursion. switch (type.GetTypeKind()) { default: Debug.Assert(false, "Bad Symbol kind in TypeContainsTyVars"); return false; case TypeKind.TK_NullType: case TypeKind.TK_VoidType: case TypeKind.TK_MethodGroupType: return false; case TypeKind.TK_ArrayType: case TypeKind.TK_NullableType: case TypeKind.TK_ParameterModifierType: case TypeKind.TK_PointerType: type = type.GetBaseOrParameterOrElementType(); goto LRecurse; case TypeKind.TK_AggregateType: { // BLOCK AggregateType ats = (AggregateType)type; for (int i = 0; i < ats.GetTypeArgsAll().Count; i++) { if (TypeContainsTyVars(ats.GetTypeArgsAll()[i], typeVars)) { return true; } } } return false; case TypeKind.TK_ErrorType: ErrorType err = (ErrorType)type; if (err.HasParent) { Debug.Assert(err.nameText != null && err.typeArgs != null); for (int i = 0; i < err.typeArgs.Count; i++) { if (TypeContainsTyVars(err.typeArgs[i], typeVars)) { return true; } } } return false; case TypeKind.TK_TypeParameterType: if (typeVars != null && typeVars.Count > 0) { int ivar = ((TypeParameterType)type).GetIndexInTotalParameters(); return ivar < typeVars.Count && type == typeVars[ivar]; } return true; } } public static bool ParametersContainTyVar(TypeArray @params, TypeParameterType typeFind) { Debug.Assert(@params != null); Debug.Assert(typeFind != null); for (int p = 0; p < @params.Count; p++) { CType sym = @params[p]; if (TypeContainsType(sym, typeFind)) { return true; } } return false; } public AggregateSymbol GetPredefAgg(PredefinedType pt) => _predefTypes.GetPredefinedAggregate(pt); public TypeArray ConcatenateTypeArrays(TypeArray pTypeArray1, TypeArray pTypeArray2) { return _BSymmgr.ConcatParams(pTypeArray1, pTypeArray2); } public TypeArray GetStdMethTyVarArray(int cTyVars) { TypeParameterType[] prgvar = new TypeParameterType[cTyVars]; for (int ivar = 0; ivar < cTyVars; ivar++) { prgvar[ivar] = GetStdMethTypeVar(ivar); } return _BSymmgr.AllocParams(cTyVars, (CType[])prgvar); } public CType SubstType(CType typeSrc, SubstContext pctx) { return (pctx == null || pctx.FNop()) ? typeSrc : SubstTypeCore(typeSrc, pctx); } public CType SubstType(CType typeSrc, AggregateType atsCls) { return SubstType(typeSrc, atsCls, (TypeArray)null); } public CType SubstType(CType typeSrc, AggregateType atsCls, TypeArray typeArgsMeth) { return SubstType(typeSrc, atsCls?.GetTypeArgsAll(), typeArgsMeth); } public CType SubstType(CType typeSrc, CType typeCls, TypeArray typeArgsMeth) { return SubstType(typeSrc, (typeCls as AggregateType)?.GetTypeArgsAll(), typeArgsMeth); } public TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls, TypeArray typeArgsMeth) { return SubstTypeArray(taSrc, atsCls?.GetTypeArgsAll(), typeArgsMeth); } public TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls) { return this.SubstTypeArray(taSrc, atsCls, (TypeArray)null); } private bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls, TypeArray typeArgsMeth) { return SubstEqualTypes(typeDst, typeSrc, (typeCls as AggregateType)?.GetTypeArgsAll(), typeArgsMeth, SubstTypeFlags.NormNone); } public bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls) { return SubstEqualTypes(typeDst, typeSrc, typeCls, (TypeArray)null); } //public bool SubstEqualTypeArrays(TypeArray taDst, TypeArray taSrc, AggregateType atsCls, TypeArray typeArgsMeth) //{ // return SubstEqualTypeArrays(taDst, taSrc, atsCls != null ? atsCls.GetTypeArgsAll() : (TypeArray)null, typeArgsMeth, SubstTypeFlags.NormNone); //} public TypeParameterType GetStdMethTypeVar(int iv) { return _stvcMethod.GetTypeVarSym(iv, this, true); } private TypeParameterType GetStdClsTypeVar(int iv) { return _stvcClass.GetTypeVarSym(iv, this, false); } public TypeParameterType GetTypeParameter(TypeParameterSymbol pSymbol) { // These guys should be singletons for each. TypeParameterType pTypeParameter = _typeTable.LookupTypeParameter(pSymbol); if (pTypeParameter == null) { pTypeParameter = _typeFactory.CreateTypeParameter(pSymbol); _typeTable.InsertTypeParameter(pSymbol, pTypeParameter); } return pTypeParameter; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // RUNTIME BINDER ONLY CHANGE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! internal bool GetBestAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, CType typeSrc, out CType typeDst) { // This method implements the "best accessible type" algorithm for determining the type // of untyped arguments in the runtime binder. It is also used in method type inference // to fix type arguments to types that are accessible. // The new type is returned in an out parameter. The result will be true (and the out param // non-null) only when the algorithm could find a suitable accessible type. Debug.Assert(semanticChecker != null); Debug.Assert(bindingContext != null); Debug.Assert(typeSrc != null); typeDst = null; if (semanticChecker.CheckTypeAccess(typeSrc, bindingContext.ContextForMemberLookup)) { // If we already have an accessible type, then use it. This is the terminal point of the recursion. typeDst = typeSrc; return true; } // These guys have no accessibility concerns. Debug.Assert(!(typeSrc is VoidType) && !(typeSrc is ErrorType) && !(typeSrc is TypeParameterType)); if (typeSrc is ParameterModifierType || typeSrc is PointerType) { // We cannot vary these. return false; } CType intermediateType; if (typeSrc is AggregateType aggSrc && (aggSrc.isInterfaceType() || aggSrc.isDelegateType()) && TryVarianceAdjustmentToGetAccessibleType(semanticChecker, bindingContext, aggSrc, out intermediateType)) { // If we have an interface or delegate type, then it can potentially be varied by its type arguments // to produce an accessible type, and if that's the case, then return that. // Example: IEnumerable<PrivateConcreteFoo> --> IEnumerable<PublicAbstractFoo> typeDst = intermediateType; Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup)); return true; } if (typeSrc is ArrayType arrSrc && TryArrayVarianceAdjustmentToGetAccessibleType(semanticChecker, bindingContext, arrSrc, out intermediateType)) { // Similarly to the interface and delegate case, arrays are covariant in their element type and // so we can potentially produce an array type that is accessible. // Example: PrivateConcreteFoo[] --> PublicAbstractFoo[] typeDst = intermediateType; Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup)); return true; } if (typeSrc is NullableType) { // We have an inaccessible nullable type, which means that the best we can do is System.ValueType. typeDst = GetPredefAgg(PredefinedType.PT_VALUE).getThisType(); Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup)); return true; } if (typeSrc is ArrayType) { // We have an inaccessible array type for which we could not earlier find a better array type // with a covariant conversion, so the best we can do is System.Array. typeDst = GetPredefAgg(PredefinedType.PT_ARRAY).getThisType(); Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup)); return true; } Debug.Assert(typeSrc is AggregateType); if (typeSrc is AggregateType aggType) { // We have an AggregateType, so recurse on its base class. AggregateType baseType = aggType.GetBaseClass(); if (baseType == null) { // This happens with interfaces, for instance. But in that case, the // conversion to object does exist, is an implicit reference conversion, // and so we will use it. baseType = GetPredefAgg(PredefinedType.PT_OBJECT).getThisType(); } return GetBestAccessibleType(semanticChecker, bindingContext, baseType, out typeDst); } return false; } private bool TryVarianceAdjustmentToGetAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, AggregateType typeSrc, out CType typeDst) { Debug.Assert(typeSrc != null); Debug.Assert(typeSrc.isInterfaceType() || typeSrc.isDelegateType()); typeDst = null; AggregateSymbol aggSym = typeSrc.GetOwningAggregate(); AggregateType aggOpenType = aggSym.getThisType(); if (!semanticChecker.CheckTypeAccess(aggOpenType, bindingContext.ContextForMemberLookup)) { // if the aggregate symbol itself is not accessible, then forget it, there is no // variance that will help us arrive at an accessible type. return false; } TypeArray typeArgs = typeSrc.GetTypeArgsThis(); TypeArray typeParams = aggOpenType.GetTypeArgsThis(); CType[] newTypeArgsTemp = new CType[typeArgs.Count]; for (int i = 0; i < typeArgs.Count; i++) { if (semanticChecker.CheckTypeAccess(typeArgs[i], bindingContext.ContextForMemberLookup)) { // we have an accessible argument, this position is not a problem. newTypeArgsTemp[i] = typeArgs[i]; continue; } if (!typeArgs[i].IsRefType() || !((TypeParameterType)typeParams[i]).Covariant) { // This guy is inaccessible, and we are not going to be able to vary him, so we need to fail. return false; } CType intermediateTypeArg; if (GetBestAccessibleType(semanticChecker, bindingContext, typeArgs[i], out intermediateTypeArg)) { // now we either have a value type (which must be accessible due to the above // check, OR we have an inaccessible type (which must be a ref type). In either // case, the recursion worked out and we are OK to vary this argument. newTypeArgsTemp[i] = intermediateTypeArg; continue; } else { Debug.Assert(false, "GetBestAccessibleType unexpectedly failed on a type that was used as a type parameter"); return false; } } TypeArray newTypeArgs = semanticChecker.getBSymmgr().AllocParams(typeArgs.Count, newTypeArgsTemp); CType intermediateType = this.GetAggregate(aggSym, typeSrc.outerType, newTypeArgs); // All type arguments were varied successfully, which means now we must be accessible. But we could // have violated constraints. Let's check that out. if (!TypeBind.CheckConstraints(semanticChecker, null/*ErrorHandling*/, intermediateType, CheckConstraintsFlags.NoErrors)) { return false; } typeDst = intermediateType; Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup)); return true; } private bool TryArrayVarianceAdjustmentToGetAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, ArrayType typeSrc, out CType typeDst) { Debug.Assert(typeSrc != null); typeDst = null; // We are here because we have an array type with an inaccessible element type. If possible, // we should create a new array type that has an accessible element type for which a // conversion exists. CType elementType = typeSrc.GetElementType(); if (!elementType.IsRefType()) { // Covariant array conversions exist for reference types only. return false; } CType intermediateType; if (GetBestAccessibleType(semanticChecker, bindingContext, elementType, out intermediateType)) { typeDst = this.GetArray(intermediateType, typeSrc.rank, typeSrc.IsSZArray); Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup)); return true; } return false; } public AggregateType ObjectAggregateType => (AggregateType)_symbolTable.GetCTypeFromType(typeof(object)); private readonly Dictionary<Tuple<Assembly, Assembly>, bool> _internalsVisibleToCalculated = new Dictionary<Tuple<Assembly, Assembly>, bool>(); internal bool InternalsVisibleTo(Assembly assemblyThatDefinesAttribute, Assembly assemblyToCheck) { bool result; var key = Tuple.Create(assemblyThatDefinesAttribute, assemblyToCheck); if (!_internalsVisibleToCalculated.TryGetValue(key, out result)) { AssemblyName assyName; // Assembly.GetName() requires FileIOPermission to FileIOPermissionAccess.PathDiscovery. // If we don't have that (we're in low trust), then we are going to effectively turn off // InternalsVisibleTo. The alternative is to crash when this happens. try { assyName = assemblyToCheck.GetName(); } catch (System.Security.SecurityException) { result = false; goto SetMemo; } result = assemblyThatDefinesAttribute.GetCustomAttributes() .OfType<InternalsVisibleToAttribute>() .Select(ivta => new AssemblyName(ivta.AssemblyName)) .Any(an => AssemblyName.ReferenceMatchesDefinition(an, assyName)); SetMemo: _internalsVisibleToCalculated[key] = result; } return result; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // END RUNTIME BINDER ONLY CHANGE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32.SafeHandles; namespace System.Threading { // // Implementation of ThreadPoolBoundHandle that sits on top of the Win32 ThreadPool // public sealed class ThreadPoolBoundHandle : IDisposable, IDeferredDisposable { private static Interop.NativeIoCompletionCallback s_nativeIoCompletionCallback; private readonly SafeHandle _handle; private readonly SafeThreadPoolIOHandle _threadPoolHandle; private DeferredDisposableLifetime<ThreadPoolBoundHandle> _lifetime; private ThreadPoolBoundHandle(SafeHandle handle, SafeThreadPoolIOHandle threadPoolHandle) { _threadPoolHandle = threadPoolHandle; _handle = handle; } public SafeHandle Handle { get { return _handle; } } public static ThreadPoolBoundHandle BindHandle(SafeHandle handle) { if (handle == null) throw new ArgumentNullException(nameof(handle)); if (handle.IsClosed || handle.IsInvalid) throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle)); // Make sure we use a statically-rooted completion callback, // so it doesn't get collected while the I/O is in progress. Interop.NativeIoCompletionCallback callback = s_nativeIoCompletionCallback; if (callback == null) s_nativeIoCompletionCallback = callback = new Interop.NativeIoCompletionCallback(OnNativeIOCompleted); SafeThreadPoolIOHandle threadPoolHandle = Interop.mincore.CreateThreadpoolIo(handle, s_nativeIoCompletionCallback, IntPtr.Zero, IntPtr.Zero); if (threadPoolHandle.IsInvalid) { int hr = Marshal.GetHRForLastWin32Error(); if (hr == System.HResults.E_HANDLE) // Bad handle throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle)); if (hr == System.HResults.E_INVALIDARG) // Handle already bound or sync handle throw new ArgumentException(SR.Argument_AlreadyBoundOrSyncHandle, nameof(handle)); throw Marshal.GetExceptionForHR(hr); } return new ThreadPoolBoundHandle(handle, threadPoolHandle); } [CLSCompliant(false)] public unsafe NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback, object state, object pinData) { if (callback == null) throw new ArgumentNullException(nameof(callback)); AddRef(); try { Win32ThreadPoolNativeOverlapped* overlapped = Win32ThreadPoolNativeOverlapped.Allocate(callback, state, pinData, preAllocated: null); overlapped->Data._boundHandle = this; Interop.mincore.StartThreadpoolIo(_threadPoolHandle); return Win32ThreadPoolNativeOverlapped.ToNativeOverlapped(overlapped); } catch { Release(); throw; } } [CLSCompliant(false)] public unsafe NativeOverlapped* AllocateNativeOverlapped(PreAllocatedOverlapped preAllocated) { if (preAllocated == null) throw new ArgumentNullException(nameof(preAllocated)); bool addedRefToThis = false; bool addedRefToPreAllocated = false; try { addedRefToThis = AddRef(); addedRefToPreAllocated = preAllocated.AddRef(); Win32ThreadPoolNativeOverlapped.OverlappedData data = preAllocated._overlapped->Data; if (data._boundHandle != null) throw new ArgumentException(SR.Argument_PreAllocatedAlreadyAllocated, nameof(preAllocated)); data._boundHandle = this; Interop.mincore.StartThreadpoolIo(_threadPoolHandle); return Win32ThreadPoolNativeOverlapped.ToNativeOverlapped(preAllocated._overlapped); } catch { if (addedRefToPreAllocated) preAllocated.Release(); if (addedRefToThis) Release(); throw; } } [CLSCompliant(false)] public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped) { if (overlapped == null) throw new ArgumentNullException(nameof(overlapped)); Win32ThreadPoolNativeOverlapped* threadPoolOverlapped = Win32ThreadPoolNativeOverlapped.FromNativeOverlapped(overlapped); Win32ThreadPoolNativeOverlapped.OverlappedData data = GetOverlappedData(threadPoolOverlapped, this); if (!data._completed) { Interop.mincore.CancelThreadpoolIo(_threadPoolHandle); Release(); } data._boundHandle = null; data._completed = false; if (data._preAllocated != null) data._preAllocated.Release(); else Win32ThreadPoolNativeOverlapped.Free(threadPoolOverlapped); } [CLSCompliant(false)] public unsafe static object GetNativeOverlappedState(NativeOverlapped* overlapped) { if (overlapped == null) throw new ArgumentNullException(nameof(overlapped)); Win32ThreadPoolNativeOverlapped* threadPoolOverlapped = Win32ThreadPoolNativeOverlapped.FromNativeOverlapped(overlapped); Win32ThreadPoolNativeOverlapped.OverlappedData data = GetOverlappedData(threadPoolOverlapped, null); return threadPoolOverlapped->Data._state; } private static unsafe Win32ThreadPoolNativeOverlapped.OverlappedData GetOverlappedData(Win32ThreadPoolNativeOverlapped* overlapped, ThreadPoolBoundHandle expectedBoundHandle) { Win32ThreadPoolNativeOverlapped.OverlappedData data = overlapped->Data; if (data._boundHandle == null) throw new ArgumentException(SR.Argument_NativeOverlappedAlreadyFree, nameof(overlapped)); if (expectedBoundHandle != null && data._boundHandle != expectedBoundHandle) throw new ArgumentException(SR.Argument_NativeOverlappedWrongBoundHandle, nameof(overlapped)); return data; } private static unsafe void OnNativeIOCompleted(IntPtr instance, IntPtr context, IntPtr overlappedPtr, uint ioResult, UIntPtr numberOfBytesTransferred, IntPtr ioPtr) { Win32ThreadPoolNativeOverlapped* overlapped = (Win32ThreadPoolNativeOverlapped*)overlappedPtr; ThreadPoolBoundHandle boundHandle = overlapped->Data._boundHandle; if (boundHandle == null) throw new InvalidOperationException(SR.Argument_NativeOverlappedAlreadyFree); boundHandle.Release(); Win32ThreadPoolNativeOverlapped.CompleteWithCallback(ioResult, (uint)numberOfBytesTransferred, overlapped); } private bool AddRef() { return _lifetime.AddRef(this); } private void Release() { _lifetime.Release(this); } public void Dispose() { _lifetime.Dispose(this); GC.SuppressFinalize(this); } ~ThreadPoolBoundHandle() { // // During shutdown, don't automatically clean up, because this instance may still be // reachable/usable by other code. // if (!Environment.HasShutdownStarted) Dispose(); } void IDeferredDisposable.OnFinalRelease(bool disposed) { if (disposed) _threadPoolHandle.Dispose(); } } }
using System; using System.Collections.Generic; using Microsoft.DirectX; namespace Simbiosis { // STANDARD BUILT-IN CELL TYPES // These are the specific cell types in the "starter set", compiled as CellType.dll // Cells of these types may be specified in the genome using just their class name, // whereas cell types in other dlls need a dllassemblyname.classname format #region ============================== new types ===================================== /// <summary> /// Female reproductive organ /// /// TEMPORARY: open/close the jaws using input 0 /// /// INPUT 0 = /// /// </summary> public class FemaleRepro : Physiology { /// <summary> /// ONLY set the physical properties in the constructor. Use Init() for initialisation. /// </summary> public FemaleRepro() { // Define my properties Mass = 0.2f; Resistance = 0.2f; Bouyancy = 0f; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { inputTerminal = new NerveEnding[1]; } /// <summary> /// Called every frame /// Nerves and JointOutputs should normally be updated here /// </summary> public override void FastUpdate(float elapsedTime) { // Update nerve signals base.FastUpdate(elapsedTime); for (int j = 0; j < JointOutput.Length; j++) JointOutput[j] = Input(0); // write one nerve signal to the muscle joint(s) } } #endregion #region =============================== old types not yet updated ======================================= /// <summary> /// Standard muscle cell: a single nerve input causes flexion /// /// INPUT 0 = muscle position (NOTE: Other muscle types might be supplied with a force rather than a position) /// /// </summary> public class Muscle : Physiology { /// <summary> /// ONLY set the physical properties in the constructor. Use Init() for initialisation. /// </summary> public Muscle() { // Define my properties Mass = 0.2f; Resistance = 0.2f; Bouyancy = 0f; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { inputTerminal = new NerveEnding[1]; } /// <summary> /// Called every frame /// Nerves and JointOutputs should normally be updated here /// </summary> public override void FastUpdate(float elapsedTime) { // Update nerve signals base.FastUpdate(elapsedTime); for (int j = 0; j < JointOutput.Length; j++) JointOutput[j] = Input(0); // write one nerve signal to the muscle joint(s) } } /// <summary> /// This is the core cell - it contains the reproductive organs and energy storage for the creature. /// All multicellular creatures must have a single core cell as the ROOT of their cell hierarchy. /// /// TEMPORARILY, treat core as a pattern generator /// output0 = swim motion /// output1 = sinusoid /// output2 = fast sinusoid /// /// </summary> public class Core : Physiology { PatternGenerator gen1 = new PatternGenerator(); PatternGenerator gen2 = new PatternGenerator(); PatternGenerator gen3 = new PatternGenerator(); /// <summary> /// ONLY set the physical properties in the constructor. Use Init() for initialisation. /// </summary> public Core() { // Define my properties Mass = 0.8f; Resistance = 0.6f; Bouyancy = 0f; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { outputTerminal = new NerveEnding[3]; gen1.Swim(0.4f, 1f, 2f, true); gen2.Sinusoid(6); gen3.Sinusoid(1); } /// <summary> /// Called on a SlowUpdate tick (about 4 times a second). /// </summary> public override void SlowUpdate() { } /// <summary> /// Called every frame /// Nerves and JointOutputs should normally be updated here /// </summary> public override void FastUpdate(float elapsedTime) { // Update nerve signals base.FastUpdate(elapsedTime); gen1.Update(elapsedTime); gen2.Update(elapsedTime); gen3.Update(elapsedTime); Output(0, gen1.state); Output(1, gen2.state); Output(2, gen3.state); } } /// <summary> /// Simple fin - does nothing - just a large water resistance /// /// /// </summary> public class Fin : Physiology { /// <summary> /// ONLY set the physical properties in the constructor. Use Init() for initialisation. /// </summary> public Fin() { // Define my properties Mass = 0.2f; Resistance = 0.8f; Bouyancy = 0f; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { } /// <summary> /// Called every frame /// Since we have no sockets we'll override the base FastUpdate() to avoid wasting time trying to read/write nerves /// </summary> public override void FastUpdate(float elapsedTime) { } } /// <summary> /// SpinySucker - toothed mouth for sucking energy /// /// INPUT 0 = teeth position (0=relaxed, 1=gripping) /// /// </summary> public class SpinySucker : Physiology { /// <summary> /// ONLY set the physical properties in the constructor. Use Init() for initialisation. /// </summary> public SpinySucker() { // Define my properties Mass = 0.2f; Resistance = 0.2f; Bouyancy = -0.05f; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { inputTerminal = new NerveEnding[1]; } /// <summary> /// Called every frame /// Nerves and JointOutputs should normally be updated here /// </summary> public override void FastUpdate(float elapsedTime) { // Update nerve signals base.FastUpdate(elapsedTime); for (int j = 0; j < JointOutput.Length; j++) JointOutput[j] = Input(0); // write one nerve signal to all the tooth joints } } /// <summary> /// Bend1, Bend2 etc. - various bends and branches. No functionality other than propagating signals /// </summary> public class Bend : Physiology { /// <summary> /// ONLY set the physical properties in the constructor. Use Init() for initialisation. /// </summary> public Bend() { // Define my properties Mass = 0.1f; Resistance = 0.1f; Bouyancy = 0.0f; } } /// <summary> /// Plate1, Plate2 etc. - various heavy armoured plates. No functionality other than propagating signals /// </summary> public class Plate : Physiology { /// <summary> /// ONLY set the physical properties in the constructor. Use Init() for initialisation. /// </summary> public Plate() { // Define my properties Mass = 0.3f; Resistance = 0.3f; Bouyancy = -0.3f; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { } } /// <summary> /// Foot1, Foot2 etc. - Slightly heavy feet. No functionality at all /// </summary> public class Foot : Physiology { /// <summary> /// ONLY set the physical properties in the constructor. Use Init() for initialisation. /// </summary> public Foot() { // Define my properties Mass = 0.1f; Resistance = 0.1f; Bouyancy = -0.1f; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { } /// <summary> /// Override FastUpdate because we have no nerves /// </summary> public override void FastUpdate(float elapsedTime) { } } //---------------------------------------------- new types - no graphics yet ------------------------------------------------- /// <summary> /// Sonar - Active sensor. Measures distance to nearest obstruction (terrain or creature). /// Equally sensitive to all obstructions less than given angle from the sensor axis. /// </summary> class Sonar : Physiology { /// <summary> Adjustable range - default is 20 </summary> private float range = 20; /// <summary> Adjustable acceptance angle in degrees either side of the line of sight </summary> private float halfAngle = (float)Math.PI / 2.0f; public Sonar() { // Define my properties Mass = 0.1f; Resistance = 0.1f; Bouyancy = 0f; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { outputTerminal = new NerveEnding[1]; } /// <summary> /// Called on a SlowUpdate tick (about 4 times a second). /// Read/write/modify your sensory/motor nerves and/or chemicals, to implement your behaviour /// </summary> public override void SlowUpdate() { // Calculate the sensor signal... float signal = 0; // largest 'sonar echo' so far found SensorItem[] items = owner.GetObjectsInRange(0, range, true, true, false); // Get a list of all creatures and tiles within range foreach (SensorItem item in items) { float angle = item.Angle(); // angle of obj from line of sight if (angle < halfAngle) // if object is within sensor cone { float dist = item.Distance(range); // get range-relative distance to obj if (dist > signal) signal = dist; // if this is closest so far, keep it } } Output(0, signal); // sonar signal is our primary output } } /// <summary> /// Test sensory cell, using the ImageSensor (eye) mesh /// </summary> public class ImageSensor : Physiology { private int blink = 0; /// <summary> /// ONLY set the physical properties in the constructor. Use Init() for initialisation. /// </summary> public ImageSensor() { // Define my properties Mass = 0.2f; Resistance = 0.2f; Bouyancy = 0f; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { outputTerminal = new NerveEnding[1]; } /// <summary> /// Called on a SlowUpdate tick (about 4 times a second). /// </summary> public override void SlowUpdate() { // Get a list of all objects in range of my hotspot SensorItem[] item = owner.GetObjectsInRange(0, 50, true, false, true); // TEMP: just count those that are inside a 45 degree cone blink = 0; for (int i = 0; i < item.Length; i++) { const float cone = (float)Math.PI / 8.0f; float angle = item[i].Angle(); if ((angle >= -cone) && (angle <= cone)) blink = 1; } } /// <summary> /// Called every frame /// Nerves and JointOutputs should normally be updated here, although slow nerve changes can happen on a slowupdate /// </summary> public override void FastUpdate(float elapsedTime) { // Update nerve signals base.FastUpdate(elapsedTime); // JointOutput[0] = Nerve[inputTap[0]]; // eyelids // JointOutput[1] = Nerve[inputTap[1]]; // eyelids if ((blink > 0) && (JointOutput[0] < 1.0f)) { JointOutput[0] += 0.1f; // blink to show we've seen something JointOutput[1] += 0.1f; // eyelids } else if ((blink == 0) && (JointOutput[0] > 0)) { JointOutput[0] -= 0.1f; // blink to show we've seen something JointOutput[1] -= 0.1f; // eyelids } } } #endregion }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Logging.V2.Tests { using Google.Api.Gax; using Google.Api.Gax.Grpc; using apis = Google.Cloud.Logging.V2; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using Moq; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; using Xunit; /// <summary>Generated unit tests</summary> public class GeneratedConfigServiceV2ClientTest { [Fact] public void GetSink() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); GetSinkRequest expectedRequest = new GetSinkRequest { SinkNameAsSinkNameOneof = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")), }; LogSink expectedResponse = new LogSink { Name = "name3373707", DestinationAsResourceName = new ProjectName("[PROJECT]"), Filter = "filter-1274492040", WriterIdentity = "writerIdentity775638794", IncludeChildren = true, }; mockGrpcClient.Setup(x => x.GetSink(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); SinkNameOneof sinkName = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")); LogSink response = client.GetSink(sinkName); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetSinkAsync() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); GetSinkRequest expectedRequest = new GetSinkRequest { SinkNameAsSinkNameOneof = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")), }; LogSink expectedResponse = new LogSink { Name = "name3373707", DestinationAsResourceName = new ProjectName("[PROJECT]"), Filter = "filter-1274492040", WriterIdentity = "writerIdentity775638794", IncludeChildren = true, }; mockGrpcClient.Setup(x => x.GetSinkAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogSink>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); SinkNameOneof sinkName = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")); LogSink response = await client.GetSinkAsync(sinkName); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void GetSink2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); GetSinkRequest request = new GetSinkRequest { SinkNameAsSinkNameOneof = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")), }; LogSink expectedResponse = new LogSink { Name = "name3373707", DestinationAsResourceName = new ProjectName("[PROJECT]"), Filter = "filter-1274492040", WriterIdentity = "writerIdentity775638794", IncludeChildren = true, }; mockGrpcClient.Setup(x => x.GetSink(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); LogSink response = client.GetSink(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetSinkAsync2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); GetSinkRequest request = new GetSinkRequest { SinkNameAsSinkNameOneof = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")), }; LogSink expectedResponse = new LogSink { Name = "name3373707", DestinationAsResourceName = new ProjectName("[PROJECT]"), Filter = "filter-1274492040", WriterIdentity = "writerIdentity775638794", IncludeChildren = true, }; mockGrpcClient.Setup(x => x.GetSinkAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogSink>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); LogSink response = await client.GetSinkAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void CreateSink() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); CreateSinkRequest expectedRequest = new CreateSinkRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), Sink = new LogSink(), }; LogSink expectedResponse = new LogSink { Name = "name3373707", DestinationAsResourceName = new ProjectName("[PROJECT]"), Filter = "filter-1274492040", WriterIdentity = "writerIdentity775638794", IncludeChildren = true, }; mockGrpcClient.Setup(x => x.CreateSink(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); ParentNameOneof parent = ParentNameOneof.From(new ProjectName("[PROJECT]")); LogSink sink = new LogSink(); LogSink response = client.CreateSink(parent, sink); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task CreateSinkAsync() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); CreateSinkRequest expectedRequest = new CreateSinkRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), Sink = new LogSink(), }; LogSink expectedResponse = new LogSink { Name = "name3373707", DestinationAsResourceName = new ProjectName("[PROJECT]"), Filter = "filter-1274492040", WriterIdentity = "writerIdentity775638794", IncludeChildren = true, }; mockGrpcClient.Setup(x => x.CreateSinkAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogSink>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); ParentNameOneof parent = ParentNameOneof.From(new ProjectName("[PROJECT]")); LogSink sink = new LogSink(); LogSink response = await client.CreateSinkAsync(parent, sink); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void CreateSink2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); CreateSinkRequest request = new CreateSinkRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), Sink = new LogSink(), }; LogSink expectedResponse = new LogSink { Name = "name3373707", DestinationAsResourceName = new ProjectName("[PROJECT]"), Filter = "filter-1274492040", WriterIdentity = "writerIdentity775638794", IncludeChildren = true, }; mockGrpcClient.Setup(x => x.CreateSink(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); LogSink response = client.CreateSink(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task CreateSinkAsync2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); CreateSinkRequest request = new CreateSinkRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), Sink = new LogSink(), }; LogSink expectedResponse = new LogSink { Name = "name3373707", DestinationAsResourceName = new ProjectName("[PROJECT]"), Filter = "filter-1274492040", WriterIdentity = "writerIdentity775638794", IncludeChildren = true, }; mockGrpcClient.Setup(x => x.CreateSinkAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogSink>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); LogSink response = await client.CreateSinkAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void UpdateSink() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); UpdateSinkRequest expectedRequest = new UpdateSinkRequest { SinkNameAsSinkNameOneof = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")), Sink = new LogSink(), UpdateMask = new FieldMask(), }; LogSink expectedResponse = new LogSink { Name = "name3373707", DestinationAsResourceName = new ProjectName("[PROJECT]"), Filter = "filter-1274492040", WriterIdentity = "writerIdentity775638794", IncludeChildren = true, }; mockGrpcClient.Setup(x => x.UpdateSink(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); SinkNameOneof sinkName = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")); LogSink sink = new LogSink(); FieldMask updateMask = new FieldMask(); LogSink response = client.UpdateSink(sinkName, sink, updateMask); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task UpdateSinkAsync() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); UpdateSinkRequest expectedRequest = new UpdateSinkRequest { SinkNameAsSinkNameOneof = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")), Sink = new LogSink(), UpdateMask = new FieldMask(), }; LogSink expectedResponse = new LogSink { Name = "name3373707", DestinationAsResourceName = new ProjectName("[PROJECT]"), Filter = "filter-1274492040", WriterIdentity = "writerIdentity775638794", IncludeChildren = true, }; mockGrpcClient.Setup(x => x.UpdateSinkAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogSink>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); SinkNameOneof sinkName = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")); LogSink sink = new LogSink(); FieldMask updateMask = new FieldMask(); LogSink response = await client.UpdateSinkAsync(sinkName, sink, updateMask); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void UpdateSink2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); UpdateSinkRequest expectedRequest = new UpdateSinkRequest { SinkNameAsSinkNameOneof = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")), Sink = new LogSink(), }; LogSink expectedResponse = new LogSink { Name = "name3373707", DestinationAsResourceName = new ProjectName("[PROJECT]"), Filter = "filter-1274492040", WriterIdentity = "writerIdentity775638794", IncludeChildren = true, }; mockGrpcClient.Setup(x => x.UpdateSink(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); SinkNameOneof sinkName = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")); LogSink sink = new LogSink(); LogSink response = client.UpdateSink(sinkName, sink); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task UpdateSinkAsync2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); UpdateSinkRequest expectedRequest = new UpdateSinkRequest { SinkNameAsSinkNameOneof = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")), Sink = new LogSink(), }; LogSink expectedResponse = new LogSink { Name = "name3373707", DestinationAsResourceName = new ProjectName("[PROJECT]"), Filter = "filter-1274492040", WriterIdentity = "writerIdentity775638794", IncludeChildren = true, }; mockGrpcClient.Setup(x => x.UpdateSinkAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogSink>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); SinkNameOneof sinkName = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")); LogSink sink = new LogSink(); LogSink response = await client.UpdateSinkAsync(sinkName, sink); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void UpdateSink3() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); UpdateSinkRequest request = new UpdateSinkRequest { SinkNameAsSinkNameOneof = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")), Sink = new LogSink(), }; LogSink expectedResponse = new LogSink { Name = "name3373707", DestinationAsResourceName = new ProjectName("[PROJECT]"), Filter = "filter-1274492040", WriterIdentity = "writerIdentity775638794", IncludeChildren = true, }; mockGrpcClient.Setup(x => x.UpdateSink(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); LogSink response = client.UpdateSink(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task UpdateSinkAsync3() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); UpdateSinkRequest request = new UpdateSinkRequest { SinkNameAsSinkNameOneof = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")), Sink = new LogSink(), }; LogSink expectedResponse = new LogSink { Name = "name3373707", DestinationAsResourceName = new ProjectName("[PROJECT]"), Filter = "filter-1274492040", WriterIdentity = "writerIdentity775638794", IncludeChildren = true, }; mockGrpcClient.Setup(x => x.UpdateSinkAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogSink>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); LogSink response = await client.UpdateSinkAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void DeleteSink() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); DeleteSinkRequest expectedRequest = new DeleteSinkRequest { SinkNameAsSinkNameOneof = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteSink(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); SinkNameOneof sinkName = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")); client.DeleteSink(sinkName); mockGrpcClient.VerifyAll(); } [Fact] public async Task DeleteSinkAsync() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); DeleteSinkRequest expectedRequest = new DeleteSinkRequest { SinkNameAsSinkNameOneof = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteSinkAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); SinkNameOneof sinkName = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")); await client.DeleteSinkAsync(sinkName); mockGrpcClient.VerifyAll(); } [Fact] public void DeleteSink2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); DeleteSinkRequest request = new DeleteSinkRequest { SinkNameAsSinkNameOneof = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteSink(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); client.DeleteSink(request); mockGrpcClient.VerifyAll(); } [Fact] public async Task DeleteSinkAsync2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); DeleteSinkRequest request = new DeleteSinkRequest { SinkNameAsSinkNameOneof = SinkNameOneof.From(new SinkName("[PROJECT]", "[SINK]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteSinkAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); await client.DeleteSinkAsync(request); mockGrpcClient.VerifyAll(); } [Fact] public void GetExclusion() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); GetExclusionRequest expectedRequest = new GetExclusionRequest { ExclusionNameOneof = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")), }; LogExclusion expectedResponse = new LogExclusion { Name = "name2-1052831874", Description = "description-1724546052", Filter = "filter-1274492040", Disabled = true, }; mockGrpcClient.Setup(x => x.GetExclusion(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); ExclusionNameOneof name = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")); LogExclusion response = client.GetExclusion(name); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetExclusionAsync() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); GetExclusionRequest expectedRequest = new GetExclusionRequest { ExclusionNameOneof = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")), }; LogExclusion expectedResponse = new LogExclusion { Name = "name2-1052831874", Description = "description-1724546052", Filter = "filter-1274492040", Disabled = true, }; mockGrpcClient.Setup(x => x.GetExclusionAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogExclusion>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); ExclusionNameOneof name = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")); LogExclusion response = await client.GetExclusionAsync(name); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void GetExclusion2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); GetExclusionRequest request = new GetExclusionRequest { ExclusionNameOneof = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")), }; LogExclusion expectedResponse = new LogExclusion { Name = "name2-1052831874", Description = "description-1724546052", Filter = "filter-1274492040", Disabled = true, }; mockGrpcClient.Setup(x => x.GetExclusion(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); LogExclusion response = client.GetExclusion(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetExclusionAsync2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); GetExclusionRequest request = new GetExclusionRequest { ExclusionNameOneof = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")), }; LogExclusion expectedResponse = new LogExclusion { Name = "name2-1052831874", Description = "description-1724546052", Filter = "filter-1274492040", Disabled = true, }; mockGrpcClient.Setup(x => x.GetExclusionAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogExclusion>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); LogExclusion response = await client.GetExclusionAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void CreateExclusion() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); CreateExclusionRequest expectedRequest = new CreateExclusionRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), Exclusion = new LogExclusion(), }; LogExclusion expectedResponse = new LogExclusion { Name = "name3373707", Description = "description-1724546052", Filter = "filter-1274492040", Disabled = true, }; mockGrpcClient.Setup(x => x.CreateExclusion(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); ParentNameOneof parent = ParentNameOneof.From(new ProjectName("[PROJECT]")); LogExclusion exclusion = new LogExclusion(); LogExclusion response = client.CreateExclusion(parent, exclusion); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task CreateExclusionAsync() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); CreateExclusionRequest expectedRequest = new CreateExclusionRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), Exclusion = new LogExclusion(), }; LogExclusion expectedResponse = new LogExclusion { Name = "name3373707", Description = "description-1724546052", Filter = "filter-1274492040", Disabled = true, }; mockGrpcClient.Setup(x => x.CreateExclusionAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogExclusion>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); ParentNameOneof parent = ParentNameOneof.From(new ProjectName("[PROJECT]")); LogExclusion exclusion = new LogExclusion(); LogExclusion response = await client.CreateExclusionAsync(parent, exclusion); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void CreateExclusion2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); CreateExclusionRequest request = new CreateExclusionRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), Exclusion = new LogExclusion(), }; LogExclusion expectedResponse = new LogExclusion { Name = "name3373707", Description = "description-1724546052", Filter = "filter-1274492040", Disabled = true, }; mockGrpcClient.Setup(x => x.CreateExclusion(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); LogExclusion response = client.CreateExclusion(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task CreateExclusionAsync2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); CreateExclusionRequest request = new CreateExclusionRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), Exclusion = new LogExclusion(), }; LogExclusion expectedResponse = new LogExclusion { Name = "name3373707", Description = "description-1724546052", Filter = "filter-1274492040", Disabled = true, }; mockGrpcClient.Setup(x => x.CreateExclusionAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogExclusion>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); LogExclusion response = await client.CreateExclusionAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void UpdateExclusion() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); UpdateExclusionRequest expectedRequest = new UpdateExclusionRequest { ExclusionNameOneof = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")), Exclusion = new LogExclusion(), UpdateMask = new FieldMask(), }; LogExclusion expectedResponse = new LogExclusion { Name = "name2-1052831874", Description = "description-1724546052", Filter = "filter-1274492040", Disabled = true, }; mockGrpcClient.Setup(x => x.UpdateExclusion(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); ExclusionNameOneof name = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")); LogExclusion exclusion = new LogExclusion(); FieldMask updateMask = new FieldMask(); LogExclusion response = client.UpdateExclusion(name, exclusion, updateMask); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task UpdateExclusionAsync() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); UpdateExclusionRequest expectedRequest = new UpdateExclusionRequest { ExclusionNameOneof = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")), Exclusion = new LogExclusion(), UpdateMask = new FieldMask(), }; LogExclusion expectedResponse = new LogExclusion { Name = "name2-1052831874", Description = "description-1724546052", Filter = "filter-1274492040", Disabled = true, }; mockGrpcClient.Setup(x => x.UpdateExclusionAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogExclusion>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); ExclusionNameOneof name = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")); LogExclusion exclusion = new LogExclusion(); FieldMask updateMask = new FieldMask(); LogExclusion response = await client.UpdateExclusionAsync(name, exclusion, updateMask); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void UpdateExclusion2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); UpdateExclusionRequest request = new UpdateExclusionRequest { ExclusionNameOneof = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")), Exclusion = new LogExclusion(), UpdateMask = new FieldMask(), }; LogExclusion expectedResponse = new LogExclusion { Name = "name2-1052831874", Description = "description-1724546052", Filter = "filter-1274492040", Disabled = true, }; mockGrpcClient.Setup(x => x.UpdateExclusion(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); LogExclusion response = client.UpdateExclusion(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task UpdateExclusionAsync2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); UpdateExclusionRequest request = new UpdateExclusionRequest { ExclusionNameOneof = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")), Exclusion = new LogExclusion(), UpdateMask = new FieldMask(), }; LogExclusion expectedResponse = new LogExclusion { Name = "name2-1052831874", Description = "description-1724546052", Filter = "filter-1274492040", Disabled = true, }; mockGrpcClient.Setup(x => x.UpdateExclusionAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogExclusion>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); LogExclusion response = await client.UpdateExclusionAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void DeleteExclusion() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); DeleteExclusionRequest expectedRequest = new DeleteExclusionRequest { ExclusionNameOneof = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteExclusion(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); ExclusionNameOneof name = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")); client.DeleteExclusion(name); mockGrpcClient.VerifyAll(); } [Fact] public async Task DeleteExclusionAsync() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); DeleteExclusionRequest expectedRequest = new DeleteExclusionRequest { ExclusionNameOneof = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteExclusionAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); ExclusionNameOneof name = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")); await client.DeleteExclusionAsync(name); mockGrpcClient.VerifyAll(); } [Fact] public void DeleteExclusion2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); DeleteExclusionRequest request = new DeleteExclusionRequest { ExclusionNameOneof = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteExclusion(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); client.DeleteExclusion(request); mockGrpcClient.VerifyAll(); } [Fact] public async Task DeleteExclusionAsync2() { Mock<ConfigServiceV2.ConfigServiceV2Client> mockGrpcClient = new Mock<ConfigServiceV2.ConfigServiceV2Client>(MockBehavior.Strict); DeleteExclusionRequest request = new DeleteExclusionRequest { ExclusionNameOneof = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteExclusionAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); ConfigServiceV2Client client = new ConfigServiceV2ClientImpl(mockGrpcClient.Object, null); await client.DeleteExclusionAsync(request); mockGrpcClient.VerifyAll(); } } }
/* Copyright (c) 2014, Lars Brubaker All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using System.Diagnostics; using System.IO; using MatterHackers.Agg; using MatterHackers.Agg.Platform; using MatterHackers.Agg.UI; using MatterHackers.RenderOpenGl; using MatterHackers.VectorMath; namespace MatterHackers.MeshVisualizer { public class MeshViewerApplication : SystemWindow { protected MeshViewerWidget meshViewerWidget; private Button openFileButton; private CheckBox bedCheckBox; private CheckBox wireframeCheckBox; private GuiWidget viewArea; public MeshViewerWidget MeshViewerWidget { get { return meshViewerWidget; } } public MeshViewerApplication(bool doDepthPeeling, string meshFileToLoad = "") : base(2200, 600) { this.doDepthPeeling = doDepthPeeling; BackgroundColor = Color.White; MinimumSize = new Vector2(200, 200); Title = "MatterHackers MeshViewr"; UseOpenGL = true; FlowLayoutWidget mainContainer = new FlowLayoutWidget(FlowDirection.TopToBottom); mainContainer.AnchorAll(); viewArea = new GuiWidget(); viewArea.AnchorAll(); Vector3 viewerVolume = new Vector3(200, 200, 200); meshViewerWidget = new MeshViewerWidget(viewerVolume, new Vector2(100, 100), BedShape.Rectangular, "No Part Loaded"); meshViewerWidget.AnchorAll(); if (!doDepthPeeling) { viewArea.AddChild(meshViewerWidget); } mainContainer.AddChild(viewArea); FlowLayoutWidget buttonPanel = new FlowLayoutWidget(FlowDirection.LeftToRight); buttonPanel.HAnchor = HAnchor.Stretch; buttonPanel.Padding = new BorderDouble(3, 3); buttonPanel.BackgroundColor = Color.DarkGray; if (meshFileToLoad != "") { meshViewerWidget.LoadItemIntoScene(meshFileToLoad); } else { openFileButton = new Button("Open 3D File", 0, 0); openFileButton.Click += openFileButton_ButtonClick; buttonPanel.AddChild(openFileButton); } bedCheckBox = new CheckBox("Bed"); bedCheckBox.Checked = true; buttonPanel.AddChild(bedCheckBox); wireframeCheckBox = new CheckBox("Wireframe"); buttonPanel.AddChild(wireframeCheckBox); GuiWidget leftRightSpacer = new GuiWidget(); leftRightSpacer.HAnchor = HAnchor.Stretch; buttonPanel.AddChild(leftRightSpacer); mainContainer.AddChild(buttonPanel); this.AddChild(mainContainer); this.AnchorAll(); bedCheckBox.CheckedStateChanged += (s, e) => { meshViewerWidget.RenderBed = bedCheckBox.Checked; }; wireframeCheckBox.CheckedStateChanged += (s, e) => { if (wireframeCheckBox.Checked) { meshViewerWidget.RenderType = RenderTypes.Polygons; } else { meshViewerWidget.RenderType = RenderTypes.Shaded; } }; } private void openFileButton_ButtonClick(object sender, EventArgs mouseEvent) { UiThread.RunOnIdle(DoOpenFileButton_ButtonClick); } private string ValidFileExtensions { get; } = ".STL;.AMF;.OBJ"; private void DoOpenFileButton_ButtonClick() { AggContext.FileDialogs.OpenFileDialog( new OpenFileDialogParams("3D Mesh Files|*.stl;*.amf;*.obj"), async (openParams) => { await meshViewerWidget.LoadItemIntoScene(openParams.FileName); var children = meshViewerWidget.Scene.Children; children[children.Count - 1].Color = Color.FireEngineRed.WithAlpha(100); }); Invalidate(); } public override void OnMouseEnterBounds(MouseEventArgs mouseEvent) { if (mouseEvent.DragFiles?.Count > 0) { foreach (string file in mouseEvent.DragFiles) { string extension = Path.GetExtension(file).ToUpper(); if ((extension != "" && this.ValidFileExtensions.Contains(extension))) { mouseEvent.AcceptDrop = true; } } } base.OnMouseEnterBounds(mouseEvent); } public override void OnMouseMove(MouseEventArgs mouseEvent) { if (mouseEvent.DragFiles?.Count > 0) { foreach (string file in mouseEvent.DragFiles) { string extension = Path.GetExtension(file).ToUpper(); if ((extension != "" && this.ValidFileExtensions.Contains(extension))) { mouseEvent.AcceptDrop = true; } } } base.OnMouseMove(mouseEvent); } public override void OnMouseUp(MouseEventArgs mouseEvent) { if (mouseEvent.DragFiles?.Count > 0) { foreach (string droppedFileName in mouseEvent.DragFiles) { string extension = Path.GetExtension(droppedFileName).ToUpper(); if ((extension != "" && this.ValidFileExtensions.Contains(extension))) { meshViewerWidget.LoadItemIntoScene(droppedFileName); break; } } } base.OnMouseUp(mouseEvent); } private Stopwatch totalDrawTime = new Stopwatch(); private int drawCount = 0; private DepthPeeling depthPeeling; private bool doDepthPeeling; public override void OnDraw(Graphics2D graphics2D) { if (doDepthPeeling) { if (depthPeeling != null) { depthPeeling.glutDisplayFunc(meshViewerWidget.World, meshViewerWidget.Scene.Children[0]); } else if (meshViewerWidget.Scene.Children.Count > 0) { depthPeeling = new DepthPeeling(meshViewerWidget.Scene.Children[0].Mesh); depthPeeling.ReshapeFunc((int)Width, (int)Height); } } totalDrawTime.Restart(); base.OnDraw(graphics2D); totalDrawTime.Stop(); if (true) { long memory = GC.GetTotalMemory(false); this.Title = string.Format("Allocated = {0:n0} : {1}ms, d{2} Size = {3}x{4}", memory, totalDrawTime.ElapsedMilliseconds, drawCount++, this.Width, this.Height); //GC.Collect(); } UiThread.RunOnIdle(Invalidate); } [STAThread] public static void Main(string[] args) { // Force OpenGL var Glfw = false; if (Glfw) { AggContext.Config.ProviderTypes.SystemWindowProvider = "MatterHackers.GlfwProvider.GlfwWindowProvider, MatterHackers.GlfwProvider"; } else { AggContext.Config.ProviderTypes.SystemWindowProvider = "MatterHackers.Agg.UI.OpenGLWinformsWindowProvider, agg_platform_win32"; } var downloadsDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads"); var possibleMeshes = new string[] { "architest_18.stl", "Runout Sensor.stl", "Swoop Shell_rev9.STL", "Engine-Benchmark.stl" }; var meshPath = ""; for (int i = 0; i < possibleMeshes.Length; i++) { meshPath = Path.Combine(downloadsDirectory, possibleMeshes[i]); if (File.Exists(meshPath)) { break; } } MeshViewerApplication app = new MeshViewerApplication(true, meshPath); SingleWindowProvider.SetWindowTheme(Color.Black, 12, () => new Button("X", 0, 0), 3, Color.LightGray, Color.DarkGray); app.ShowAsSystemWindow(); } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Testing; using Microsoft.CodeAnalysis.Text; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.AvoidEmptyInterfacesAnalyzer, Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpAvoidEmptyInterfacesFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.AvoidEmptyInterfacesAnalyzer, Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicAvoidEmptyInterfacesFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class AvoidEmptyInterfacesTests { [Fact] public async Task TestCSharpEmptyPublicInterface() { await VerifyCS.VerifyAnalyzerAsync(@" public interface I { }", CreateCSharpResult(2, 18)); } [Fact] public async Task TestBasicEmptyPublicInterface() { await VerifyVB.VerifyAnalyzerAsync(@" Public Interface I End Interface", CreateBasicResult(2, 18)); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task TestCSharpEmptyInternalInterface() { await VerifyCS.VerifyAnalyzerAsync(@" interface I { }"); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task TestBasicEmptyInternalInterface() { await VerifyVB.VerifyAnalyzerAsync(@" Interface I End Interface"); } [Fact] public async Task TestCSharpNonEmptyInterface1() { await VerifyCS.VerifyAnalyzerAsync(@" public interface I { void DoStuff(); }"); } [Fact] public async Task TestBasicNonEmptyInterface1() { await VerifyVB.VerifyAnalyzerAsync(@" Public Interface I Function GetStuff() as Integer End Interface"); } [Fact] public async Task TestCSharpEmptyInterfaceWithNoInheritedMembers() { await VerifyCS.VerifyAnalyzerAsync(@" public interface I : IBase { } public interface IBase { }", CreateCSharpResult(2, 18), CreateCSharpResult(6, 18)); } [Fact] public async Task TestBasicEmptyInterfaceWithNoInheritedMembers() { await VerifyVB.VerifyAnalyzerAsync(@" Public Interface I Inherits IBase End Interface Public Interface IBase End Interface", CreateBasicResult(2, 18), CreateBasicResult(6, 18)); } [Fact] public async Task TestCSharpEmptyInterfaceWithInheritedMembers() { await VerifyCS.VerifyAnalyzerAsync(@" public interface I : IBase { } public interface IBase { void DoStuff(); }"); } [Fact] public async Task TestBasicEmptyInterfaceWithInheritedMembers() { await VerifyVB.VerifyAnalyzerAsync(@" Public Interface I Inherits IBase End Interface Public Interface IBase Sub DoStuff() End Interface"); } [Theory] // General analyzer option [InlineData("public", "dotnet_code_quality.api_surface = public")] [InlineData("public", "dotnet_code_quality.api_surface = private, internal, public")] [InlineData("public", "dotnet_code_quality.api_surface = all")] [InlineData("protected", "dotnet_code_quality.api_surface = public")] [InlineData("protected", "dotnet_code_quality.api_surface = private, internal, public")] [InlineData("protected", "dotnet_code_quality.api_surface = all")] [InlineData("internal", "dotnet_code_quality.api_surface = internal")] [InlineData("internal", "dotnet_code_quality.api_surface = private, internal")] [InlineData("internal", "dotnet_code_quality.api_surface = all")] [InlineData("private", "dotnet_code_quality.api_surface = private")] [InlineData("private", "dotnet_code_quality.api_surface = private, public")] [InlineData("private", "dotnet_code_quality.api_surface = all")] // Specific analyzer option [InlineData("internal", "dotnet_code_quality.CA1040.api_surface = all")] [InlineData("internal", "dotnet_code_quality.Design.api_surface = all")] // General + Specific analyzer option [InlineData("internal", @"dotnet_code_quality.api_surface = private dotnet_code_quality.CA1040.api_surface = all")] // Case-insensitive analyzer option [InlineData("internal", "DOTNET_code_quality.CA1040.API_SURFACE = ALL")] // Invalid analyzer option ignored [InlineData("internal", @"dotnet_code_quality.api_surface = all dotnet_code_quality.CA1040.api_surface_2 = private")] public async Task TestCSharpEmptyInterface_AnalyzerOptions_Diagnostic(string accessibility, string editorConfigText) { await new VerifyCS.Test { TestState = { Sources = { $@" public class C {{ {accessibility} interface I {{ }} }}" }, AdditionalFiles = { (".editorconfig", editorConfigText) } }, ExpectedDiagnostics = { CreateCSharpResult(4, 16 + accessibility.Length), } }.RunAsync(); } [Theory] // General analyzer option [InlineData("Public", "dotnet_code_quality.api_surface = Public")] [InlineData("Public", "dotnet_code_quality.api_surface = Private, Friend, Public")] [InlineData("Public", "dotnet_code_quality.api_surface = All")] [InlineData("Protected", "dotnet_code_quality.api_surface = Public")] [InlineData("Protected", "dotnet_code_quality.api_surface = Private, Friend, Public")] [InlineData("Protected", "dotnet_code_quality.api_surface = All")] [InlineData("Friend", "dotnet_code_quality.api_surface = Friend")] [InlineData("Friend", "dotnet_code_quality.api_surface = Private, Friend")] [InlineData("Friend", "dotnet_code_quality.api_surface = All")] [InlineData("Private", "dotnet_code_quality.api_surface = Private")] [InlineData("Private", "dotnet_code_quality.api_surface = Private, Public")] [InlineData("Private", "dotnet_code_quality.api_surface = All")] // Specific analyzer option [InlineData("Friend", "dotnet_code_quality.CA1040.api_surface = All")] [InlineData("Friend", "dotnet_code_quality.Design.api_surface = All")] // General + Specific analyzer option [InlineData("Friend", @"dotnet_code_quality.api_surface = Private dotnet_code_quality.CA1040.api_surface = All")] // Case-insensitive analyzer option [InlineData("Friend", "DOTNET_code_quality.CA1040.API_SURFACE = ALL")] // Invalid analyzer option ignored [InlineData("Friend", @"dotnet_code_quality.api_surface = All dotnet_code_quality.CA1040.api_surface_2 = Private")] public async Task TestBasicEmptyInterface_AnalyzerOptions_Diagnostic(string accessibility, string editorConfigText) { await new VerifyVB.Test { TestState = { Sources = { $@" Public Class C {accessibility} Interface I End Interface End Class" }, AdditionalFiles = { (".editorconfig", editorConfigText) } }, ExpectedDiagnostics = { CreateBasicResult(3, 16 + accessibility.Length), } }.RunAsync(); } [Theory] [InlineData("public", "dotnet_code_quality.api_surface = private")] [InlineData("public", "dotnet_code_quality.CA1040.api_surface = internal, private")] [InlineData("public", "dotnet_code_quality.Design.api_surface = internal, private")] [InlineData("public", @"dotnet_code_quality.api_surface = all dotnet_code_quality.CA1040.api_surface = private")] public async Task TestCSharpEmptyInterface_AnalyzerOptions_NoDiagnostic(string accessibility, string editorConfigText) { await new VerifyCS.Test { TestState = { Sources = { $@" public class C {{ {accessibility} interface I {{ }} }}" }, AdditionalFiles = { (".editorconfig", editorConfigText) } } }.RunAsync(); } [Theory] [InlineData("Public", "dotnet_code_quality.api_surface = Private")] [InlineData("Public", "dotnet_code_quality.CA1040.api_surface = Friend, Private")] [InlineData("Public", "dotnet_code_quality.Design.api_surface = Friend, Private")] [InlineData("Public", @"dotnet_code_quality.api_surface = All dotnet_code_quality.CA1040.api_surface = Private")] public async Task TestBasicEmptyInterface_AnalyzerOptions_NoDiagnostic(string accessibility, string editorConfigText) { await new VerifyVB.Test { TestState = { Sources = { $@" Public Class C {accessibility} Interface I End Interface End Class" }, AdditionalFiles = { (".editorconfig", editorConfigText) } } }.RunAsync(); } [Theory(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/3494")] [CombinatorialData] public async Task TestConflictingAnalyzerOptionsForPartials(bool hasConflict) { var csTest = new VerifyCS.Test { TestState = { Sources = { @"public partial interface I { }", @"public partial interface I { }", } }, SolutionTransforms = { ApplyTransform } }; if (!hasConflict) { csTest.ExpectedDiagnostics.Add(VerifyCS.Diagnostic().WithSpan(@"z:\folder1\Test0.cs", 1, 26, 1, 27).WithSpan(@"z:\folder2\Test1.cs", 1, 26, 1, 27)); } await csTest.RunAsync(); var vbTest = new VerifyVB.Test { TestState = { Sources = { @" Public Partial Interface I End Interface", @" Public Partial Interface I End Interface" }, }, SolutionTransforms = { ApplyTransform } }; if (!hasConflict) { vbTest.ExpectedDiagnostics.Add(VerifyVB.Diagnostic().WithSpan(@"z:\folder1\Test0.vb", 2, 26, 2, 27).WithSpan(@"z:\folder2\Test1.vb", 2, 26, 2, 27)); } await vbTest.RunAsync(); return; Solution ApplyTransform(Solution solution, ProjectId projectId) { var project = solution.GetProject(projectId)!; var projectFilePath = project.Language == LanguageNames.CSharp ? @"z:\Test.csproj" : @"z:\Test.vbproj"; solution = solution.WithProjectFilePath(projectId, projectFilePath); var documentExtension = project.Language == LanguageNames.CSharp ? "cs" : "vb"; var document1EditorConfig = $"[*.{documentExtension}]" + Environment.NewLine + "dotnet_code_quality.api_surface = public"; var document2OptionValue = hasConflict ? "internal" : "public"; var document2EditorConfig = $"[*.{documentExtension}]" + Environment.NewLine + $"dotnet_code_quality.api_surface = {document2OptionValue}"; var document1Folder = $@"z:\folder1"; solution = solution.WithDocumentFilePath(project.DocumentIds[0], $@"{document1Folder}\Test0.{documentExtension}"); solution = solution.GetProject(projectId)! .AddAnalyzerConfigDocument( ".editorconfig", SourceText.From(document1EditorConfig), filePath: $@"{document1Folder}\.editorconfig") .Project.Solution; var document2Folder = $@"z:\folder2"; solution = solution.WithDocumentFilePath(project.DocumentIds[1], $@"{document2Folder}\Test1.{documentExtension}"); return solution.GetProject(projectId)! .AddAnalyzerConfigDocument( ".editorconfig", SourceText.From(document2EditorConfig), filePath: $@"{document2Folder}\.editorconfig") .Project.Solution; } } private static DiagnosticResult CreateCSharpResult(int line, int col) => VerifyCS.Diagnostic() .WithLocation(line, col); private static DiagnosticResult CreateBasicResult(int line, int col) => VerifyVB.Diagnostic() .WithLocation(line, col); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #pragma warning disable 0420 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A lock-free, concurrent queue primitive, and its associated debugger view type. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Threading; namespace System.Collections.Concurrent { /// <summary> /// Represents a thread-safe first-in, first-out collection of objects. /// </summary> /// <typeparam name="T">Specifies the type of elements in the queue.</typeparam> /// <remarks> /// All public and protected members of <see cref="ConcurrentQueue{T}"/> are thread-safe and may be used /// concurrently from multiple threads. /// </remarks> [ComVisible(false)] [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))] [HostProtection(Synchronization = true, ExternalThreading = true)] [Serializable] public class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T> { //fields of ConcurrentQueue [NonSerialized] private volatile Segment m_head; [NonSerialized] private volatile Segment m_tail; private T[] m_serializationArray; // Used for custom serialization. private const int SEGMENT_SIZE = 32; //number of snapshot takers, GetEnumerator(), ToList() and ToArray() operations take snapshot. [NonSerialized] internal volatile int m_numSnapshotTakers = 0; /// <summary> /// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class. /// </summary> public ConcurrentQueue() { m_head = m_tail = new Segment(0, this); } /// <summary> /// Initializes the contents of the queue from an existing collection. /// </summary> /// <param name="collection">A collection from which to copy elements.</param> private void InitializeFromCollection(IEnumerable<T> collection) { Segment localTail = new Segment(0, this);//use this local variable to avoid the extra volatile read/write. this is safe because it is only called from ctor m_head = localTail; int index = 0; foreach (T element in collection) { Contract.Assert(index >= 0 && index < SEGMENT_SIZE); localTail.UnsafeAdd(element); index++; if (index >= SEGMENT_SIZE) { localTail = localTail.UnsafeGrow(); index = 0; } } m_tail = localTail; } /// <summary> /// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> /// class that contains elements copied from the specified collection /// </summary> /// <param name="collection">The collection whose elements are copied to the new <see /// cref="ConcurrentQueue{T}"/>.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is /// null.</exception> public ConcurrentQueue(IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException("collection"); } InitializeFromCollection(collection); } /// <summary> /// Get the data array to be serialized /// </summary> [OnSerializing] private void OnSerializing(StreamingContext context) { // save the data into the serialization array to be saved m_serializationArray = ToArray(); } /// <summary> /// Construct the queue from a previously seiralized one /// </summary> [OnDeserialized] private void OnDeserialized(StreamingContext context) { Contract.Assert(m_serializationArray != null); InitializeFromCollection(m_serializationArray); m_serializationArray = null; } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see /// cref="T:System.Array"/>, starting at a particular /// <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the /// destination of the elements copied from the /// <see cref="T:System.Collections.Concurrent.ConcurrentBag"/>. The <see /// cref="T:System.Array">Array</see> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"> /// <paramref name="array"/> is multidimensional. -or- /// <paramref name="array"/> does not have zero-based indexing. -or- /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is /// greater than the available space from <paramref name="index"/> to the end of the destination /// <paramref name="array"/>. -or- The type of the source <see /// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the /// destination <paramref name="array"/>. /// </exception> void ICollection.CopyTo(Array array, int index) { // Validate arguments. if (array == null) { throw new ArgumentNullException("array"); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ((ICollection)ToList()).CopyTo(array, index); } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is /// synchronized with the SyncRoot. /// </summary> /// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized /// with the SyncRoot; otherwise, false. For <see cref="ConcurrentQueue{T}"/>, this property always /// returns false.</value> bool ICollection.IsSynchronized { // Gets a value indicating whether access to this collection is synchronized. Always returns // false. The reason is subtle. While access is in face thread safe, it's not the case that // locking on the SyncRoot would have prevented concurrent pushes and pops, as this property // would typically indicate; that's because we internally use CAS operations vs. true locks. get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see /// cref="T:System.Collections.ICollection"/>. This property is not supported. /// </summary> /// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported.</exception> object ICollection.SyncRoot { get { throw new NotSupportedException(Environment.GetResourceString("ConcurrentCollection_SyncRoot_NotSupported")); } } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<T>)this).GetEnumerator(); } /// <summary> /// Attempts to add an object to the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null /// reference (Nothing in Visual Basic) for reference types. /// </param> /// <returns>true if the object was added successfully; otherwise, false.</returns> /// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will always add the object to the /// end of the <see cref="ConcurrentQueue{T}"/> /// and return true.</remarks> bool IProducerConsumerCollection<T>.TryAdd(T item) { Enqueue(item); return true; } /// <summary> /// Attempts to remove and return an object from the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item"> /// When this method returns, if the operation was successful, <paramref name="item"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned succesfully; otherwise, false.</returns> /// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will attempt to remove the object /// from the beginning of the <see cref="ConcurrentQueue{T}"/>. /// </remarks> bool IProducerConsumerCollection<T>.TryTake(out T item) { return TryDequeue(out item); } /// <summary> /// Gets a value that indicates whether the <see cref="ConcurrentQueue{T}"/> is empty. /// </summary> /// <value>true if the <see cref="ConcurrentQueue{T}"/> is empty; otherwise, false.</value> /// <remarks> /// For determining whether the collection contains any items, use of this property is recommended /// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it /// to 0. However, as this collection is intended to be accessed concurrently, it may be the case /// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating /// the result. /// </remarks> public bool IsEmpty { get { Segment head = m_head; if (!head.IsEmpty) //fast route 1: //if current head is not empty, then queue is not empty return false; else if (head.Next == null) //fast route 2: //if current head is empty and it's the last segment //then queue is empty return true; else //slow route: //current head is empty and it is NOT the last segment, //it means another thread is growing new segment { SpinWait spin = new SpinWait(); while (head.IsEmpty) { if (head.Next == null) return true; spin.SpinOnce(); head = m_head; } return false; } } } /// <summary> /// Copies the elements stored in the <see cref="ConcurrentQueue{T}"/> to a new array. /// </summary> /// <returns>A new array containing a snapshot of elements copied from the <see /// cref="ConcurrentQueue{T}"/>.</returns> public T[] ToArray() { return ToList().ToArray(); } /// <summary> /// Copies the <see cref="ConcurrentQueue{T}"/> elements to a new <see /// cref="T:System.Collections.Generic.List{T}"/>. /// </summary> /// <returns>A new <see cref="T:System.Collections.Generic.List{T}"/> containing a snapshot of /// elements copied from the <see cref="ConcurrentQueue{T}"/>.</returns> private List<T> ToList() { // Increments the number of active snapshot takers. This increment must happen before the snapshot is // taken. At the same time, Decrement must happen after list copying is over. Only in this way, can it // eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0. Interlocked.Increment(ref m_numSnapshotTakers); List<T> list = new List<T>(); try { //store head and tail positions in buffer, Segment head, tail; int headLow, tailHigh; GetHeadTailPositions(out head, out tail, out headLow, out tailHigh); if (head == tail) { head.AddToList(list, headLow, tailHigh); } else { head.AddToList(list, headLow, SEGMENT_SIZE - 1); Segment curr = head.Next; while (curr != tail) { curr.AddToList(list, 0, SEGMENT_SIZE - 1); curr = curr.Next; } //Add tail segment tail.AddToList(list, 0, tailHigh); } } finally { // This Decrement must happen after copying is over. Interlocked.Decrement(ref m_numSnapshotTakers); } return list; } /// <summary> /// Store the position of the current head and tail positions. /// </summary> /// <param name="head">return the head segment</param> /// <param name="tail">return the tail segment</param> /// <param name="headLow">return the head offset, value range [0, SEGMENT_SIZE]</param> /// <param name="tailHigh">return the tail offset, value range [-1, SEGMENT_SIZE-1]</param> private void GetHeadTailPositions(out Segment head, out Segment tail, out int headLow, out int tailHigh) { head = m_head; tail = m_tail; headLow = head.Low; tailHigh = tail.High; SpinWait spin = new SpinWait(); //we loop until the observed values are stable and sensible. //This ensures that any update order by other methods can be tolerated. while ( //if head and tail changed, retry head != m_head || tail != m_tail //if low and high pointers, retry || headLow != head.Low || tailHigh != tail.High //if head jumps ahead of tail because of concurrent grow and dequeue, retry || head.m_index > tail.m_index) { spin.SpinOnce(); head = m_head; tail = m_tail; headLow = head.Low; tailHigh = tail.High; } } /// <summary> /// Gets the number of elements contained in the <see cref="ConcurrentQueue{T}"/>. /// </summary> /// <value>The number of elements contained in the <see cref="ConcurrentQueue{T}"/>.</value> /// <remarks> /// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/> /// property is recommended rather than retrieving the number of items from the <see cref="Count"/> /// property and comparing it to 0. /// </remarks> public int Count { get { //store head and tail positions in buffer, Segment head, tail; int headLow, tailHigh; GetHeadTailPositions(out head, out tail, out headLow, out tailHigh); if (head == tail) { return tailHigh - headLow + 1; } //head segment int count = SEGMENT_SIZE - headLow; //middle segment(s), if any, are full. //We don't deal with overflow to be consistent with the behavior of generic types in CLR. count += SEGMENT_SIZE * ((int)(tail.m_index - head.m_index - 1)); //tail segment count += tailHigh + 1; return count; } } /// <summary> /// Copies the <see cref="ConcurrentQueue{T}"/> elements to an existing one-dimensional <see /// cref="T:System.Array">Array</see>, starting at the specified array index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the /// destination of the elements copied from the /// <see cref="ConcurrentQueue{T}"/>. The <see cref="T:System.Array">Array</see> must have zero-based /// indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the /// length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="ConcurrentQueue{T}"/> is greater than the /// available space from <paramref name="index"/> to the end of the destination <paramref /// name="array"/>. /// </exception> public void CopyTo(T[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ToList().CopyTo(array, index); } /// <summary> /// Returns an enumerator that iterates through the <see /// cref="ConcurrentQueue{T}"/>. /// </summary> /// <returns>An enumerator for the contents of the <see /// cref="ConcurrentQueue{T}"/>.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents /// of the queue. It does not reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use /// concurrently with reads from and writes to the queue. /// </remarks> public IEnumerator<T> GetEnumerator() { // Increments the number of active snapshot takers. This increment must happen before the snapshot is // taken. At the same time, Decrement must happen after the enumeration is over. Only in this way, can it // eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0. Interlocked.Increment(ref m_numSnapshotTakers); // Takes a snapshot of the queue. // A design flaw here: if a Thread.Abort() happens, we cannot decrement m_numSnapshotTakers. But we cannot // wrap the following with a try/finally block, otherwise the decrement will happen before the yield return // statements in the GetEnumerator (head, tail, headLow, tailHigh) method. Segment head, tail; int headLow, tailHigh; GetHeadTailPositions(out head, out tail, out headLow, out tailHigh); //If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of // the queue is not taken when GetEnumerator is initialized but when MoveNext() is first called. // This is inconsistent with existing generic collections. In order to prevent it, we capture the // value of m_head in a buffer and call out to a helper method. //The old way of doing this was to return the ToList().GetEnumerator(), but ToList() was an // unnecessary perfomance hit. return GetEnumerator(head, tail, headLow, tailHigh); } /// <summary> /// Helper method of GetEnumerator to seperate out yield return statement, and prevent lazy evaluation. /// </summary> private IEnumerator<T> GetEnumerator(Segment head, Segment tail, int headLow, int tailHigh) { try { SpinWait spin = new SpinWait(); if (head == tail) { for (int i = headLow; i <= tailHigh; i++) { // If the position is reserved by an Enqueue operation, but the value is not written into, // spin until the value is available. spin.Reset(); while (!head.m_state[i].m_value) { spin.SpinOnce(); } yield return head.m_array[i]; } } else { //iterate on head segment for (int i = headLow; i < SEGMENT_SIZE; i++) { // If the position is reserved by an Enqueue operation, but the value is not written into, // spin until the value is available. spin.Reset(); while (!head.m_state[i].m_value) { spin.SpinOnce(); } yield return head.m_array[i]; } //iterate on middle segments Segment curr = head.Next; while (curr != tail) { for (int i = 0; i < SEGMENT_SIZE; i++) { // If the position is reserved by an Enqueue operation, but the value is not written into, // spin until the value is available. spin.Reset(); while (!curr.m_state[i].m_value) { spin.SpinOnce(); } yield return curr.m_array[i]; } curr = curr.Next; } //iterate on tail segment for (int i = 0; i <= tailHigh; i++) { // If the position is reserved by an Enqueue operation, but the value is not written into, // spin until the value is available. spin.Reset(); while (!tail.m_state[i].m_value) { spin.SpinOnce(); } yield return tail.m_array[i]; } } } finally { // This Decrement must happen after the enumeration is over. Interlocked.Decrement(ref m_numSnapshotTakers); } } /// <summary> /// Adds an object to the end of the <see cref="ConcurrentQueue{T}"/>. /// </summary> /// <param name="item">The object to add to the end of the <see /// cref="ConcurrentQueue{T}"/>. The value can be a null reference /// (Nothing in Visual Basic) for reference types. /// </param> public void Enqueue(T item) { SpinWait spin = new SpinWait(); while (true) { Segment tail = m_tail; if (tail.TryAppend(item)) return; spin.SpinOnce(); } } /// <summary> /// Attempts to remove and return the object at the beginning of the <see /// cref="ConcurrentQueue{T}"/>. /// </summary> /// <param name="result"> /// When this method returns, if the operation was successful, <paramref name="result"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned from the beggining of the <see /// cref="ConcurrentQueue{T}"/> /// succesfully; otherwise, false.</returns> public bool TryDequeue(out T result) { while (!IsEmpty) { Segment head = m_head; if (head.TryRemove(out result)) return true; //since method IsEmpty spins, we don't need to spin in the while loop } result = default(T); return false; } /// <summary> /// Attempts to return an object from the beginning of the <see cref="ConcurrentQueue{T}"/> /// without removing it. /// </summary> /// <param name="result">When this method returns, <paramref name="result"/> contains an object from /// the beginning of the <see cref="T:System.Collections.Concurrent.ConccurrentQueue{T}"/> or an /// unspecified value if the operation failed.</param> /// <returns>true if and object was returned successfully; otherwise, false.</returns> public bool TryPeek(out T result) { Interlocked.Increment(ref m_numSnapshotTakers); while (!IsEmpty) { Segment head = m_head; if (head.TryPeek(out result)) { Interlocked.Decrement(ref m_numSnapshotTakers); return true; } //since method IsEmpty spins, we don't need to spin in the while loop } result = default(T); Interlocked.Decrement(ref m_numSnapshotTakers); return false; } /// <summary> /// private class for ConcurrentQueue. /// a queue is a linked list of small arrays, each node is called a segment. /// A segment contains an array, a pointer to the next segment, and m_low, m_high indices recording /// the first and last valid elements of the array. /// </summary> private class Segment { //we define two volatile arrays: m_array and m_state. Note that the accesses to the array items //do not get volatile treatment. But we don't need to worry about loading adjacent elements or //store/load on adjacent elements would suffer reordering. // - Two stores: these are at risk, but CLRv2 memory model guarantees store-release hence we are safe. // - Two loads: because one item from two volatile arrays are accessed, the loads of the array references // are sufficient to prevent reordering of the loads of the elements. internal volatile T[] m_array; // For each entry in m_array, the corresponding entry in m_state indicates whether this position contains // a valid value. m_state is initially all false. internal volatile VolatileBool[] m_state; //pointer to the next segment. null if the current segment is the last segment private volatile Segment m_next; //We use this zero based index to track how many segments have been created for the queue, and //to compute how many active segments are there currently. // * The number of currently active segments is : m_tail.m_index - m_head.m_index + 1; // * m_index is incremented with every Segment.Grow operation. We use Int64 type, and we can safely // assume that it never overflows. To overflow, we need to do 2^63 increments, even at a rate of 4 // billion (2^32) increments per second, it takes 2^31 seconds, which is about 64 years. internal readonly long m_index; //indices of where the first and last valid values // - m_low points to the position of the next element to pop from this segment, range [0, infinity) // m_low >= SEGMENT_SIZE implies the segment is disposable // - m_high points to the position of the latest pushed element, range [-1, infinity) // m_high == -1 implies the segment is new and empty // m_high >= SEGMENT_SIZE-1 means this segment is ready to grow. // and the thread who sets m_high to SEGMENT_SIZE-1 is responsible to grow the segment // - Math.Min(m_low, SEGMENT_SIZE) > Math.Min(m_high, SEGMENT_SIZE-1) implies segment is empty // - initially m_low =0 and m_high=-1; private volatile int m_low; private volatile int m_high; private volatile ConcurrentQueue<T> m_source; /// <summary> /// Create and initialize a segment with the specified index. /// </summary> internal Segment(long index, ConcurrentQueue<T> source) { m_array = new T[SEGMENT_SIZE]; m_state = new VolatileBool[SEGMENT_SIZE]; //all initialized to false m_high = -1; Contract.Assert(index >= 0); m_index = index; m_source = source; } /// <summary> /// return the next segment /// </summary> internal Segment Next { get { return m_next; } } /// <summary> /// return true if the current segment is empty (doesn't have any element available to dequeue, /// false otherwise /// </summary> internal bool IsEmpty { get { return (Low > High); } } /// <summary> /// Add an element to the tail of the current segment /// exclusively called by ConcurrentQueue.InitializedFromCollection /// InitializeFromCollection is responsible to guaratee that there is no index overflow, /// and there is no contention /// </summary> /// <param name="value"></param> internal void UnsafeAdd(T value) { Contract.Assert(m_high < SEGMENT_SIZE - 1); m_high++; m_array[m_high] = value; m_state[m_high].m_value = true; } /// <summary> /// Create a new segment and append to the current one /// Does not update the m_tail pointer /// exclusively called by ConcurrentQueue.InitializedFromCollection /// InitializeFromCollection is responsible to guaratee that there is no index overflow, /// and there is no contention /// </summary> /// <returns>the reference to the new Segment</returns> internal Segment UnsafeGrow() { Contract.Assert(m_high >= SEGMENT_SIZE - 1); Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow m_next = newSegment; return newSegment; } /// <summary> /// Create a new segment and append to the current one /// Update the m_tail pointer /// This method is called when there is no contention /// </summary> internal void Grow() { //no CAS is needed, since there is no contention (other threads are blocked, busy waiting) Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow m_next = newSegment; Contract.Assert(m_source.m_tail == this); m_source.m_tail = m_next; } /// <summary> /// Try to append an element at the end of this segment. /// </summary> /// <param name="value">the element to append</param> /// <param name="tail">The tail.</param> /// <returns>true if the element is appended, false if the current segment is full</returns> /// <remarks>if appending the specified element succeeds, and after which the segment is full, /// then grow the segment</remarks> internal bool TryAppend(T value) { //quickly check if m_high is already over the boundary, if so, bail out if (m_high >= SEGMENT_SIZE - 1) { return false; } //Now we will use a CAS to increment m_high, and store the result in newhigh. //Depending on how many free spots left in this segment and how many threads are doing this Increment //at this time, the returning "newhigh" can be // 1) < SEGMENT_SIZE - 1 : we took a spot in this segment, and not the last one, just insert the value // 2) == SEGMENT_SIZE - 1 : we took the last spot, insert the value AND grow the segment // 3) > SEGMENT_SIZE - 1 : we failed to reserve a spot in this segment, we return false to // Queue.Enqueue method, telling it to try again in the next segment. int newhigh = SEGMENT_SIZE; //initial value set to be over the boundary //We need do Interlocked.Increment and value/state update in a finally block to ensure that they run //without interuption. This is to prevent anything from happening between them, and another dequeue //thread maybe spinning forever to wait for m_state[] to be true; try { } finally { newhigh = Interlocked.Increment(ref m_high); if (newhigh <= SEGMENT_SIZE - 1) { m_array[newhigh] = value; m_state[newhigh].m_value = true; } //if this thread takes up the last slot in the segment, then this thread is responsible //to grow a new segment. Calling Grow must be in the finally block too for reliability reason: //if thread abort during Grow, other threads will be left busy spinning forever. if (newhigh == SEGMENT_SIZE - 1) { Grow(); } } //if newhigh <= SEGMENT_SIZE-1, it means the current thread successfully takes up a spot return newhigh <= SEGMENT_SIZE - 1; } /// <summary> /// try to remove an element from the head of current segment /// </summary> /// <param name="result">The result.</param> /// <param name="head">The head.</param> /// <returns>return false only if the current segment is empty</returns> internal bool TryRemove(out T result) { SpinWait spin = new SpinWait(); int lowLocal = Low, highLocal = High; while (lowLocal <= highLocal) { //try to update m_low if (Interlocked.CompareExchange(ref m_low, lowLocal + 1, lowLocal) == lowLocal) { //if the specified value is not available (this spot is taken by a push operation, // but the value is not written into yet), then spin SpinWait spinLocal = new SpinWait(); while (!m_state[lowLocal].m_value) { spinLocal.SpinOnce(); } result = m_array[lowLocal]; // If there is no other thread taking snapshot (GetEnumerator(), ToList(), etc), reset the deleted entry to null. // It is ok if after this conditional check m_numSnapshotTakers becomes > 0, because new snapshots won't include // the deleted entry at m_array[lowLocal]. if (m_source.m_numSnapshotTakers <= 0) { m_array[lowLocal] = default(T); //release the reference to the object. } //if the current thread sets m_low to SEGMENT_SIZE, which means the current segment becomes //disposable, then this thread is responsible to dispose this segment, and reset m_head if (lowLocal + 1 >= SEGMENT_SIZE) { // Invariant: we only dispose the current m_head, not any other segment // In usual situation, disposing a segment is simply seting m_head to m_head.m_next // But there is one special case, where m_head and m_tail points to the same and ONLY //segment of the queue: Another thread A is doing Enqueue and finds that it needs to grow, //while the *current* thread is doing *this* Dequeue operation, and finds that it needs to //dispose the current (and ONLY) segment. Then we need to wait till thread A finishes its //Grow operation, this is the reason of having the following while loop spinLocal = new SpinWait(); while (m_next == null) { spinLocal.SpinOnce(); } Contract.Assert(m_source.m_head == this); m_source.m_head = m_next; } return true; } else { //CAS failed due to contention: spin briefly and retry spin.SpinOnce(); lowLocal = Low; highLocal = High; } }//end of while result = default(T); return false; } /// <summary> /// try to peek the current segment /// </summary> /// <param name="result">holds the return value of the element at the head position, /// value set to default(T) if there is no such an element</param> /// <returns>true if there are elements in the current segment, false otherwise</returns> internal bool TryPeek(out T result) { result = default(T); int lowLocal = Low; if (lowLocal > High) return false; SpinWait spin = new SpinWait(); while (!m_state[lowLocal].m_value) { spin.SpinOnce(); } result = m_array[lowLocal]; return true; } /// <summary> /// Adds part or all of the current segment into a List. /// </summary> /// <param name="list">the list to which to add</param> /// <param name="start">the start position</param> /// <param name="end">the end position</param> internal void AddToList(List<T> list, int start, int end) { for (int i = start; i <= end; i++) { SpinWait spin = new SpinWait(); while (!m_state[i].m_value) { spin.SpinOnce(); } list.Add(m_array[i]); } } /// <summary> /// return the position of the head of the current segment /// Value range [0, SEGMENT_SIZE], if it's SEGMENT_SIZE, it means this segment is exhausted and thus empty /// </summary> internal int Low { get { return Math.Min(m_low, SEGMENT_SIZE); } } /// <summary> /// return the logical position of the tail of the current segment /// Value range [-1, SEGMENT_SIZE-1]. When it's -1, it means this is a new segment and has no elemnet yet /// </summary> internal int High { get { //if m_high > SEGMENT_SIZE, it means it's out of range, we should return //SEGMENT_SIZE-1 as the logical position return Math.Min(m_high, SEGMENT_SIZE - 1); } } } }//end of class Segment /// <summary> /// A wrapper struct for volatile bool, please note the copy of the struct it self will not be volatile /// for example this statement will not include in volatilness operation volatileBool1 = volatileBool2 the jit will copy the struct and will ignore the volatile /// </summary> struct VolatileBool { public VolatileBool(bool value) { m_value = value; } public volatile bool m_value; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Bookshelf.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Runtime.InteropServices; using System.Security; using BulletSharp.Math; using AOT; namespace BulletSharp { [Flags] public enum ContactPointFlags { None = 0, LateralFrictionInitialized = 1, HasContactCfm = 2, HasContactErp = 4 } public delegate void ContactAddedEventHandler(ManifoldPoint cp, CollisionObjectWrapper colObj0Wrap, int partId0, int index0, CollisionObjectWrapper colObj1Wrap, int partId1, int index1); public class ManifoldPoint : IDisposable { internal IntPtr _native; bool _preventDelete; static ContactAddedEventHandler _contactAdded; static ContactAddedUnmanagedDelegate _contactAddedUnmanaged; static IntPtr _contactAddedUnmanagedPtr; [UnmanagedFunctionPointer(Native.Conv), SuppressUnmanagedCodeSecurity] private delegate bool ContactAddedUnmanagedDelegate(IntPtr cp, IntPtr colObj0Wrap, int partId0, int index0, IntPtr colObj1Wrap, int partId1, int index1); [MonoPInvokeCallback(typeof(ContactAddedUnmanagedDelegate))] static bool ContactAddedUnmanaged(IntPtr cp, IntPtr colObj0Wrap, int partId0, int index0, IntPtr colObj1Wrap, int partId1, int index1) { _contactAdded.Invoke(new ManifoldPoint(cp, true), new CollisionObjectWrapper(colObj0Wrap), partId0, index0, new CollisionObjectWrapper(colObj1Wrap), partId1, index1); return false; } public static event ContactAddedEventHandler ContactAdded { add { if (_contactAddedUnmanaged == null) { _contactAddedUnmanaged = new ContactAddedUnmanagedDelegate(ContactAddedUnmanaged); _contactAddedUnmanagedPtr = Marshal.GetFunctionPointerForDelegate(_contactAddedUnmanaged); } setGContactAddedCallback(_contactAddedUnmanagedPtr); _contactAdded += value; } remove { _contactAdded -= value; if (_contactAdded == null) { setGContactAddedCallback(IntPtr.Zero); } } } internal ManifoldPoint(IntPtr native, bool preventDelete) { _native = native; _preventDelete = preventDelete; } public ManifoldPoint() { _native = btManifoldPoint_new(); } public ManifoldPoint(Vector3 pointA, Vector3 pointB, Vector3 normal, float distance) { _native = btManifoldPoint_new2(ref pointA, ref pointB, ref normal, distance); } public float AppliedImpulse { get { return btManifoldPoint_getAppliedImpulse(_native); } set { btManifoldPoint_setAppliedImpulse(_native, value); } } public float AppliedImpulseLateral1 { get { return btManifoldPoint_getAppliedImpulseLateral1(_native); } set { btManifoldPoint_setAppliedImpulseLateral1(_native, value); } } public float AppliedImpulseLateral2 { get { return btManifoldPoint_getAppliedImpulseLateral2(_native); } set { btManifoldPoint_setAppliedImpulseLateral2(_native, value); } } public float CombinedFriction { get { return btManifoldPoint_getCombinedFriction(_native); } set { btManifoldPoint_setCombinedFriction(_native, value); } } public float CombinedRestitution { get { return btManifoldPoint_getCombinedRestitution(_native); } set { btManifoldPoint_setCombinedRestitution(_native, value); } } public float CombinedRollingFriction { get { return btManifoldPoint_getCombinedRollingFriction(_native); } set { btManifoldPoint_setCombinedRollingFriction(_native, value); } } public float ContactCfm { get { return btManifoldPoint_getContactCFM(_native); } set { btManifoldPoint_setContactCFM(_native, value); } } public float ContactErp { get { return btManifoldPoint_getContactERP(_native); } set { btManifoldPoint_setContactERP(_native, value); } } public float ContactMotion1 { get { return btManifoldPoint_getContactMotion1(_native); } set { btManifoldPoint_setContactMotion1(_native, value); } } public float ContactMotion2 { get { return btManifoldPoint_getContactMotion2(_native); } set { btManifoldPoint_setContactMotion2(_native, value); } } public ContactPointFlags ContactPointFlags { get { return btManifoldPoint_getContactPointFlags(_native); } set { btManifoldPoint_setContactPointFlags(_native, value); } } public float Distance { get { return btManifoldPoint_getDistance(_native); } set { btManifoldPoint_setDistance(_native, value); } } public float Distance1 { get { return btManifoldPoint_getDistance1(_native); } set { btManifoldPoint_setDistance1(_native, value); } } public float FrictionCfm { get { return btManifoldPoint_getFrictionCFM(_native); } set { btManifoldPoint_setFrictionCFM(_native, value); } } public int Index0 { get { return btManifoldPoint_getIndex0(_native); } set { btManifoldPoint_setIndex0(_native, value); } } public int Index1 { get { return btManifoldPoint_getIndex1(_native); } set { btManifoldPoint_setIndex1(_native, value); } } public Vector3 LateralFrictionDir1 { get { Vector3 value; btManifoldPoint_getLateralFrictionDir1(_native, out value); return value; } set { btManifoldPoint_setLateralFrictionDir1(_native, ref value); } } public Vector3 LateralFrictionDir2 { get { Vector3 value; btManifoldPoint_getLateralFrictionDir2(_native, out value); return value; } set { btManifoldPoint_setLateralFrictionDir2(_native, ref value); } } public int LifeTime { get { return btManifoldPoint_getLifeTime(_native); } set { btManifoldPoint_setLifeTime(_native, value); } } public Vector3 LocalPointA { get { Vector3 value; btManifoldPoint_getLocalPointA(_native, out value); return value; } set { btManifoldPoint_setLocalPointA(_native, ref value); } } public Vector3 LocalPointB { get { Vector3 value; btManifoldPoint_getLocalPointB(_native, out value); return value; } set { btManifoldPoint_setLocalPointB(_native, ref value); } } public Vector3 NormalWorldOnB { get { Vector3 value; btManifoldPoint_getNormalWorldOnB(_native, out value); return value; } set { btManifoldPoint_setNormalWorldOnB(_native, ref value); } } public int PartId0 { get { return btManifoldPoint_getPartId0(_native); } set { btManifoldPoint_setPartId0(_native, value); } } public int PartId1 { get { return btManifoldPoint_getPartId1(_native); } set { btManifoldPoint_setPartId1(_native, value); } } public Vector3 PositionWorldOnA { get { Vector3 value; btManifoldPoint_getPositionWorldOnA(_native, out value); return value; } set { btManifoldPoint_setPositionWorldOnA(_native, ref value); } } public Vector3 PositionWorldOnB { get { Vector3 value; btManifoldPoint_getPositionWorldOnB(_native, out value); return value; } set { btManifoldPoint_setPositionWorldOnB(_native, ref value); } } public Object UserPersistentData { get { IntPtr valuePtr = btManifoldPoint_getUserPersistentData(_native); return (valuePtr != IntPtr.Zero) ? GCHandle.FromIntPtr(valuePtr).Target : null; } set { IntPtr prevPtr = btManifoldPoint_getUserPersistentData(_native); if (prevPtr != IntPtr.Zero) { GCHandle prevHandle = GCHandle.FromIntPtr(prevPtr); if (ReferenceEquals(value, prevHandle.Target)) { return; } prevHandle.Free(); } if (value != null) { GCHandle handle = GCHandle.Alloc(value); btManifoldPoint_setUserPersistentData(_native, GCHandle.ToIntPtr(handle)); } else { btManifoldPoint_setUserPersistentData(_native, IntPtr.Zero); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { if (!_preventDelete) { btManifoldPoint_delete(_native); } _native = IntPtr.Zero; } } ~ManifoldPoint() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btManifoldPoint_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btManifoldPoint_new2([In] ref Vector3 pointA, [In] ref Vector3 pointB, [In] ref Vector3 normal, float distance); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btManifoldPoint_getAppliedImpulse(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btManifoldPoint_getAppliedImpulseLateral1(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btManifoldPoint_getAppliedImpulseLateral2(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btManifoldPoint_getCombinedFriction(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btManifoldPoint_getCombinedRestitution(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btManifoldPoint_getCombinedRollingFriction(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btManifoldPoint_getContactCFM(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btManifoldPoint_getContactERP(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btManifoldPoint_getContactMotion1(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btManifoldPoint_getContactMotion2(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern ContactPointFlags btManifoldPoint_getContactPointFlags(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btManifoldPoint_getDistance(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btManifoldPoint_getDistance1(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btManifoldPoint_getFrictionCFM(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btManifoldPoint_getIndex0(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btManifoldPoint_getIndex1(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_getLateralFrictionDir1(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_getLateralFrictionDir2(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btManifoldPoint_getLifeTime(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_getLocalPointA(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_getLocalPointB(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_getNormalWorldOnB(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btManifoldPoint_getPartId0(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btManifoldPoint_getPartId1(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_getPositionWorldOnA(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_getPositionWorldOnB(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btManifoldPoint_getUserPersistentData(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setAppliedImpulse(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setAppliedImpulseLateral1(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setAppliedImpulseLateral2(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setCombinedFriction(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setCombinedRestitution(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setCombinedRollingFriction(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setContactCFM(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setContactERP(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setContactMotion1(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setContactMotion2(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setContactPointFlags(IntPtr obj, ContactPointFlags value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setDistance(IntPtr obj, float dist); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setDistance1(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setFrictionCFM(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setIndex0(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setIndex1(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setLateralFrictionDir1(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setLateralFrictionDir2(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setLifeTime(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setLocalPointA(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setLocalPointB(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setNormalWorldOnB(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setPartId0(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setPartId1(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setPositionWorldOnA(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setPositionWorldOnB(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_setUserPersistentData(IntPtr obj, IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btManifoldPoint_delete(IntPtr obj); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern IntPtr getGContactAddedCallback(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void setGContactAddedCallback(IntPtr value); } }
// ImageListView - A listview control for image files // Copyright (C) 2009 Ozgur Ozcitak // // 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. // // Ozgur Ozcitak (ozcitak@yahoo.com) // // Theme support coded by Robby using System.ComponentModel; using System.Drawing; namespace Manina.Windows.Forms { /// <summary> /// Represents the color palette of the image list view. /// </summary> public class ImageListViewColor { #region Member Variables Color mControlBackColor; Color mBackColor; Color mBorderColor; Color mUnFocusedColor1; Color mUnFocusedColor2; Color mUnFocusedBorderColor; Color mForeColor; Color mHoverColor1; Color mHoverColor2; Color mHoverBorderColor; Color mInsertionCaretColor; Color mSelectedColor1; Color mSelectedColor2; Color mSelectedBorderColor; // thumbnail & pane Color mImageInnerBorderColor; Color mImageOuterBorderColor; // details view Color mCellForeColor; Color mColumnHeaderBackColor1; Color mColumnHeaderBackColor2; Color mColumnHeaderForeColor; Color mColumnHeaderHoverColor1; Color mColumnHeaderHoverColor2; Color mColumnSelectColor; Color mColumnSeparatorColor; // pane Color mPaneBackColor; Color mPaneSeparatorColor; Color mPaneLabelColor; // selection rectangle Color mSelectionRectangleColor1; Color mSelectionRectangleColor2; Color mSelectionRectangleBorderColor; #endregion #region Properties /// <summary> /// Gets or sets the background color of the ImageListView control. /// </summary> [Category("Appearance"), Description("Gets or sets the background color of the ImageListView control.")] public Color ControlBackColor { get { return mControlBackColor; } set { mControlBackColor = value; } } /// <summary> /// Gets or sets the background color of the ImageListViewItem. /// </summary> [Category("Appearance"), Description("Gets or sets the background color of the ImageListViewItem.")] public Color BackColor { get { return mBackColor; } set { mBackColor = value; } } /// <summary> /// Gets or sets the border color of the ImageListViewItem. /// </summary> [Category("Appearance"), Description("Gets or sets the border color of the ImageListViewItem.")] public Color BorderColor { get { return mBorderColor; } set { mBorderColor = value; } } /// <summary> /// Gets or sets the foreground color of the ImageListViewItem. /// </summary> [Category("Appearance"), Description("Gets or sets the foreground color of the ImageListViewItem.")] public Color ForeColor { get { return mForeColor; } set { mForeColor = value; } } /// <summary> /// Gets or sets the background gradient color1 of the ImageListViewItem if the control is not focused. /// </summary> [Category("Appearance"), Description("Gets or sets the background gradient color1 of the ImageListViewItem if the control is not focused.")] public Color UnFocusedColor1 { get { return mUnFocusedColor1; } set { mUnFocusedColor1 = value; } } /// <summary> /// Gets or sets the background gradient color2 of the ImageListViewItem if the control is not focused. /// </summary> [Category("Appearance"), Description("Gets or sets the background gradient color2 of the ImageListViewItem if the control is not focused.")] public Color UnFocusedColor2 { get { return mUnFocusedColor2; } set { mUnFocusedColor1 = value; } } /// <summary> /// Gets or sets the border color of the ImageListViewItem if the control is not focused. /// </summary> [Category("Appearance"), Description("Gets or sets the border color of the ImageListViewItem if the control is not focused.")] public Color UnFocusedBorderColor { get { return mUnFocusedBorderColor; } set { mUnFocusedBorderColor = value; } } /// <summary> /// Gets or sets the background gradient color1 if the ImageListViewItem is hovered. /// </summary> [Category("Appearance"), Description("Gets or sets the background gradient color1 if the ImageListViewItem is hovered.")] public Color HoverColor1 { get { return mHoverColor1; } set { mHoverColor1 = value; } } /// <summary> /// Gets or sets the background gradient color2 if the ImageListViewItem is hovered. /// </summary> [Category("Appearance"), Description("Gets or sets the background gradient color2 if the ImageListViewItem is hovered.")] public Color HoverColor2 { get { return mHoverColor2; } set { mHoverColor2 = value; } } /// <summary> /// Gets or sets the border color of the ImageListViewItem if the item is hovered. /// </summary> [Category("Appearance"), Description("Gets or sets the border color of the ImageListViewItem if the item is hovered.")] public Color HoverBorderColor { get { return mHoverBorderColor; } set { mHoverBorderColor = value; } } /// <summary> /// Gets or sets the color of the insertion caret. /// </summary> [Category("Appearance"), Description("Gets or sets the color of the insertion caret.")] public Color InsertionCaretColor { get { return mInsertionCaretColor; } set { mInsertionCaretColor = value; } } /// <summary> /// Gets or sets the background gradient color1 if the ImageListViewItem is selected. /// </summary> [Category("Appearance"), Description("Gets or sets the background gradient color1 if the ImageListViewItem is selected.")] public Color SelectedColor1 { get { return mSelectedColor1; } set { mSelectedColor1 = value; } } /// <summary> /// Gets or sets the background gradient color2 if the ImageListViewItem is selected. /// </summary> [Category("Appearance"), Description("Gets or sets the background gradient color2 if the ImageListViewItem is selected.")] public Color SelectedColor2 { get { return mSelectedColor2; } set { mSelectedColor2 = value; } } /// <summary> /// Gets or sets the border color of the ImageListViewItem if the item is selected. /// </summary> [Category("Appearance"), Description("Gets or sets the border color of the ImageListViewItem if the item is selected.")] public Color SelectedBorderColor { get { return mSelectedBorderColor; } set { mSelectedBorderColor = value; } } /// <summary> /// Gets or sets the background gradient color1 of the column header. /// </summary> [Category("Appearance Details View"), Description("Gets or sets the cells background color1 of the column header.")] public Color ColumnHeaderBackColor1 { get { return mColumnHeaderBackColor1; } set { mColumnHeaderBackColor1 = value; } } /// <summary> /// Gets or sets the background gradient color2 of the column header. /// </summary> [Category("Appearance Details View"), Description("Gets or sets the cells background color2 of the column header.")] public Color ColumnHeaderBackColor2 { get { return mColumnHeaderBackColor2; } set { mColumnHeaderBackColor2 = value; } } /// <summary> /// Gets or sets the background hover gradient color1 of the column header. /// </summary> [Category("Appearance Details View"), Description("Gets or sets the background hover color1 of the column header.")] public Color ColumnHeaderHoverColor1 { get { return mColumnHeaderHoverColor1; } set { mColumnHeaderHoverColor1 = value; } } /// <summary> /// Gets or sets the background hover gradient color2 of the column header. /// </summary> [Category("Appearance Details View"), Description("Gets or sets the background hover color2 of the column header.")] public Color ColumnHeaderHoverColor2 { get { return mColumnHeaderHoverColor2; } set { mColumnHeaderHoverColor2 = value; } } /// <summary> /// Gets or sets the cells foreground color of the coumn header text. /// </summary> [Category("Appearance Details View"), Description("Gets or sets the cells foreground color of the coumn header text.")] public Color ColumnHeaderForeColor { get { return mColumnHeaderForeColor; } set { mColumnHeaderForeColor = value; } } /// <summary> /// Gets or sets the cells background color if column is selected in Details View. /// </summary> [Category("Appearance Details View"), Description("Gets or sets the cells background color if column is selected in Details View.")] public Color ColumnSelectColor { get { return mColumnSelectColor; } set { mColumnSelectColor = value; } } /// <summary> /// Gets or sets the foreground color of the cell text in Details View. /// </summary> [Category("Appearance Details View"), Description("Gets or sets the foreground color of the cell text in Details View.")] public Color CellForeColor { get { return mCellForeColor; } set { mCellForeColor = value; } } /// <summary> /// Gets or sets the color of the separator in Details View. /// </summary> [Category("Appearance Details View"), Description("Gets or sets the color of the separator in Details View.")] public Color ColumnSeparatorColor { get { return mColumnSeparatorColor; } set { mColumnSeparatorColor = value; } } /// <summary> /// Gets or sets the background color of the image pane. /// </summary> [Category("Appearance Pane View"), Description("Gets or sets the background color of the image pane.")] public Color PaneBackColor { get { return mPaneBackColor; } set { mPaneBackColor = value; } } /// <summary> /// Gets or sets the separator line color between image pane and thumbnail view. /// </summary> [Category("Appearance Pane View"), Description("Gets or sets the separator line color between image pane and thumbnail view.")] public Color PaneSeparatorColor { get { return mPaneSeparatorColor; } set { mPaneSeparatorColor = value; } } /// <summary> /// Gets or sets the color of labels in pane view. /// </summary> [Category("Appearance Pane View"), Description("Gets or sets the color of labels in pane view.")] public Color PaneLabelColor { get { return mPaneLabelColor; } set { mPaneLabelColor = value; } } /// <summary> /// Gets or sets the image inner border color for thumbnails and pane. /// </summary> [Category("Appearance Image"), Description("Gets or sets the image inner border color for thumbnails and pane.")] public Color ImageInnerBorderColor { get { return mImageInnerBorderColor; } set { mImageInnerBorderColor = value; } } /// <summary> /// Gets or sets the image outer border color for thumbnails and pane. /// </summary> [Category("Appearance Image"), Description("Gets or sets the image outer border color for thumbnails and pane.")] public Color ImageOuterBorderColor { get { return mImageOuterBorderColor; } set { mImageOuterBorderColor = value; } } /// <summary> /// Gets or sets the background color1 of the selection rectangle. /// </summary> [Category("Appearance"), Description("Gets or sets the background color1 of the selection rectangle.")] public Color SelectionRectangleColor1 { get { return mSelectionRectangleColor1; } set { mSelectionRectangleColor1 = value; } } /// <summary> /// Gets or sets the background color2 of the selection rectangle. /// </summary> [Category("Appearance"), Description("Gets or sets the background color2 of the selection rectangle.")] public Color SelectionRectangleColor2 { get { return mSelectionRectangleColor2; } set { mSelectionRectangleColor2 = value; } } /// <summary> /// Gets or sets the color of the selection rectangle border. /// </summary> [Category("Appearance"), Description("Gets or sets the color of the selection rectangle border.")] public Color SelectionRectangleBorderColor { get { return mSelectionRectangleBorderColor; } set { mSelectionRectangleBorderColor = value; } } #endregion #region Constructor /// <summary> /// Initializes a new instance of the ImageListViewColor class. /// </summary> public ImageListViewColor() { // control mControlBackColor = SystemColors.Window; // item mBackColor = SystemColors.Window; mForeColor = SystemColors.ControlText; mBorderColor = Color.FromArgb(64, SystemColors.GrayText); mUnFocusedColor1 = Color.FromArgb(16, SystemColors.GrayText); mUnFocusedColor2 = Color.FromArgb(64, SystemColors.GrayText); mUnFocusedBorderColor = Color.FromArgb(128, SystemColors.GrayText); mHoverColor1 = Color.FromArgb(8, SystemColors.Highlight); mHoverColor2 = Color.FromArgb(64, SystemColors.Highlight); mHoverBorderColor = Color.FromArgb(64, SystemColors.Highlight); mSelectedColor1 = Color.FromArgb(16, SystemColors.Highlight); mSelectedColor2 = Color.FromArgb(128, SystemColors.Highlight); mSelectedBorderColor = Color.FromArgb(128, SystemColors.Highlight); mInsertionCaretColor = SystemColors.Highlight; // thumbnails & pane mImageInnerBorderColor = Color.FromArgb(128, Color.White); mImageOuterBorderColor = Color.FromArgb(128, Color.Gray); // details view mColumnHeaderBackColor1 = Color.FromArgb(32, SystemColors.Control); mColumnHeaderBackColor2 = Color.FromArgb(196, SystemColors.Control); mColumnHeaderHoverColor1 = Color.FromArgb(16, SystemColors.Highlight); mColumnHeaderHoverColor2 = Color.FromArgb(64, SystemColors.Highlight); mColumnHeaderForeColor = SystemColors.WindowText; mColumnSelectColor = Color.FromArgb(16, SystemColors.GrayText); mColumnSeparatorColor = Color.FromArgb(32, SystemColors.GrayText); mCellForeColor = SystemColors.ControlText; // image pane mPaneBackColor = Color.FromArgb(16, SystemColors.GrayText); mPaneSeparatorColor = Color.FromArgb(128, SystemColors.GrayText); mPaneLabelColor = SystemColors.GrayText; // selection rectangle mSelectionRectangleColor1 = Color.FromArgb(128, SystemColors.Highlight); mSelectionRectangleColor2 = Color.FromArgb(128, SystemColors.Highlight); mSelectionRectangleBorderColor = SystemColors.Highlight; } #endregion #region Static Members /// <summary> /// Represents the default color theme. /// </summary> public static ImageListViewColor Default = new ImageListViewColor(); /// <summary> /// Represents the noir color theme. /// </summary> public static ImageListViewColor Noir = ImageListViewColor.GetNoirTheme(); /// <summary> /// Sets the controls color palette to noir colors. /// </summary> private static ImageListViewColor GetNoirTheme() { ImageListViewColor c = new ImageListViewColor(); // control c.ControlBackColor = Color.Black; // item c.BackColor = Color.FromArgb(0x31, 0x31, 0x31); c.ForeColor = Color.LightGray; c.BorderColor = Color.DarkGray; c.UnFocusedColor1 = Color.FromArgb(16, SystemColors.GrayText); c.UnFocusedColor2 = Color.FromArgb(64, SystemColors.GrayText); c.UnFocusedBorderColor = Color.FromArgb(128, SystemColors.GrayText); c.HoverColor1 = Color.FromArgb(64, Color.White); c.HoverColor2 = Color.FromArgb(16, Color.White); c.HoverBorderColor = Color.FromArgb(64, SystemColors.Highlight); c.SelectedColor1 = Color.FromArgb(64, 96, 160); c.SelectedColor2 = Color.FromArgb(64, 64, 96, 160); c.SelectedBorderColor = Color.FromArgb(128, SystemColors.Highlight); c.InsertionCaretColor = Color.FromArgb(96, 144, 240); // thumbnails & pane c.ImageInnerBorderColor = Color.FromArgb(128, Color.White); c.ImageOuterBorderColor = Color.FromArgb(128, Color.Gray); // details view c.CellForeColor = Color.WhiteSmoke; c.ColumnHeaderBackColor1 = Color.FromArgb(32, 128, 128, 128); c.ColumnHeaderBackColor2 = Color.FromArgb(196, 128, 128, 128); c.ColumnHeaderHoverColor1 = Color.FromArgb(64, 96, 144, 240); c.ColumnHeaderHoverColor2 = Color.FromArgb(196, 96, 144, 240); c.ColumnHeaderForeColor = Color.White; c.ColumnSelectColor = Color.FromArgb(96, 128, 128, 128); c.ColumnSeparatorColor = Color.Gold; // image pane c.PaneBackColor = Color.FromArgb(0x31, 0x31, 0x31); c.PaneSeparatorColor = Color.Gold; c.PaneLabelColor = SystemColors.GrayText; // selection rectangke c.SelectionRectangleColor1 = Color.FromArgb(160, 96, 144, 240); c.SelectionRectangleColor2 = Color.FromArgb(32, 96, 144, 240); c.SelectionRectangleBorderColor = Color.FromArgb(64, 96, 144, 240); return c; } #endregion } }
#region MigraDoc - Creating Documents on the Fly // // Authors: // Stefan Lange (mailto:Stefan.Lange@pdfsharp.com) // Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com) // David Stephensen (mailto:David.Stephensen@pdfsharp.com) // // Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://www.migradoc.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; using System.Reflection; using System.Collections; using MigraDoc.DocumentObjectModel.IO; using MigraDoc.DocumentObjectModel.Internals; using MigraDoc.DocumentObjectModel.Visitors; namespace MigraDoc.DocumentObjectModel.Tables { /// <summary> /// Represents a table in a document. /// </summary> public class Table : DocumentObject, IVisitable { /// <summary> /// Initializes a new instance of the Table class. /// </summary> public Table() { } /// <summary> /// Initializes a new instance of the Table class with the specified parent. /// </summary> internal Table(DocumentObject parent) : base(parent) { } #region Methods /// <summary> /// Creates a deep copy of this object. /// </summary> public new Table Clone() { return (Table)DeepCopy(); } /// <summary> /// Implements the deep copy of the object. /// </summary> protected override object DeepCopy() { Table table = (Table)base.DeepCopy(); if (table.columns != null) { table.columns = table.columns.Clone(); table.columns.parent = table; } if (table.rows != null) { table.rows = table.rows.Clone(); table.rows.parent = table; } if (table.format != null) { table.format = table.format.Clone(); table.format.parent = table; } if (table.borders != null) { table.borders = table.borders.Clone(); table.borders.parent = table; } if (table.shading != null) { table.shading = table.shading.Clone(); table.shading.parent = table; } return table; } /// <summary> /// Adds a new column to the table. Allowed only before any row was added. /// </summary> public Column AddColumn() { return this.Columns.AddColumn(); } /// <summary> /// Adds a new column of the specified width to the table. Allowed only before any row was added. /// </summary> public Column AddColumn(Unit width) { Column clm = this.Columns.AddColumn(); clm.Width = width; return clm; } /// <summary> /// Adds a new row to the table. Allowed only if at least one column was added. /// </summary> public Row AddRow() { return this.rows.AddRow(); } /// <summary> /// Returns true if no cell exists in the table. /// </summary> public bool IsEmpty { get { return this.Rows.Count == 0 || this.Columns.Count == 0; } } /// <summary> /// Sets a shading of the specified Color in the specified Tablerange. /// </summary> public void SetShading(int clm, int row, int clms, int rows, Color clr) { int rowsCount = this.rows.Count; int clmsCount = this.columns.Count; if (row < 0 || row >= rowsCount) throw new ArgumentOutOfRangeException("row", row, "Invalid row index."); if (clm < 0 || clm >= clmsCount) throw new ArgumentOutOfRangeException("clm", clm, "Invalid column index."); if (rows <= 0 || row + rows > rowsCount) throw new ArgumentOutOfRangeException("rows", rows, "Invalid row count."); if (clms <= 0 || clm + clms > clmsCount) throw new ArgumentOutOfRangeException("clms", clms, "Invalid column count."); int maxRow = row + rows - 1; int maxClm = clm + clms - 1; for (int r = row; r <= maxRow; r++) { Row currentRow = this.rows[r]; for (int c = clm; c <= maxClm; c++) currentRow[c].Shading.Color = clr; } } /// <summary> /// Sets the borders surrounding the specified range of the table. /// </summary> public void SetEdge(int clm, int row, int clms, int rows, Edge edge, BorderStyle style, Unit width, Color clr) { Border border; int maxRow = row + rows - 1; int maxClm = clm + clms - 1; for (int r = row; r <= maxRow; r++) { Row currentRow = this.rows[r]; for (int c = clm; c <= maxClm; c++) { Cell currentCell = currentRow[c]; if ((edge & Edge.Top) == Edge.Top && r == row) { border = currentCell.Borders.Top; border.Style = style; border.Width = width; if (clr != Color.Empty) border.Color = clr; } if ((edge & Edge.Left) == Edge.Left && c == clm) { border = currentCell.Borders.Left; border.Style = style; border.Width = width; if (clr != Color.Empty) border.Color = clr; } if ((edge & Edge.Bottom) == Edge.Bottom && r == maxRow) { border = currentCell.Borders.Bottom; border.Style = style; border.Width = width; if (clr != Color.Empty) border.Color = clr; } if ((edge & Edge.Right) == Edge.Right && c == maxClm) { border = currentCell.Borders.Right; border.Style = style; border.Width = width; if (clr != Color.Empty) border.Color = clr; } if ((edge & Edge.Horizontal) == Edge.Horizontal && r < maxRow) { border = currentCell.Borders.Bottom; border.Style = style; border.Width = width; if (clr != Color.Empty) border.Color = clr; } if ((edge & Edge.Vertical) == Edge.Vertical && c < maxClm) { border = currentCell.Borders.Right; border.Style = style; border.Width = width; if (clr != Color.Empty) border.Color = clr; } if ((edge & Edge.DiagonalDown) == Edge.DiagonalDown) { border = currentCell.Borders.DiagonalDown; border.Style = style; border.Width = width; if (clr != Color.Empty) border.Color = clr; } if ((edge & Edge.DiagonalUp) == Edge.DiagonalUp) { border = currentCell.Borders.DiagonalUp; border.Style = style; border.Width = width; if (clr != Color.Empty) border.Color = clr; } } } } /// <summary> /// Sets the borders surrounding the specified range of the table. /// </summary> public void SetEdge(int clm, int row, int clms, int rows, Edge edge, BorderStyle style, Unit width) { SetEdge(clm, row, clms, rows, edge, style, width, Color.Empty); } #endregion #region Properties /// <summary> /// Gets or sets the Columns collection of the table. /// </summary> public Columns Columns { get { if (this.columns == null) this.columns = new Columns(this); return this.columns; } set { SetParent(value); this.columns = value; } } [DV] internal Columns columns; /// <summary> /// Gets the Rows collection of the table. /// </summary> public Rows Rows { get { if (this.rows == null) this.rows = new Rows(this); return this.rows; } set { SetParent(value); this.rows = value; } } [DV] internal Rows rows; /// <summary> /// Sets or gets the default style name for all rows and columns of the table. /// </summary> public string Style { get { return this.style.Value; } set { this.style.Value = value; } } [DV] internal NString style = NString.NullValue; /// <summary> /// Gets the default ParagraphFormat for all rows and columns of the table. /// </summary> public ParagraphFormat Format { get { if (this.format == null) this.format = new ParagraphFormat(this); return this.format; } set { SetParent(value); this.format = value; } } [DV] internal ParagraphFormat format; /// <summary> /// Gets or sets the default top padding for all cells of the table. /// </summary> public Unit TopPadding { get { return this.topPadding; } set { this.topPadding = value; } } [DV] internal Unit topPadding = Unit.NullValue; /// <summary> /// Gets or sets the default bottom padding for all cells of the table. /// </summary> public Unit BottomPadding { get { return this.bottomPadding; } set { this.bottomPadding = value; } } [DV] internal Unit bottomPadding = Unit.NullValue; /// <summary> /// Gets or sets the default left padding for all cells of the table. /// </summary> public Unit LeftPadding { get { return this.leftPadding; } set { this.leftPadding = value; } } [DV] internal Unit leftPadding = Unit.NullValue; /// <summary> /// Gets or sets the default right padding for all cells of the table. /// </summary> public Unit RightPadding { get { return this.rightPadding; } set { this.rightPadding = value; } } [DV] internal Unit rightPadding = Unit.NullValue; /// <summary> /// Gets the default Borders object for all cells of the column. /// </summary> public Borders Borders { get { if (this.borders == null) this.borders = new Borders(this); return this.borders; } set { SetParent(value); this.borders = value; } } [DV] internal Borders borders; /// <summary> /// Gets the default Borders object for all cells of the column. /// </summary> public Border LastRowOnPageBottomBorder { get { if (this.lastRowOnPageBottomBorder == null) this.lastRowOnPageBottomBorder = new Border(); return this.lastRowOnPageBottomBorder; } set { //SetParent(value); this.lastRowOnPageBottomBorder = value; } } [DV] internal Border lastRowOnPageBottomBorder; /// <summary> /// Gets or sets a flag to indicate the use of custom borders on the last row of each page. /// </summary> public Boolean UseCustomBorderForLastRowOnPage { get; set; } /// <summary> /// Gets the default Shading object for all cells of the column. /// </summary> public Shading Shading { get { if (this.shading == null) this.shading = new Shading(this); return this.shading; } set { SetParent(value); this.shading = value; } } [DV] internal Shading shading; /// <summary> /// Gets or sets a value indicating whether /// to keep all the table rows on the same page. /// </summary> public bool KeepTogether { get { return this.keepTogether.Value; } set { this.keepTogether.Value = value; } } [DV] internal NBool keepTogether = NBool.NullValue; /// <summary> /// Gets or sets a comment associated with this object. /// </summary> public string Comment { get { return this.comment.Value; } set { this.comment.Value = value; } } [DV] internal NString comment = NString.NullValue; #endregion #region Internal /// <summary> /// Converts Table into DDL. /// </summary> internal override void Serialize(Serializer serializer) { serializer.WriteComment(this.comment.Value); serializer.WriteLine("\\table"); int pos = serializer.BeginAttributes(); if (this.style.Value != String.Empty) serializer.WriteSimpleAttribute("Style", this.Style); if (!this.IsNull("Format")) this.format.Serialize(serializer, "Format", null); if (!this.topPadding.IsNull) serializer.WriteSimpleAttribute("TopPadding", this.TopPadding); if (!this.leftPadding.IsNull) serializer.WriteSimpleAttribute("LeftPadding", this.LeftPadding); if (!this.rightPadding.IsNull) serializer.WriteSimpleAttribute("RightPadding", this.RightPadding); if (!this.bottomPadding.IsNull) serializer.WriteSimpleAttribute("BottomPadding", this.BottomPadding); if (!this.IsNull("Borders")) this.borders.Serialize(serializer, null); if (!this.IsNull("Shading")) this.shading.Serialize(serializer); serializer.EndAttributes(pos); serializer.BeginContent(); this.Columns.Serialize(serializer); this.Rows.Serialize(serializer); serializer.EndContent(); } /// <summary> /// Allows the visitor object to visit the document object and it's child objects. /// </summary> void IVisitable.AcceptVisitor(DocumentObjectVisitor visitor, bool visitChildren) { visitor.VisitTable(this); ((IVisitable)this.columns).AcceptVisitor(visitor, visitChildren); ((IVisitable)this.rows).AcceptVisitor(visitor, visitChildren); } /// <summary> /// Gets the cell with the given row and column indices. /// </summary> public Cell this[int rwIdx, int clmIdx] { get { return this.Rows[rwIdx].Cells[clmIdx]; } } /// <summary> /// Returns the meta object of this instance. /// </summary> internal override Meta Meta { get { if (meta == null) meta = new Meta(typeof(Table)); return meta; } } static Meta meta; #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Collections; using Microsoft.DiaSymReader; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal partial class MethodDebugInfo<TTypeSymbol, TLocalSymbol> { private struct LocalNameAndScope : IEquatable<LocalNameAndScope> { internal readonly string LocalName; internal readonly int ScopeStart; internal readonly int ScopeEnd; internal LocalNameAndScope(string localName, int scopeStart, int scopeEnd) { LocalName = localName; ScopeStart = scopeStart; ScopeEnd = scopeEnd; } public bool Equals(LocalNameAndScope other) { return ScopeStart == other.ScopeStart && ScopeEnd == other.ScopeEnd && string.Equals(LocalName, other.LocalName, StringComparison.Ordinal); } public override bool Equals(object obj) { throw new NotImplementedException(); } public override int GetHashCode() { return Hash.Combine( Hash.Combine(ScopeStart, ScopeEnd), LocalName.GetHashCode()); } } public unsafe static MethodDebugInfo<TTypeSymbol, TLocalSymbol> ReadMethodDebugInfo( ISymUnmanagedReader3 symReader, EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProviderOpt, // TODO: only null in DTEE case where we looking for default namesapace int methodToken, int methodVersion, int ilOffset, bool isVisualBasicMethod) { // no symbols if (symReader == null) { return None; } if (symReader is ISymUnmanagedReader5 symReader5) { int hr = symReader5.GetPortableDebugMetadataByVersion(methodVersion, out byte* metadata, out int size); SymUnmanagedReaderExtensions.ThrowExceptionForHR(hr); if (hr == 0) { var mdReader = new MetadataReader(metadata, size); try { return ReadFromPortable(mdReader, methodToken, ilOffset, symbolProviderOpt, isVisualBasicMethod); } catch (BadImageFormatException) { // bad CDI, ignore return None; } } } var allScopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); var containingScopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); try { var symMethod = symReader.GetMethodByVersion(methodToken, methodVersion); if (symMethod != null) { symMethod.GetAllScopes(allScopes, containingScopes, ilOffset, isScopeEndInclusive: isVisualBasicMethod); } ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups; ImmutableArray<ExternAliasRecord> externAliasRecords; string defaultNamespaceName; if (isVisualBasicMethod) { ReadVisualBasicImportsDebugInfo( symReader, methodToken, methodVersion, out importRecordGroups, out defaultNamespaceName); externAliasRecords = ImmutableArray<ExternAliasRecord>.Empty; } else { Debug.Assert(symbolProviderOpt != null); ReadCSharpNativeImportsInfo( symReader, symbolProviderOpt, methodToken, methodVersion, out importRecordGroups, out externAliasRecords); defaultNamespaceName = ""; } // VB should read hoisted scope information from local variables: var hoistedLocalScopeRecords = isVisualBasicMethod ? default(ImmutableArray<HoistedLocalScopeRecord>) : ImmutableArray<HoistedLocalScopeRecord>.Empty; ImmutableDictionary<int, ImmutableArray<bool>> dynamicLocalMap = null; ImmutableDictionary<string, ImmutableArray<bool>> dynamicLocalConstantMap = null; ImmutableDictionary<int, ImmutableArray<string>> tupleLocalMap = null; ImmutableDictionary<LocalNameAndScope, ImmutableArray<string>> tupleLocalConstantMap = null; byte[] customDebugInfo = symReader.GetCustomDebugInfoBytes(methodToken, methodVersion); if (customDebugInfo != null) { if (!isVisualBasicMethod) { var customDebugInfoRecord = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(customDebugInfo, CustomDebugInfoKind.StateMachineHoistedLocalScopes); if (!customDebugInfoRecord.IsDefault) { hoistedLocalScopeRecords = CustomDebugInfoReader.DecodeStateMachineHoistedLocalScopesRecord(customDebugInfoRecord) .SelectAsArray(s => new HoistedLocalScopeRecord(s.StartOffset, s.Length)); } GetCSharpDynamicLocalInfo( customDebugInfo, allScopes, out dynamicLocalMap, out dynamicLocalConstantMap); } GetTupleElementNamesLocalInfo( customDebugInfo, out tupleLocalMap, out tupleLocalConstantMap); } var constantsBuilder = ArrayBuilder<TLocalSymbol>.GetInstance(); if (symbolProviderOpt != null) // TODO { GetConstants(constantsBuilder, symbolProviderOpt, containingScopes, dynamicLocalConstantMap, tupleLocalConstantMap); } var reuseSpan = GetReuseSpan(allScopes, ilOffset, isVisualBasicMethod); return new MethodDebugInfo<TTypeSymbol, TLocalSymbol>( hoistedLocalScopeRecords, importRecordGroups, externAliasRecords, dynamicLocalMap, tupleLocalMap, defaultNamespaceName, containingScopes.GetLocalNames(), constantsBuilder.ToImmutableAndFree(), reuseSpan); } catch (InvalidOperationException) { // bad CDI, ignore return None; } finally { allScopes.Free(); containingScopes.Free(); } } /// <summary> /// Get the (unprocessed) import strings for a given method. /// </summary> /// <remarks> /// Doesn't consider forwarding. /// /// CONSIDER: Dev12 doesn't just check the root scope - it digs around to find the best /// match based on the IL offset and then walks up to the root scope (see PdbUtil::GetScopeFromOffset). /// However, it's not clear that this matters, since imports can't be scoped in VB. This is probably /// just based on the way they were extracting locals and constants based on a specific scope. /// /// Returns empty array if there are no import strings for the specified method. /// </remarks> private static ImmutableArray<string> GetImportStrings(ISymUnmanagedReader reader, int methodToken, int methodVersion) { var method = reader.GetMethodByVersion(methodToken, methodVersion); if (method == null) { // In rare circumstances (only bad PDBs?) GetMethodByVersion can return null. // If there's no debug info for the method, then no import strings are available. return ImmutableArray<string>.Empty; } ISymUnmanagedScope rootScope = method.GetRootScope(); if (rootScope == null) { Debug.Assert(false, "Expected a root scope."); return ImmutableArray<string>.Empty; } var childScopes = rootScope.GetChildren(); if (childScopes.Length == 0) { // It seems like there should always be at least one child scope, but we've // seen PDBs where that is not the case. return ImmutableArray<string>.Empty; } // As in NamespaceListWrapper::Init, we only consider namespaces in the first // child of the root scope. ISymUnmanagedScope firstChildScope = childScopes[0]; var namespaces = firstChildScope.GetNamespaces(); if (namespaces.Length == 0) { // It seems like there should always be at least one namespace (i.e. the global // namespace), but we've seen PDBs where that is not the case. return ImmutableArray<string>.Empty; } return ImmutableArray.CreateRange(namespaces.Select(n => n.GetName())); } private static void ReadCSharpNativeImportsInfo( ISymUnmanagedReader3 reader, EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider, int methodToken, int methodVersion, out ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups, out ImmutableArray<ExternAliasRecord> externAliasRecords) { ImmutableArray<string> externAliasStrings; var importStringGroups = CustomDebugInfoReader.GetCSharpGroupedImportStrings( methodToken, KeyValuePair.Create(reader, methodVersion), getMethodCustomDebugInfo: (token, arg) => arg.Key.GetCustomDebugInfoBytes(token, arg.Value), getMethodImportStrings: (token, arg) => GetImportStrings(arg.Key, token, arg.Value), externAliasStrings: out externAliasStrings); Debug.Assert(importStringGroups.IsDefault == externAliasStrings.IsDefault); ArrayBuilder<ImmutableArray<ImportRecord>> importRecordGroupBuilder = null; ArrayBuilder<ExternAliasRecord> externAliasRecordBuilder = null; if (!importStringGroups.IsDefault) { importRecordGroupBuilder = ArrayBuilder<ImmutableArray<ImportRecord>>.GetInstance(importStringGroups.Length); foreach (var importStringGroup in importStringGroups) { var groupBuilder = ArrayBuilder<ImportRecord>.GetInstance(importStringGroup.Length); foreach (var importString in importStringGroup) { ImportRecord record; if (TryCreateImportRecordFromCSharpImportString(symbolProvider, importString, out record)) { groupBuilder.Add(record); } else { Debug.WriteLine($"Failed to parse import string {importString}"); } } importRecordGroupBuilder.Add(groupBuilder.ToImmutableAndFree()); } if (!externAliasStrings.IsDefault) { externAliasRecordBuilder = ArrayBuilder<ExternAliasRecord>.GetInstance(externAliasStrings.Length); foreach (string externAliasString in externAliasStrings) { string alias; string externAlias; string target; ImportTargetKind kind; if (!CustomDebugInfoReader.TryParseCSharpImportString(externAliasString, out alias, out externAlias, out target, out kind)) { Debug.WriteLine($"Unable to parse extern alias '{externAliasString}'"); continue; } Debug.Assert(kind == ImportTargetKind.Assembly, "Programmer error: How did a non-assembly get in the extern alias list?"); Debug.Assert(alias != null); // Name of the extern alias. Debug.Assert(externAlias == null); // Not used. Debug.Assert(target != null); // Name of the target assembly. AssemblyIdentity targetIdentity; if (!AssemblyIdentity.TryParseDisplayName(target, out targetIdentity)) { Debug.WriteLine($"Unable to parse target of extern alias '{externAliasString}'"); continue; } externAliasRecordBuilder.Add(new ExternAliasRecord(alias, targetIdentity)); } } } importRecordGroups = importRecordGroupBuilder?.ToImmutableAndFree() ?? ImmutableArray<ImmutableArray<ImportRecord>>.Empty; externAliasRecords = externAliasRecordBuilder?.ToImmutableAndFree() ?? ImmutableArray<ExternAliasRecord>.Empty; } private static bool TryCreateImportRecordFromCSharpImportString(EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider, string importString, out ImportRecord record) { ImportTargetKind targetKind; string externAlias; string alias; string targetString; if (CustomDebugInfoReader.TryParseCSharpImportString(importString, out alias, out externAlias, out targetString, out targetKind)) { ITypeSymbol type = null; if (targetKind == ImportTargetKind.Type) { type = symbolProvider.GetTypeSymbolForSerializedType(targetString); targetString = null; } record = new ImportRecord( targetKind: targetKind, alias: alias, targetType: type, targetString: targetString, targetAssembly: null, targetAssemblyAlias: externAlias); return true; } record = default(ImportRecord); return false; } /// <exception cref="InvalidOperationException">Bad data.</exception> private static void GetCSharpDynamicLocalInfo( byte[] customDebugInfo, IEnumerable<ISymUnmanagedScope> scopes, out ImmutableDictionary<int, ImmutableArray<bool>> dynamicLocalMap, out ImmutableDictionary<string, ImmutableArray<bool>> dynamicLocalConstantMap) { dynamicLocalMap = null; dynamicLocalConstantMap = null; var record = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(customDebugInfo, CustomDebugInfoKind.DynamicLocals); if (record.IsDefault) { return; } var localKindsByName = PooledDictionary<string, LocalKind>.GetInstance(); GetLocalKindByName(localKindsByName, scopes); ImmutableDictionary<int, ImmutableArray<bool>>.Builder localBuilder = null; ImmutableDictionary<string, ImmutableArray<bool>>.Builder constantBuilder = null; var dynamicLocals = CustomDebugInfoReader.DecodeDynamicLocalsRecord(record); foreach (var dynamicLocal in dynamicLocals) { int slot = dynamicLocal.SlotId; var flags = GetFlags(dynamicLocal); if (slot == 0) { LocalKind kind; var name = dynamicLocal.LocalName; localKindsByName.TryGetValue(name, out kind); switch (kind) { case LocalKind.DuplicateName: // Drop locals with ambiguous names. continue; case LocalKind.ConstantName: constantBuilder = constantBuilder ?? ImmutableDictionary.CreateBuilder<string, ImmutableArray<bool>>(); constantBuilder[name] = flags; continue; } } localBuilder = localBuilder ?? ImmutableDictionary.CreateBuilder<int, ImmutableArray<bool>>(); localBuilder[slot] = flags; } if (localBuilder != null) { dynamicLocalMap = localBuilder.ToImmutable(); } if (constantBuilder != null) { dynamicLocalConstantMap = constantBuilder.ToImmutable(); } localKindsByName.Free(); } private static ImmutableArray<bool> GetFlags(DynamicLocalInfo bucket) { int flagCount = bucket.FlagCount; ulong flags = bucket.Flags; var builder = ArrayBuilder<bool>.GetInstance(flagCount); for (int i = 0; i < flagCount; i++) { builder.Add((flags & (1u << i)) != 0); } return builder.ToImmutableAndFree(); } private enum LocalKind { DuplicateName, VariableName, ConstantName } /// <summary> /// Dynamic CDI encodes slot id and name for each dynamic local variable, but only name for a constant. /// Constants have slot id set to 0. As a result there is a potential for ambiguity. If a variable in a slot 0 /// and a constant defined anywhere in the method body have the same name we can't say which one /// the dynamic flags belong to (if there is a dynamic record for at least one of them). /// /// This method returns the local kind (variable, constant, or duplicate) based on name. /// </summary> private static void GetLocalKindByName(Dictionary<string, LocalKind> localNames, IEnumerable<ISymUnmanagedScope> scopes) { Debug.Assert(localNames.Count == 0); var localSlot0 = scopes.SelectMany(scope => scope.GetLocals()).FirstOrDefault(variable => variable.GetSlot() == 0); if (localSlot0 != null) { localNames.Add(localSlot0.GetName(), LocalKind.VariableName); } foreach (var scope in scopes) { foreach (var constant in scope.GetConstants()) { string name = constant.GetName(); localNames[name] = localNames.ContainsKey(name) ? LocalKind.DuplicateName : LocalKind.ConstantName; } } } private static void GetTupleElementNamesLocalInfo( byte[] customDebugInfo, out ImmutableDictionary<int, ImmutableArray<string>> tupleLocalMap, out ImmutableDictionary<LocalNameAndScope, ImmutableArray<string>> tupleLocalConstantMap) { tupleLocalMap = null; tupleLocalConstantMap = null; var record = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(customDebugInfo, CustomDebugInfoKind.TupleElementNames); if (record.IsDefault) { return; } ImmutableDictionary<int, ImmutableArray<string>>.Builder localBuilder = null; ImmutableDictionary<LocalNameAndScope, ImmutableArray<string>>.Builder constantBuilder = null; var tuples = CustomDebugInfoReader.DecodeTupleElementNamesRecord(record); foreach (var tuple in tuples) { var slotIndex = tuple.SlotIndex; var elementNames = tuple.ElementNames; if (slotIndex < 0) { constantBuilder = constantBuilder ?? ImmutableDictionary.CreateBuilder<LocalNameAndScope, ImmutableArray<string>>(); var localAndScope = new LocalNameAndScope(tuple.LocalName, tuple.ScopeStart, tuple.ScopeEnd); constantBuilder[localAndScope] = elementNames; } else { localBuilder = localBuilder ?? ImmutableDictionary.CreateBuilder<int, ImmutableArray<string>>(); localBuilder[slotIndex] = elementNames; } } if (localBuilder != null) { tupleLocalMap = localBuilder.ToImmutable(); } if (constantBuilder != null) { tupleLocalConstantMap = constantBuilder.ToImmutable(); } } private static void ReadVisualBasicImportsDebugInfo( ISymUnmanagedReader reader, int methodToken, int methodVersion, out ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups, out string defaultNamespaceName) { importRecordGroups = ImmutableArray<ImmutableArray<ImportRecord>>.Empty; var importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings( methodToken, KeyValuePair.Create(reader, methodVersion), (token, arg) => GetImportStrings(arg.Key, token, arg.Value)); if (importStrings.IsDefault) { defaultNamespaceName = ""; return; } defaultNamespaceName = null; var projectLevelImportRecords = ArrayBuilder<ImportRecord>.GetInstance(); var fileLevelImportRecords = ArrayBuilder<ImportRecord>.GetInstance(); foreach (string importString in importStrings) { Debug.Assert(importString != null); if (importString.Length > 0 && importString[0] == '*') { string alias = null; string target = null; ImportTargetKind kind = 0; VBImportScopeKind scope = 0; if (!CustomDebugInfoReader.TryParseVisualBasicImportString(importString, out alias, out target, out kind, out scope)) { Debug.WriteLine($"Unable to parse import string '{importString}'"); continue; } else if (kind == ImportTargetKind.Defunct) { continue; } Debug.Assert(alias == null); // The default namespace is never aliased. Debug.Assert(target != null); Debug.Assert(kind == ImportTargetKind.DefaultNamespace); // We only expect to see one of these, but it looks like ProcedureContext::LoadImportsAndDefaultNamespaceNormal // implicitly uses the last one if there are multiple. Debug.Assert(defaultNamespaceName == null); defaultNamespaceName = target; } else { ImportRecord importRecord; VBImportScopeKind scope = 0; if (TryCreateImportRecordFromVisualBasicImportString(importString, out importRecord, out scope)) { if (scope == VBImportScopeKind.Project) { projectLevelImportRecords.Add(importRecord); } else { Debug.Assert(scope == VBImportScopeKind.File || scope == VBImportScopeKind.Unspecified); fileLevelImportRecords.Add(importRecord); } } else { Debug.WriteLine($"Failed to parse import string {importString}"); } } } importRecordGroups = ImmutableArray.Create( fileLevelImportRecords.ToImmutableAndFree(), projectLevelImportRecords.ToImmutableAndFree()); defaultNamespaceName = defaultNamespaceName ?? ""; } private static bool TryCreateImportRecordFromVisualBasicImportString(string importString, out ImportRecord record, out VBImportScopeKind scope) { ImportTargetKind targetKind; string alias; string targetString; if (CustomDebugInfoReader.TryParseVisualBasicImportString(importString, out alias, out targetString, out targetKind, out scope)) { record = new ImportRecord( targetKind: targetKind, alias: alias, targetType: null, targetString: targetString, targetAssembly: null, targetAssemblyAlias: null); return true; } record = default(ImportRecord); return false; } private static ILSpan GetReuseSpan(ArrayBuilder<ISymUnmanagedScope> scopes, int ilOffset, bool isEndInclusive) { return MethodContextReuseConstraints.CalculateReuseSpan( ilOffset, ILSpan.MaxValue, scopes.Select(scope => new ILSpan((uint)scope.GetStartOffset(), (uint)(scope.GetEndOffset() + (isEndInclusive ? 1 : 0))))); } private static void GetConstants( ArrayBuilder<TLocalSymbol> builder, EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider, ArrayBuilder<ISymUnmanagedScope> scopes, ImmutableDictionary<string, ImmutableArray<bool>> dynamicLocalConstantMapOpt, ImmutableDictionary<LocalNameAndScope, ImmutableArray<string>> tupleLocalConstantMapOpt) { foreach (var scope in scopes) { foreach (var constant in scope.GetConstants()) { string name = constant.GetName(); object rawValue = constant.GetValue(); var signature = constant.GetSignature().ToImmutableArray(); TTypeSymbol type; try { type = symbolProvider.DecodeLocalVariableType(signature); } catch (Exception e) when (e is UnsupportedSignatureContent || e is BadImageFormatException) { // ignore continue; } if (type.Kind == SymbolKind.ErrorType) { continue; } ConstantValue constantValue = PdbHelpers.GetSymConstantValue(type, rawValue); // TODO (https://github.com/dotnet/roslyn/issues/1815): report error properly when the symbol is used if (constantValue.IsBad) { continue; } var dynamicFlags = default(ImmutableArray<bool>); if (dynamicLocalConstantMapOpt != null) { dynamicLocalConstantMapOpt.TryGetValue(name, out dynamicFlags); } var tupleElementNames = default(ImmutableArray<string>); if (tupleLocalConstantMapOpt != null) { int scopeStart = scope.GetStartOffset(); int scopeEnd = scope.GetEndOffset(); tupleLocalConstantMapOpt.TryGetValue(new LocalNameAndScope(name, scopeStart, scopeEnd), out tupleElementNames); } builder.Add(symbolProvider.GetLocalConstant(name, type, constantValue, dynamicFlags, tupleElementNames)); } } } /// <summary> /// Returns symbols for the locals emitted in the original method, /// based on the local signatures from the IL and the names and /// slots from the PDB. The actual locals are needed to ensure the /// local slots in the generated method match the original. /// </summary> public static void GetLocals( ArrayBuilder<TLocalSymbol> builder, EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider, ImmutableArray<string> names, ImmutableArray<LocalInfo<TTypeSymbol>> localInfo, ImmutableDictionary<int, ImmutableArray<bool>> dynamicLocalMapOpt, ImmutableDictionary<int, ImmutableArray<string>> tupleLocalConstantMapOpt) { if (localInfo.Length == 0) { // When debugging a .dmp without a heap, localInfo will be empty although // names may be non-empty if there is a PDB. Since there's no type info, the // locals are dropped. Note this means the local signature of any generated // method will not match the original signature, so new locals will overlap // original locals. That is ok since there is no live process for the debugger // to update (any modified values exist in the debugger only). return; } Debug.Assert(localInfo.Length >= names.Length); for (int i = 0; i < localInfo.Length; i++) { string name = (i < names.Length) ? names[i] : null; var dynamicFlags = default(ImmutableArray<bool>); dynamicLocalMapOpt?.TryGetValue(i, out dynamicFlags); var tupleElementNames = default(ImmutableArray<string>); tupleLocalConstantMapOpt?.TryGetValue(i, out tupleElementNames); builder.Add(symbolProvider.GetLocalVariable(name, i, localInfo[i], dynamicFlags, tupleElementNames)); } } } }
using System; using System.Data; using System.Data.SqlTypes; using System.Data.SqlClient; namespace SIMRS.DataAccess { public class RS_Registrasi : DBInteractionBase { #region Class Member Declarations private SqlInt64 _penjaminId, _penjaminIdOld, _pasienId, _pasienIdOld, _registrasiId; private SqlDateTime _tanggalRegistrasi, _createdDate, _modifiedDate, _tanggalBayar; private SqlInt32 _createdBy, _modifiedBy, _jenisRegistrasiId, _jenisRegistrasiIdOld, _jenisPenjaminId, _jenisPenjaminIdOld, _statusBayar; private SqlString _noRegistrasi, _keterangan, _noUrut; #endregion public RS_Registrasi() { // Nothing for now. } public override bool Insert() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Registrasi_Insert]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@PasienId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _pasienId)); cmdToExecute.Parameters.Add(new SqlParameter("@NoRegistrasi", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _noRegistrasi)); cmdToExecute.Parameters.Add(new SqlParameter("@JenisRegistrasiId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _jenisRegistrasiId)); cmdToExecute.Parameters.Add(new SqlParameter("@TanggalRegistrasi", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _tanggalRegistrasi)); cmdToExecute.Parameters.Add(new SqlParameter("@JenisPenjaminId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _jenisPenjaminId)); cmdToExecute.Parameters.Add(new SqlParameter("@PenjaminId", SqlDbType.BigInt, 8, ParameterDirection.Input, true, 19, 0, "", DataRowVersion.Proposed, _penjaminId)); cmdToExecute.Parameters.Add(new SqlParameter("@StatusBayar", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _statusBayar)); cmdToExecute.Parameters.Add(new SqlParameter("@TanggalBayar", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _tanggalBayar)); cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _createdBy)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _createdDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate)); cmdToExecute.Parameters.Add(new SqlParameter("@RegistrasiId", SqlDbType.BigInt, 8, ParameterDirection.Output, true, 19, 0, "", DataRowVersion.Proposed, _registrasiId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); cmdToExecute.Parameters.Add(new SqlParameter("@NoUrut", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _noUrut)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _registrasiId = (SqlInt64)cmdToExecute.Parameters["@RegistrasiId"].Value; _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Registrasi_Insert' reported the ErrorCode: " + _errorCode); } return true; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Registrasi::Insert::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } public override bool Update() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Registrasi_Update]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@RegistrasiId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _registrasiId)); cmdToExecute.Parameters.Add(new SqlParameter("@PasienId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _pasienId)); cmdToExecute.Parameters.Add(new SqlParameter("@NoRegistrasi", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _noRegistrasi)); cmdToExecute.Parameters.Add(new SqlParameter("@JenisRegistrasiId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _jenisRegistrasiId)); cmdToExecute.Parameters.Add(new SqlParameter("@TanggalRegistrasi", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _tanggalRegistrasi)); cmdToExecute.Parameters.Add(new SqlParameter("@JenisPenjaminId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _jenisPenjaminId)); cmdToExecute.Parameters.Add(new SqlParameter("@PenjaminId", SqlDbType.BigInt, 8, ParameterDirection.Input, true, 19, 0, "", DataRowVersion.Proposed, _penjaminId)); cmdToExecute.Parameters.Add(new SqlParameter("@StatusBayar", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _statusBayar)); cmdToExecute.Parameters.Add(new SqlParameter("@TanggalBayar", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _tanggalBayar)); cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _createdBy)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _createdDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Registrasi_Update' reported the ErrorCode: " + _errorCode); } return true; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Registrasi::Update::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Delete method. This method will Delete one existing row in the database, based on the Primary Key. /// </summary> /// <returns>True if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>RegistrasiId</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override bool Delete() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Registrasi_Delete]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@RegistrasiId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _registrasiId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Registrasi_Delete' reported the ErrorCode: " + _errorCode); } return true; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Registrasi::Delete::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Select method. This method will Select one existing row from the database, based on the Primary Key. /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>RegistrasiId</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// <LI>RegistrasiId</LI> /// <LI>PasienId</LI> /// <LI>NoRegistrasi</LI> /// <LI>JenisRegistrasiId</LI> /// <LI>TanggalRegistrasi</LI> /// <LI>JenisPenjaminId</LI> /// <LI>PenjaminId</LI> /// <LI>StatusBayar</LI> /// <LI>TanggalBayar</LI> /// <LI>Keterangan</LI> /// <LI>CreatedBy</LI> /// <LI>CreatedDate</LI> /// <LI>ModifiedBy</LI> /// <LI>ModifiedDate</LI> /// </UL> /// Will fill all properties corresponding with a field in the table with the value of the row selected. /// </remarks> /// public override DataTable SelectOne() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Registrasi_SelectOne]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_Registrasi"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@RegistrasiId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _registrasiId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Registrasi_SelectOne' reported the ErrorCode: " + _errorCode); } if(toReturn.Rows.Count > 0) { _registrasiId = (Int64)toReturn.Rows[0]["RegistrasiId"]; _pasienId = (Int64)toReturn.Rows[0]["PasienId"]; _noRegistrasi = toReturn.Rows[0]["NoRegistrasi"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["NoRegistrasi"]; _jenisRegistrasiId = toReturn.Rows[0]["JenisRegistrasiId"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["JenisRegistrasiId"]; _tanggalRegistrasi = toReturn.Rows[0]["TanggalRegistrasi"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["TanggalRegistrasi"]; _jenisPenjaminId = toReturn.Rows[0]["JenisPenjaminId"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["JenisPenjaminId"]; _penjaminId = toReturn.Rows[0]["PenjaminId"] == System.DBNull.Value ? SqlInt64.Null : (Int64)toReturn.Rows[0]["PenjaminId"]; _statusBayar = toReturn.Rows[0]["StatusBayar"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["StatusBayar"]; _tanggalBayar = toReturn.Rows[0]["TanggalBayar"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["TanggalBayar"]; _keterangan = toReturn.Rows[0]["Keterangan"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Keterangan"]; _createdBy = toReturn.Rows[0]["CreatedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["CreatedBy"]; _createdDate = toReturn.Rows[0]["CreatedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["CreatedDate"]; _modifiedBy = toReturn.Rows[0]["ModifiedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["ModifiedBy"]; _modifiedDate = toReturn.Rows[0]["ModifiedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["ModifiedDate"]; } return toReturn; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Registrasi::SelectOne::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } public DataTable SelectOne_ByPasienId() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Registrasi_SelectOne_ByPasienId]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_Registrasi"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@PasienId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _pasienId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Registrasi_SelectOne_ByPasienId' reported the ErrorCode: " + _errorCode); } if (toReturn.Rows.Count > 0) { _registrasiId = (Int64)toReturn.Rows[0]["RegistrasiId"]; _pasienId = (Int64)toReturn.Rows[0]["PasienId"]; _noRegistrasi = toReturn.Rows[0]["NoRegistrasi"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["NoRegistrasi"]; _jenisRegistrasiId = toReturn.Rows[0]["JenisRegistrasiId"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["JenisRegistrasiId"]; _tanggalRegistrasi = toReturn.Rows[0]["TanggalRegistrasi"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["TanggalRegistrasi"]; _jenisPenjaminId = toReturn.Rows[0]["JenisPenjaminId"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["JenisPenjaminId"]; _penjaminId = toReturn.Rows[0]["PenjaminId"] == System.DBNull.Value ? SqlInt64.Null : (Int64)toReturn.Rows[0]["PenjaminId"]; _statusBayar = toReturn.Rows[0]["StatusBayar"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["StatusBayar"]; _tanggalBayar = toReturn.Rows[0]["TanggalBayar"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["TanggalBayar"]; _keterangan = toReturn.Rows[0]["Keterangan"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Keterangan"]; _createdBy = toReturn.Rows[0]["CreatedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["CreatedBy"]; _createdDate = toReturn.Rows[0]["CreatedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["CreatedDate"]; _modifiedBy = toReturn.Rows[0]["ModifiedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["ModifiedBy"]; _modifiedDate = toReturn.Rows[0]["ModifiedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["ModifiedDate"]; } return toReturn; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Registrasi::SelectOne_ByPasienId::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } /// <summary> /// Purpose: SelectAll method. This method will Select all rows from the table. /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override DataTable SelectAll() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Registrasi_SelectAll]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_Registrasi"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Registrasi_SelectAll' reported the ErrorCode: " + _errorCode); } return toReturn; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Registrasi::SelectAll::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } /// <summary> /// Purpose: Select method for a foreign key. This method will Select one or more rows from the database, based on the Foreign Key 'PasienId' /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>PasienId</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public DataTable SelectAllWPasienIdLogic() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Registrasi_SelectAllWPasienIdLogic]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_Registrasi"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@PasienId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _pasienId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 19, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Registrasi_SelectAllWPasienIdLogic' reported the ErrorCode: " + _errorCode); } return toReturn; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Registrasi::SelectAllWPasienIdLogic::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } /// <summary> /// Purpose: Select method for a foreign key. This method will Select one or more rows from the database, based on the Foreign Key 'JenisRegistrasiId' /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>JenisRegistrasiId. May be SqlInt32.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public DataTable SelectAllWJenisRegistrasiIdLogic() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Registrasi_SelectAllWJenisRegistrasiIdLogic]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_Registrasi"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@JenisRegistrasiId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _jenisRegistrasiId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Registrasi_SelectAllWJenisRegistrasiIdLogic' reported the ErrorCode: " + _errorCode); } return toReturn; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Registrasi::SelectAllWJenisRegistrasiIdLogic::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } public DataTable SelectAsalPasien() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Registrasi_SelectAsalPasien]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_Registrasi"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@RegistrasiId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _registrasiId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Registrasi_SelectAsalPasien' reported the ErrorCode: " + _errorCode); } return toReturn; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Registrasi::SelectAsalPasien::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } #region Class Property Declarations public SqlInt64 RegistrasiId { get { return _registrasiId; } set { SqlInt64 registrasiIdTmp = (SqlInt64)value; if(registrasiIdTmp.IsNull) { throw new ArgumentOutOfRangeException("RegistrasiId", "RegistrasiId can't be NULL"); } _registrasiId = value; } } public SqlInt64 PasienId { get { return _pasienId; } set { SqlInt64 pasienIdTmp = (SqlInt64)value; if(pasienIdTmp.IsNull) { throw new ArgumentOutOfRangeException("PasienId", "PasienId can't be NULL"); } _pasienId = value; } } public SqlInt64 PasienIdOld { get { return _pasienIdOld; } set { SqlInt64 pasienIdOldTmp = (SqlInt64)value; if(pasienIdOldTmp.IsNull) { throw new ArgumentOutOfRangeException("PasienIdOld", "PasienIdOld can't be NULL"); } _pasienIdOld = value; } } public SqlString NoRegistrasi { get { return _noRegistrasi; } set { _noRegistrasi = value; } } public SqlInt32 JenisRegistrasiId { get { return _jenisRegistrasiId; } set { _jenisRegistrasiId = value; } } public SqlInt32 JenisRegistrasiIdOld { get { return _jenisRegistrasiIdOld; } set { _jenisRegistrasiIdOld = value; } } public SqlDateTime TanggalRegistrasi { get { return _tanggalRegistrasi; } set { _tanggalRegistrasi = value; } } public SqlInt32 JenisPenjaminId { get { return _jenisPenjaminId; } set { _jenisPenjaminId = value; } } public SqlInt32 JenisPenjaminIdOld { get { return _jenisPenjaminIdOld; } set { _jenisPenjaminIdOld = value; } } public SqlInt64 PenjaminId { get { return _penjaminId; } set { _penjaminId = value; } } public SqlInt64 PenjaminIdOld { get { return _penjaminIdOld; } set { _penjaminIdOld = value; } } public SqlInt32 StatusBayar { get { return _statusBayar; } set { _statusBayar = value; } } public SqlDateTime TanggalBayar { get { return _tanggalBayar; } set { _tanggalBayar = value; } } public SqlString Keterangan { get { return _keterangan; } set { _keterangan = value; } } public SqlInt32 CreatedBy { get { return _createdBy; } set { _createdBy = value; } } public SqlDateTime CreatedDate { get { return _createdDate; } set { _createdDate = value; } } public SqlInt32 ModifiedBy { get { return _modifiedBy; } set { _modifiedBy = value; } } public SqlDateTime ModifiedDate { get { return _modifiedDate; } set { _modifiedDate = value; } } public SqlString NoUrut { get { return _noUrut; } set { _noUrut = value; } } #endregion } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Linq; using System.Runtime.CompilerServices; using System.Security; namespace NLog.UnitTests { using System; using NLog.Common; using System.IO; using System.Text; using System.Globalization; using NLog.Layouts; using NLog.Config; using NLog.Targets; using Xunit; using System.Xml.Linq; using System.Xml; using System.IO.Compression; #if (NET3_5 || NET4_0 || NET4_5) && !NETSTANDARD using Ionic.Zip; #endif public abstract class NLogTestBase { protected NLogTestBase() { //reset before every test if (LogManager.Configuration != null) { //flush all events if needed. LogManager.Configuration.Close(); } if (LogManager.LogFactory != null) { LogManager.LogFactory.ResetCandidateConfigFilePath(); } LogManager.Configuration = null; InternalLogger.Reset(); LogManager.ThrowExceptions = false; LogManager.ThrowConfigExceptions = null; System.Diagnostics.Trace.Listeners.Clear(); #if !NETSTANDARD System.Diagnostics.Debug.Listeners.Clear(); #endif } protected void AssertDebugCounter(string targetName, int val) { Assert.Equal(val, GetDebugTarget(targetName).Counter); } protected void AssertDebugLastMessage(string targetName, string msg) { Assert.Equal(msg, GetDebugLastMessage(targetName)); } protected void AssertDebugLastMessageContains(string targetName, string msg) { string debugLastMessage = GetDebugLastMessage(targetName); Assert.True(debugLastMessage.Contains(msg), $"Expected to find '{msg}' in last message value on '{targetName}', but found '{debugLastMessage}'"); } protected string GetDebugLastMessage(string targetName) { return GetDebugLastMessage(targetName, LogManager.Configuration); } protected string GetDebugLastMessage(string targetName, LoggingConfiguration configuration) { return GetDebugTarget(targetName, configuration).LastMessage; } public DebugTarget GetDebugTarget(string targetName) { return GetDebugTarget(targetName, LogManager.Configuration); } protected DebugTarget GetDebugTarget(string targetName, LoggingConfiguration configuration) { var debugTarget = (DebugTarget)configuration.FindTargetByName(targetName); Assert.NotNull(debugTarget); return debugTarget; } protected void AssertFileContentsStartsWith(string fileName, string contents, Encoding encoding) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); byte[] buf = File.ReadAllBytes(fileName); Assert.True(encodedBuf.Length <= buf.Length, $"File:{fileName} encodedBytes:{encodedBuf.Length} does not match file.content:{buf.Length}, file.length = {fi.Length}"); for (int i = 0; i < encodedBuf.Length; ++i) { if (encodedBuf[i] != buf[i]) Assert.True(encodedBuf[i] == buf[i], $"File:{fileName} content mismatch {(int) encodedBuf[i]} <> {(int) buf[i]} at index {i}"); } } protected void AssertFileContentsEndsWith(string fileName, string contents, Encoding encoding) { if (!File.Exists(fileName)) Assert.True(false, "File '" + fileName + "' doesn't exist."); string fileText = File.ReadAllText(fileName, encoding); Assert.True(fileText.Length >= contents.Length); Assert.Equal(contents, fileText.Substring(fileText.Length - contents.Length)); } protected class CustomFileCompressor : IFileCompressor { public void CompressFile(string fileName, string archiveFileName) { #if (NET3_5 || NET4_0 || NET4_5) && !NETSTANDARD using (var zip = new Ionic.Zip.ZipFile()) { zip.AddFile(fileName); zip.Save(archiveFileName); } #endif } } #if NET3_5 || NET4_0 protected void AssertZipFileContents(string fileName, string contents, Encoding encoding) { if (!File.Exists(fileName)) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); using (var zip = new Ionic.Zip.ZipFile(fileName)) { Assert.Equal(1, zip.Count); Assert.Equal(encodedBuf.Length, zip[0].UncompressedSize); byte[] buf = new byte[zip[0].UncompressedSize]; using (var fs = zip[0].OpenReader()) { fs.Read(buf, 0, buf.Length); } for (int i = 0; i < buf.Length; ++i) { Assert.Equal(encodedBuf[i], buf[i]); } } } #elif NET4_5 protected void AssertZipFileContents(string fileName, string contents, Encoding encoding) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var zip = new ZipArchive(stream, ZipArchiveMode.Read)) { Assert.Single(zip.Entries); Assert.Equal(encodedBuf.Length, zip.Entries[0].Length); byte[] buf = new byte[(int)zip.Entries[0].Length]; using (var fs = zip.Entries[0].Open()) { fs.Read(buf, 0, buf.Length); } for (int i = 0; i < buf.Length; ++i) { Assert.Equal(encodedBuf[i], buf[i]); } } } #else protected void AssertZipFileContents(string fileName, string contents, Encoding encoding) { Assert.True(false); } #endif protected void AssertFileContents(string fileName, string contents, Encoding encoding) { AssertFileContents(fileName, contents, encoding, false); } protected void AssertFileContents(string fileName, string contents, Encoding encoding, bool addBom) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); //add bom if needed if (addBom) { var preamble = encoding.GetPreamble(); if (preamble.Length > 0) { //insert before encodedBuf = preamble.Concat(encodedBuf).ToArray(); } } byte[] buf = File.ReadAllBytes(fileName); Assert.True(encodedBuf.Length == buf.Length, $"File:{fileName} encodedBytes:{encodedBuf.Length} does not match file.content:{buf.Length}, file.length = {fi.Length}"); for (int i = 0; i < buf.Length; ++i) { if (encodedBuf[i] != buf[i]) Assert.True(encodedBuf[i] == buf[i], $"File:{fileName} content mismatch {(int) encodedBuf[i]} <> {(int) buf[i]} at index {i}"); } } protected void AssertFileContains(string fileName, string contentToCheck, Encoding encoding) { if (contentToCheck.Contains(Environment.NewLine)) Assert.True(false, "Please use only single line string to check."); FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); using (TextReader fs = new StreamReader(fileName, encoding)) { string line; while ((line = fs.ReadLine()) != null) { if (line.Contains(contentToCheck)) return; } } Assert.True(false, "File doesn't contains '" + contentToCheck + "'"); } protected void AssertFileNotContains(string fileName, string contentToCheck, Encoding encoding) { if (contentToCheck.Contains(Environment.NewLine)) Assert.True(false, "Please use only single line string to check."); FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); using (TextReader fs = new StreamReader(fileName, encoding)) { string line; while ((line = fs.ReadLine()) != null) { if (line.Contains(contentToCheck)) Assert.False(true, "File contains '" + contentToCheck + "'"); } } return; } protected string StringRepeat(int times, string s) { StringBuilder sb = new StringBuilder(s.Length * times); for (int i = 0; i < times; ++i) sb.Append(s); return sb.ToString(); } /// <summary> /// Render layout <paramref name="layout"/> with dummy <see cref="LogEventInfo" />and compare result with <paramref name="expected"/>. /// </summary> protected static void AssertLayoutRendererOutput(Layout layout, string expected) { var logEventInfo = LogEventInfo.Create(LogLevel.Info, "loggername", "message"); AssertLayoutRendererOutput(layout, logEventInfo, expected); } /// <summary> /// Render layout <paramref name="layout"/> with <paramref name="logEventInfo"/> and compare result with <paramref name="expected"/>. /// </summary> protected static void AssertLayoutRendererOutput(Layout layout, LogEventInfo logEventInfo, string expected) { layout.Initialize(null); string actual = layout.Render(logEventInfo); layout.Close(); Assert.Equal(expected, actual); } #if NET4_5 /// <summary> /// Get line number of previous line. /// </summary> protected int GetPrevLineNumber([CallerLineNumber] int callingFileLineNumber = 0) { return callingFileLineNumber - 1; } #else /// <summary> /// Get line number of previous line. /// </summary> protected int GetPrevLineNumber() { //fixed value set with #line 100000 return 100001; } #endif public static XmlLoggingConfiguration CreateConfigurationFromString(string configXml) { XmlDocument doc = new XmlDocument(); doc.LoadXml(configXml); string currentDirectory = null; try { currentDirectory = Environment.CurrentDirectory; } catch (SecurityException) { //ignore } return new XmlLoggingConfiguration(doc.DocumentElement, currentDirectory); } protected string RunAndCaptureInternalLog(SyncAction action, LogLevel internalLogLevel) { var stringWriter = new Logger(); InternalLogger.LogWriter = stringWriter; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; action(); return stringWriter.ToString(); } /// <summary> /// This class has to be used when outputting from the InternalLogger.LogWriter. /// Just creating a string writer will cause issues, since string writer is not thread safe. /// This can cause issues when calling the ToString() on the text writer, since the underlying stringbuilder /// of the textwriter, has char arrays that gets fucked up by the multiple threads. /// this is a simple wrapper that just locks access to the writer so only one thread can access /// it at a time. /// </summary> private class Logger : TextWriter { private readonly StringWriter writer = new StringWriter(); public override Encoding Encoding => writer.Encoding; #if NETSTANDARD1_5 public override void Write(char value) { lock (this.writer) { this.writer.Write(value); } } #endif public override void Write(string value) { lock (writer) { writer.Write(value); } } public override void WriteLine(string value) { lock (writer) { writer.WriteLine(value); } } public override string ToString() { lock (writer) { return writer.ToString(); } } } /// <summary> /// Creates <see cref="CultureInfo"/> instance for test purposes /// </summary> /// <param name="cultureName">Culture name to create</param> /// <remarks> /// Creates <see cref="CultureInfo"/> instance with non-userOverride /// flag to provide expected results when running tests in different /// system cultures(with overriden culture options) /// </remarks> protected static CultureInfo GetCultureInfo(string cultureName) { return new CultureInfo(cultureName, false); } /// <summary> /// Are we running on Travis? /// </summary> /// <returns></returns> protected static bool IsTravis() { var val = Environment.GetEnvironmentVariable("TRAVIS"); return val != null && val.Equals("true", StringComparison.OrdinalIgnoreCase); } /// <summary> /// Are we running on AppVeyor? /// </summary> /// <returns></returns> protected static bool IsAppVeyor() { var val = Environment.GetEnvironmentVariable("APPVEYOR"); return val != null && val.Equals("true", StringComparison.OrdinalIgnoreCase); } public delegate void SyncAction(); public class InternalLoggerScope : IDisposable { private readonly TextWriter oldConsoleOutputWriter; public StringWriter ConsoleOutputWriter { get; private set; } private readonly TextWriter oldConsoleErrorWriter; public StringWriter ConsoleErrorWriter { get; private set; } private readonly LogLevel globalThreshold; private readonly bool throwExceptions; private readonly bool? throwConfigExceptions; public InternalLoggerScope(bool redirectConsole = false) { if (redirectConsole) { ConsoleOutputWriter = new StringWriter() { NewLine = "\n" }; ConsoleErrorWriter = new StringWriter() { NewLine = "\n" }; oldConsoleOutputWriter = Console.Out; oldConsoleErrorWriter = Console.Error; Console.SetOut(ConsoleOutputWriter); Console.SetError(ConsoleErrorWriter); } globalThreshold = LogManager.GlobalThreshold; throwExceptions = LogManager.ThrowExceptions; throwConfigExceptions = LogManager.ThrowConfigExceptions; } public void SetConsoleError(StringWriter consoleErrorWriter) { if (ConsoleOutputWriter == null || consoleErrorWriter == null) throw new InvalidOperationException("Initialize with redirectConsole=true"); ConsoleErrorWriter = consoleErrorWriter; Console.SetError(consoleErrorWriter); } public void SetConsoleOutput(StringWriter consoleOutputWriter) { if (ConsoleOutputWriter == null || consoleOutputWriter == null) throw new InvalidOperationException("Initialize with redirectConsole=true"); ConsoleOutputWriter = consoleOutputWriter; Console.SetOut(consoleOutputWriter); } public void Dispose() { InternalLogger.Reset(); if (ConsoleOutputWriter != null) Console.SetOut(oldConsoleOutputWriter); if (ConsoleErrorWriter != null) Console.SetError(oldConsoleErrorWriter); if (File.Exists(InternalLogger.LogFile)) File.Delete(InternalLogger.LogFile); //restore logmanager LogManager.GlobalThreshold = globalThreshold; LogManager.ThrowExceptions = throwExceptions; LogManager.ThrowConfigExceptions = throwConfigExceptions; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Microsoft.VisualStudio.SymReaderInterop; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class CompilationContext { private static readonly SymbolDisplayFormat s_fullNameFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); internal readonly CSharpCompilation Compilation; internal readonly Binder NamespaceBinder; // Internal for test purposes. private readonly MetadataDecoder _metadataDecoder; private readonly MethodSymbol _currentFrame; private readonly ImmutableArray<LocalSymbol> _locals; private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables; private readonly ImmutableHashSet<string> _hoistedParameterNames; private readonly ImmutableArray<LocalSymbol> _localsForBinding; private readonly CSharpSyntaxNode _syntax; private readonly bool _methodNotType; /// <summary> /// Create a context to compile expressions within a method scope. /// Include imports if <paramref name="importStringGroups"/> is set. /// </summary> internal CompilationContext( CSharpCompilation compilation, MetadataDecoder metadataDecoder, MethodSymbol currentFrame, ImmutableArray<LocalSymbol> locals, ImmutableSortedSet<int> inScopeHoistedLocalIndices, ImmutableArray<ImmutableArray<string>> importStringGroups, ImmutableArray<string> externAliasStrings, CSharpSyntaxNode syntax) { Debug.Assert((syntax == null) || (syntax is ExpressionSyntax) || (syntax is LocalDeclarationStatementSyntax)); Debug.Assert(importStringGroups.IsDefault == externAliasStrings.IsDefault); // TODO: syntax.SyntaxTree should probably be added to the compilation, // but it isn't rooted by a CompilationUnitSyntax so it doesn't work (yet). _currentFrame = currentFrame; _syntax = syntax; _methodNotType = !locals.IsDefault; // NOTE: Since this is done within CompilationContext, it will not be cached. // CONSIDER: The values should be the same everywhere in the module, so they // could be cached. // (Catch: what happens in a type context without a method def?) this.Compilation = GetCompilationWithExternAliases(compilation, externAliasStrings); _metadataDecoder = metadataDecoder; // Each expression compile should use a unique compilation // to ensure expression-specific synthesized members can be // added (anonymous types, for instance). Debug.Assert(this.Compilation != compilation); this.NamespaceBinder = CreateBinderChain( this.Compilation, currentFrame.ContainingNamespace, importStringGroups, _metadataDecoder); if (_methodNotType) { _locals = locals; ImmutableArray<string> displayClassVariableNamesInOrder; GetDisplayClassVariables( currentFrame, _locals, inScopeHoistedLocalIndices, out displayClassVariableNamesInOrder, out _displayClassVariables, out _hoistedParameterNames); Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count); _localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables); } else { _locals = ImmutableArray<LocalSymbol>.Empty; _displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; _localsForBinding = ImmutableArray<LocalSymbol>.Empty; } // Assert that the cheap check for "this" is equivalent to the expensive check for "this". Debug.Assert( _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()) == _displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This)); } internal CommonPEModuleBuilder CompileExpression( InspectionContext inspectionContext, string typeName, string methodName, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics, out ResultProperties resultProperties) { Debug.Assert(inspectionContext != null); var properties = default(ResultProperties); var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( this.Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, typeName, methodName, this, (method, diags) => { var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()); var binder = ExtendBinderChain( inspectionContext, this.Compilation, _metadataDecoder, _syntax, method, this.NamespaceBinder, hasDisplayClassThis, _methodNotType); var statementSyntax = _syntax as StatementSyntax; return (statementSyntax == null) ? BindExpression(binder, (ExpressionSyntax)_syntax, diags, out properties) : BindStatement(binder, statementSyntax, diags, out properties); }); var module = CreateModuleBuilder( this.Compilation, synthesizedType.Methods, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), testData: testData, diagnostics: diagnostics); Debug.Assert(module != null); this.Compilation.Compile( module, win32Resources: null, xmlDocStream: null, generateDebugInfo: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: CancellationToken.None); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } // Should be no name mangling since the caller provided explicit names. Debug.Assert(synthesizedType.MetadataName == typeName); Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName); resultProperties = properties; return module; } internal CommonPEModuleBuilder CompileAssignment( InspectionContext inspectionContext, string typeName, string methodName, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics, out ResultProperties resultProperties) { Debug.Assert(inspectionContext != null); var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, typeName, methodName, this, (method, diags) => { var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()); var binder = ExtendBinderChain( inspectionContext, this.Compilation, _metadataDecoder, _syntax, method, this.NamespaceBinder, hasDisplayClassThis, methodNotType: true); return BindAssignment(binder, (ExpressionSyntax)_syntax, diags); }); var module = CreateModuleBuilder( this.Compilation, synthesizedType.Methods, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), testData: testData, diagnostics: diagnostics); Debug.Assert(module != null); this.Compilation.Compile( module, win32Resources: null, xmlDocStream: null, generateDebugInfo: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: CancellationToken.None); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } // Should be no name mangling since the caller provided explicit names. Debug.Assert(synthesizedType.MetadataName == typeName); Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName); resultProperties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect); return module; } private static string GetNextMethodName(ArrayBuilder<MethodSymbol> builder) { return string.Format("<>m{0}", builder.Count); } /// <summary> /// Generate a class containing methods that represent /// the set of arguments and locals at the current scope. /// </summary> internal CommonPEModuleBuilder CompileGetLocals( string typeName, ArrayBuilder<LocalAndMethod> localBuilder, bool argumentsOnly, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics) { var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object); var allTypeParameters = _currentFrame.GetAllTypeParameters(); var additionalTypes = ArrayBuilder<NamedTypeSymbol>.GetInstance(); EENamedTypeSymbol typeVariablesType = null; if (!argumentsOnly && (allTypeParameters.Length > 0)) { // Generate a generic type with matching type parameters. // A null instance of the type will be used to represent the // "Type variables" local. typeVariablesType = new EENamedTypeSymbol( this.Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, ExpressionCompilerConstants.TypeVariablesClassName, (m, t) => ImmutableArray.Create<MethodSymbol>(new EEConstructorSymbol(t)), allTypeParameters, (t1, t2) => allTypeParameters.SelectAsArray((tp, i, t) => (TypeParameterSymbol)new SimpleTypeParameterSymbol(t, i, tp.Name), t2)); additionalTypes.Add(typeVariablesType); } var synthesizedType = new EENamedTypeSymbol( this.Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, typeName, (m, container) => { var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance(); if (!argumentsOnly) { // "this" for non-static methods that are not display class methods or // display class methods where the display class contains "<>4__this". if (!m.IsStatic && (!IsDisplayClassType(m.ContainingType) || _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()))) { var methodName = GetNextMethodName(methodBuilder); var method = this.GetThisMethod(container, methodName); localBuilder.Add(new LocalAndMethod("this", methodName, DkmClrCompilationResultFlags.None)); // Note: writable in dev11. methodBuilder.Add(method); } } // Hoisted method parameters (represented as locals in the EE). int ordinal = 0; if (!_hoistedParameterNames.IsEmpty) { foreach (var local in _localsForBinding) { // Since we are showing hoisted method parameters first, the parameters may appear out of order // in the Locals window if only some of the parameters are hoisted. This is consistent with the // behavior of the old EE. var localName = local.Name; if (_hoistedParameterNames.Contains(local.Name)) { AppendLocalAndMethod(localBuilder, methodBuilder, localName, this.GetLocalMethod, container, ordinal, GetLocalResultFlags(local)); } ordinal++; } } // Method parameters (except those that have been hoisted). ordinal = m.IsStatic ? 0 : 1; foreach (var parameter in m.Parameters) { var parameterName = parameter.Name; if (!_hoistedParameterNames.Contains(parameterName)) { AppendLocalAndMethod(localBuilder, methodBuilder, parameterName, this.GetParameterMethod, container, ordinal, DkmClrCompilationResultFlags.None); } ordinal++; } if (!argumentsOnly) { // Locals. ordinal = 0; foreach (var local in _localsForBinding) { var localName = local.Name; if (!_hoistedParameterNames.Contains(localName)) { AppendLocalAndMethod(localBuilder, methodBuilder, localName, this.GetLocalMethod, container, ordinal, GetLocalResultFlags(local)); } ordinal++; } // "Type variables". if ((object)typeVariablesType != null) { var methodName = GetNextMethodName(methodBuilder); var returnType = typeVariablesType.Construct(allTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>()); var method = this.GetTypeVariablesMethod(container, methodName, returnType); localBuilder.Add(new LocalAndMethod(ExpressionCompilerConstants.TypeVariablesLocalName, methodName, DkmClrCompilationResultFlags.ReadOnlyResult)); methodBuilder.Add(method); } } return methodBuilder.ToImmutableAndFree(); }); additionalTypes.Add(synthesizedType); var module = CreateModuleBuilder( this.Compilation, synthesizedType.Methods, additionalTypes: additionalTypes.ToImmutableAndFree(), testData: testData, diagnostics: diagnostics); Debug.Assert(module != null); this.Compilation.Compile( module, win32Resources: null, xmlDocStream: null, generateDebugInfo: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: CancellationToken.None); return diagnostics.HasAnyErrors() ? null : module; } private static void AppendLocalAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, string name, Func<EENamedTypeSymbol, string, string, int, MethodSymbol> getMethod, EENamedTypeSymbol container, int ordinal, DkmClrCompilationResultFlags resultFlags) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. name = SyntaxHelpers.EscapeKeywordIdentifiers(name); var methodName = GetNextMethodName(methodBuilder); var method = getMethod(container, methodName, name, ordinal); localBuilder.Add(new LocalAndMethod(name, methodName, resultFlags)); methodBuilder.Add(method); } private static EEAssemblyBuilder CreateModuleBuilder( CSharpCompilation compilation, ImmutableArray<MethodSymbol> methods, ImmutableArray<NamedTypeSymbol> additionalTypes, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics) { // Each assembly must have a unique name. var emitOptions = new EmitOptions(outputNameOverride: ExpressionCompilerUtilities.GenerateUniqueName()); string runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics); var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion); return new EEAssemblyBuilder(compilation.SourceAssembly, emitOptions, methods, serializationProperties, additionalTypes, testData); } internal EEMethodSymbol CreateMethod( EENamedTypeSymbol container, string methodName, CSharpSyntaxNode syntax, GenerateMethodBody generateMethodBody) { return new EEMethodSymbol( container, methodName, syntax.Location, _currentFrame, _locals, _localsForBinding, _displayClassVariables, generateMethodBody); } private EEMethodSymbol GetLocalMethod(EENamedTypeSymbol container, string methodName, string localName, int index) { var syntax = SyntaxFactory.IdentifierName(localName); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var local = method.LocalsForBinding[index]; var expression = new BoundLocal(syntax, local, constantValueOpt: local.GetConstantValue(null, null, diagnostics), type: local.Type) { WasCompilerGenerated = true }; return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetParameterMethod(EENamedTypeSymbol container, string methodName, string parameterName, int ordinal) { var syntax = SyntaxFactory.IdentifierName(parameterName); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var parameter = method.Parameters[ordinal]; var expression = new BoundParameter(syntax, parameter) { WasCompilerGenerated = true }; return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetThisMethod(EENamedTypeSymbol container, string methodName) { var syntax = SyntaxFactory.ThisExpression(); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var expression = new BoundThisReference(syntax, GetNonDisplayClassContainer(container.SubstitutedSourceType)) { WasCompilerGenerated = true }; return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetTypeVariablesMethod(EENamedTypeSymbol container, string methodName, NamedTypeSymbol typeVariablesType) { var syntax = SyntaxFactory.IdentifierName(""); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var type = method.TypeMap.SubstituteNamedType(typeVariablesType); var expression = new BoundObjectCreationExpression(syntax, type.InstanceConstructors[0]) { WasCompilerGenerated = true }; var statement = new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; return statement; }); } private static BoundStatement BindExpression(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics, out ResultProperties resultProperties) { var flags = DkmClrCompilationResultFlags.None; // In addition to C# expressions, the native EE also supports // type names which are bound to a representation of the type // (but not System.Type) that the user can expand to see the // base type. Instead, we only allow valid C# expressions. var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } if (MayHaveSideEffectsVisitor.MayHaveSideEffects(expression)) { flags |= DkmClrCompilationResultFlags.PotentialSideEffect; } var expressionType = expression.Type; if ((object)expressionType == null) { expression = binder.CreateReturnConversion( syntax, diagnostics, expression, binder.Compilation.GetSpecialType(SpecialType.System_Object)); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } } else if (expressionType.SpecialType == SpecialType.System_Void) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; Debug.Assert(expression.ConstantValue == null); resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant: false); return new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true }; } else if (expressionType.SpecialType == SpecialType.System_Boolean) { flags |= DkmClrCompilationResultFlags.BoolResult; } if (!IsAssignableExpression(binder, expression)) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; } resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValue != null); return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; } private static BoundStatement BindStatement(Binder binder, StatementSyntax syntax, DiagnosticBag diagnostics, out ResultProperties properties) { properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); return binder.BindStatement(syntax, diagnostics); } private static bool IsAssignableExpression(Binder binder, BoundExpression expression) { // NOTE: Surprisingly, binder.CheckValueKind will return true (!) for readonly fields // in contexts where they cannot be assigned - it simply reports a diagnostic. // Presumably, this is done to avoid producing a confusing error message about the // field not being an lvalue. var diagnostics = DiagnosticBag.GetInstance(); var result = binder.CheckValueKind(expression, Binder.BindValueKind.Assignment, diagnostics) && !diagnostics.HasAnyErrors(); diagnostics.Free(); return result; } private static BoundStatement BindAssignment(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics) { var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue); if (diagnostics.HasAnyErrors()) { return null; } return new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true }; } private static Binder CreateBinderChain( CSharpCompilation compilation, NamespaceSymbol @namespace, ImmutableArray<ImmutableArray<string>> importStringGroups, MetadataDecoder metadataDecoder) { var stack = ArrayBuilder<string>.GetInstance(); while ((object)@namespace != null) { stack.Push(@namespace.Name); @namespace = @namespace.ContainingNamespace; } var binder = (new BuckStopsHereBinder(compilation)).WithAdditionalFlags( BinderFlags.SuppressObsoleteChecks | BinderFlags.SuppressAccessChecks | BinderFlags.UnsafeRegion | BinderFlags.UncheckedRegion | BinderFlags.AllowManagedAddressOf | BinderFlags.AllowAwaitInUnsafeContext); var hasImports = !importStringGroups.IsDefault; var numImportStringGroups = hasImports ? importStringGroups.Length : 0; var currentStringGroup = numImportStringGroups - 1; // PERF: We used to call compilation.GetCompilationNamespace on every iteration, // but that involved walking up to the global namespace, which we have to do // anyway. Instead, we'll inline the functionality into our own walk of the // namespace chain. @namespace = compilation.GlobalNamespace; while (stack.Count > 0) { var namespaceName = stack.Pop(); if (namespaceName.Length > 0) { // We're re-getting the namespace, rather than using the one containing // the current frame method, because we want the merged namespace. @namespace = @namespace.GetNestedNamespace(namespaceName); Debug.Assert((object)@namespace != null, "We worked backwards from symbols to names, but no symbol exists for name '" + namespaceName + "'"); } else { Debug.Assert((object)@namespace == (object)compilation.GlobalNamespace); } Imports imports = null; if (hasImports) { if (currentStringGroup < 0) { Debug.WriteLine("No import string group for namespace '{0}'", @namespace); break; } var importsBinder = new InContainerBinder(@namespace, binder); imports = BuildImports(compilation, importStringGroups[currentStringGroup], importsBinder, metadataDecoder); currentStringGroup--; } binder = new InContainerBinder(@namespace, binder, imports); } stack.Free(); if (currentStringGroup >= 0) { // CONSIDER: We could lump these into the outermost namespace. It's probably not worthwhile since // the usings are already for the wrong method. Debug.WriteLine("Found {0} import string groups without corresponding namespaces", currentStringGroup + 1); } return binder; } private static CSharpCompilation GetCompilationWithExternAliases(CSharpCompilation compilation, ImmutableArray<string> externAliasStrings) { if (externAliasStrings.IsDefaultOrEmpty) { return compilation.Clone(); } var updatedReferences = ArrayBuilder<MetadataReference>.GetInstance(); var assemblyIdentities = ArrayBuilder<AssemblyIdentity>.GetInstance(); foreach (var reference in compilation.References) { var identity = reference.Properties.Kind == MetadataImageKind.Assembly ? ((AssemblySymbol)compilation.GetAssemblyOrModuleSymbol(reference)).Identity : null; assemblyIdentities.Add(identity); updatedReferences.Add(reference); } Debug.Assert(assemblyIdentities.Count == updatedReferences.Count); var comparer = compilation.Options.AssemblyIdentityComparer; var numAssemblies = assemblyIdentities.Count; foreach (var externAliasString in externAliasStrings) { string alias; string externAlias; string target; ImportTargetKind kind; if (!CustomDebugInfoReader.TryParseCSharpImportString(externAliasString, out alias, out externAlias, out target, out kind)) { Debug.WriteLine("Unable to parse extern alias '{0}'", (object)externAliasString); continue; } Debug.Assert(kind == ImportTargetKind.Assembly, "Programmer error: How did a non-assembly get in the extern alias list?"); Debug.Assert(alias == null); // Not used. Debug.Assert(externAlias != null); // Name of the extern alias. Debug.Assert(target != null); // Name of the target assembly. AssemblyIdentity targetIdentity; if (!AssemblyIdentity.TryParseDisplayName(target, out targetIdentity)) { Debug.WriteLine("Unable to parse target of extern alias '{0}'", (object)externAliasString); continue; } int index = -1; for (int i = 0; i < numAssemblies; i++) { var candidateIdentity = assemblyIdentities[i]; if (candidateIdentity != null && comparer.ReferenceMatchesDefinition(targetIdentity, candidateIdentity)) { index = i; break; } } if (index < 0) { Debug.WriteLine("Unable to find corresponding assembly reference for extern alias '{0}'", (object)externAliasString); continue; } var assemblyReference = updatedReferences[index]; var oldAliases = assemblyReference.Properties.Aliases; var newAliases = oldAliases.IsEmpty ? ImmutableArray.Create(MetadataReferenceProperties.GlobalAlias, externAlias) : oldAliases.Concat(ImmutableArray.Create(externAlias)); // NOTE: Dev12 didn't emit custom debug info about "global", so we don't have // a good way to distinguish between a module aliased with both (e.g.) "X" and // "global" and a module aliased with only "X". As in Dev12, we assume that // "global" is a valid alias to remain at least as permissive as source. // NOTE: In the event that this introduces ambiguities between two assemblies // (e.g. because one was "global" in source and the other was "X"), it should be // possible to disambiguate as long as each assembly has a distinct extern alias, // not necessarily used in source. Debug.Assert(newAliases.Contains(MetadataReferenceProperties.GlobalAlias)); // Replace the value in the map with the updated reference. updatedReferences[index] = assemblyReference.WithAliases(newAliases); } compilation = compilation.WithReferences(updatedReferences); assemblyIdentities.Free(); updatedReferences.Free(); return compilation; } private static Binder ExtendBinderChain( InspectionContext inspectionContext, CSharpCompilation compilation, MetadataDecoder metadataDecoder, CSharpSyntaxNode syntax, EEMethodSymbol method, Binder binder, bool hasDisplayClassThis, bool methodNotType) { var substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassThis); var substitutedSourceType = substitutedSourceMethod.ContainingType; var stack = ArrayBuilder<NamedTypeSymbol>.GetInstance(); for (var type = substitutedSourceType; (object)type != null; type = type.ContainingType) { stack.Add(type); } while (stack.Count > 0) { substitutedSourceType = stack.Pop(); binder = new InContainerBinder(substitutedSourceType, binder); if (substitutedSourceType.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceType.TypeArguments, binder); } } stack.Free(); if (substitutedSourceMethod.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceMethod.TypeArguments, binder); } if (methodNotType) { // Method locals and parameters shadow pseudo-variables. binder = new PlaceholderLocalBinder(inspectionContext, new EETypeNameDecoder(compilation, metadataDecoder.ModuleSymbol), syntax, method, binder); } binder = new EEMethodBinder(method, substitutedSourceMethod, binder); if (methodNotType) { binder = new SimpleLocalScopeBinder(method.LocalsForBinding, binder); } return binder; } private static Imports BuildImports(CSharpCompilation compilation, ImmutableArray<string> importStrings, InContainerBinder binder, MetadataDecoder metadataDecoder) { // We make a first pass to extract all of the extern aliases because other imports may depend on them. var externsBuilder = ArrayBuilder<AliasAndExternAliasDirective>.GetInstance(); foreach (var importString in importStrings) { string alias; string externAlias; string target; ImportTargetKind kind; if (!CustomDebugInfoReader.TryParseCSharpImportString(importString, out alias, out externAlias, out target, out kind)) { Debug.WriteLine("Unable to parse import string '{0}'", (object)importString); continue; } else if (kind != ImportTargetKind.Assembly) { continue; } Debug.Assert(alias == null); Debug.Assert(externAlias != null); Debug.Assert(target == null); NameSyntax aliasNameSyntax; if (!SyntaxHelpers.TryParseDottedName(externAlias, out aliasNameSyntax) || aliasNameSyntax.Kind() != SyntaxKind.IdentifierName) { Debug.WriteLine("Import string '{0}' has syntactically invalid extern alias '{1}'", importString, externAlias); continue; } var aliasToken = ((IdentifierNameSyntax)aliasNameSyntax).Identifier; var externAliasSyntax = SyntaxFactory.ExternAliasDirective(aliasToken); var aliasSymbol = new AliasSymbol(binder, externAliasSyntax); // Binder is only used to access compilation. externsBuilder.Add(new AliasAndExternAliasDirective(aliasSymbol, externAliasSyntax)); } var externs = externsBuilder.ToImmutableAndFree(); if (externs.Any()) { // NB: This binder (and corresponding Imports) is only used to bind the other imports. // We'll merge the externs into a final Imports object and return that to be used in // the actual binder chain. binder = new InContainerBinder( binder.Container, binder, Imports.FromCustomDebugInfo(binder.Compilation, new Dictionary<string, AliasAndUsingDirective>(), ImmutableArray<NamespaceOrTypeAndUsingDirective>.Empty, externs)); } var usingAliases = new Dictionary<string, AliasAndUsingDirective>(); var usingsBuilder = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance(); foreach (var importString in importStrings) { string alias; string externAlias; string target; ImportTargetKind kind; if (!CustomDebugInfoReader.TryParseCSharpImportString(importString, out alias, out externAlias, out target, out kind)) { Debug.WriteLine("Unable to parse import string '{0}'", (object)importString); continue; } switch (kind) { case ImportTargetKind.Type: { Debug.Assert(target != null, string.Format("Type import string '{0}' has no target", importString)); Debug.Assert(externAlias == null, string.Format("Type import string '{0}' has an extern alias (should be folded into target)", importString)); TypeSymbol typeSymbol = metadataDecoder.GetTypeSymbolForSerializedType(target); Debug.Assert((object)typeSymbol != null); if (typeSymbol.IsErrorType()) { // Type is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } else if (alias == null && !typeSymbol.IsStatic) { // Only static types can be directly imported. continue; } NameSyntax typeSyntax = SyntaxFactory.ParseName(typeSymbol.ToDisplayString(s_fullNameFormat)); if (!TryAddImport(alias, typeSyntax, typeSymbol, usingsBuilder, usingAliases, binder, importString)) { continue; } break; } case ImportTargetKind.Namespace: { Debug.Assert(target != null, string.Format("Namespace import string '{0}' has no target", importString)); NameSyntax targetSyntax; if (!SyntaxHelpers.TryParseDottedName(target, out targetSyntax)) { // DevDiv #999086: Some previous version of VS apparently generated type aliases as "UA{alias} T{alias-qualified type name}". // Neither Roslyn nor Dev12 parses such imports. However, Roslyn discards them, rather than interpreting them as "UA{alias}" // (which will rarely work and never be correct). Debug.WriteLine("Import string '{0}' has syntactically invalid target '{1}'", importString, target); continue; } if (externAlias != null) { IdentifierNameSyntax externAliasSyntax; if (!TryParseIdentifierNameSyntax(externAlias, out externAliasSyntax)) { Debug.WriteLine("Import string '{0}' has syntactically invalid extern alias '{1}'", importString, externAlias); continue; } // This is the case that requires the binder to already know about extern aliases. targetSyntax = SyntaxHelpers.PrependExternAlias(externAliasSyntax, targetSyntax); } var unusedDiagnostics = DiagnosticBag.GetInstance(); var namespaceSymbol = binder.BindNamespaceOrType(targetSyntax, unusedDiagnostics).ExpressionSymbol as NamespaceSymbol; unusedDiagnostics.Free(); if ((object)namespaceSymbol == null) { // Namespace is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } if (!TryAddImport(alias, targetSyntax, namespaceSymbol, usingsBuilder, usingAliases, binder, importString)) { continue; } break; } case ImportTargetKind.Assembly: { // Handled in first pass (above). break; } default: { throw ExceptionUtilities.UnexpectedValue(kind); } } } return Imports.FromCustomDebugInfo(binder.Compilation, usingAliases, usingsBuilder.ToImmutableAndFree(), externs); } private static bool TryAddImport( string alias, NameSyntax targetSyntax, NamespaceOrTypeSymbol targetSymbol, ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder, Dictionary<string, AliasAndUsingDirective> usingAliases, InContainerBinder binder, string importString) { if (alias == null) { var usingSyntax = SyntaxFactory.UsingDirective(targetSyntax); usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingSyntax)); } else { IdentifierNameSyntax aliasSyntax; if (!TryParseIdentifierNameSyntax(alias, out aliasSyntax)) { Debug.WriteLine("Import string '{0}' has syntactically invalid alias '{1}'", importString, alias); return false; } var usingSyntax = SyntaxFactory.UsingDirective(SyntaxFactory.NameEquals(aliasSyntax), targetSyntax); var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder); usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingSyntax)); } return true; } private static bool TryParseIdentifierNameSyntax(string name, out IdentifierNameSyntax syntax) { Debug.Assert(name != null); if (name == MetadataReferenceProperties.GlobalAlias) { syntax = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); return true; } NameSyntax nameSyntax; if (!SyntaxHelpers.TryParseDottedName(name, out nameSyntax) || nameSyntax.Kind() != SyntaxKind.IdentifierName) { syntax = null; return false; } syntax = (IdentifierNameSyntax)nameSyntax; return true; } internal CommonMessageProvider MessageProvider { get { return this.Compilation.MessageProvider; } } private static DkmClrCompilationResultFlags GetLocalResultFlags(LocalSymbol local) { // CONSIDER: We might want to prevent the user from modifying pinned locals - // that's pretty dangerous. return local.IsConst ? DkmClrCompilationResultFlags.ReadOnlyResult : DkmClrCompilationResultFlags.None; } /// <summary> /// Generate the set of locals to use for binding. /// </summary> private static ImmutableArray<LocalSymbol> GetLocalsForBinding( ImmutableArray<LocalSymbol> locals, ImmutableArray<string> displayClassVariableNamesInOrder, ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { var builder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var local in locals) { var name = local.Name; if (name == null) { continue; } if (GeneratedNames.GetKind(name) != GeneratedNameKind.None) { continue; } // Although Roslyn doesn't name synthesized locals unless they are well-known to EE, // Dev12 did so we need to skip them here. if (GeneratedNames.IsSynthesizedLocalName(name)) { continue; } builder.Add(local); } foreach (var variableName in displayClassVariableNamesInOrder) { var variable = displayClassVariables[variableName]; switch (variable.Kind) { case DisplayClassVariableKind.Local: case DisplayClassVariableKind.Parameter: builder.Add(new EEDisplayClassFieldLocalSymbol(variable)); break; } } return builder.ToImmutableAndFree(); } /// <summary> /// Return a mapping of captured variables (parameters, locals, and /// "this") to locals. The mapping is needed to expose the original /// local identifiers (those from source) in the binder. /// </summary> private static void GetDisplayClassVariables( MethodSymbol method, ImmutableArray<LocalSymbol> locals, ImmutableSortedSet<int> inScopeHoistedLocalIndices, out ImmutableArray<string> displayClassVariableNamesInOrder, out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables, out ImmutableHashSet<string> hoistedParameterNames) { // Calculated the shortest paths from locals to instances of display // classes. There should not be two instances of the same display // class immediately within any particular method. var displayClassTypes = PooledHashSet<NamedTypeSymbol>.GetInstance(); var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance(); // Add any display class instances from locals (these will contain any hoisted locals). foreach (var local in locals) { var name = local.Name; if ((name != null) && (GeneratedNames.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField)) { var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local); displayClassTypes.Add(instance.Type); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } var containingType = method.ContainingType; bool isIteratorOrAsyncMethod = false; if (IsDisplayClassType(containingType)) { if (!method.IsStatic) { // Add "this" display class instance. var instance = new DisplayClassInstanceFromThis(method.ThisParameter); displayClassTypes.Add(instance.Type); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } isIteratorOrAsyncMethod = GeneratedNames.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType; } if (displayClassInstances.Any()) { // Find any additional display class instances breadth first. for (int depth = 0; GetDisplayClassInstances(displayClassTypes, displayClassInstances, depth) > 0; depth++) { } // The locals are the set of all fields from the display classes. var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance(); var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance(); var parameterNames = PooledHashSet<string>.GetInstance(); if (isIteratorOrAsyncMethod) { Debug.Assert(IsDisplayClassType(containingType)); foreach (var field in containingType.GetMembers().OfType<FieldSymbol>()) { // All iterator and async state machine fields (including hoisted locals) have mangled names, except // for hoisted parameters (whose field names are always the same as the original source parameters). var fieldName = field.Name; if (GeneratedNames.GetKind(fieldName) == GeneratedNameKind.None) { parameterNames.Add(fieldName); } } } else { foreach (var p in method.Parameters) { parameterNames.Add(p.Name); } } var pooledHoistedParameterNames = PooledHashSet<string>.GetInstance(); foreach (var instance in displayClassInstances) { GetDisplayClassVariables( displayClassVariableNamesInOrderBuilder, displayClassVariablesBuilder, parameterNames, inScopeHoistedLocalIndices, instance, pooledHoistedParameterNames); } hoistedParameterNames = pooledHoistedParameterNames.ToImmutableHashSet<string>(); pooledHoistedParameterNames.Free(); parameterNames.Free(); displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree(); displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary(); displayClassVariablesBuilder.Free(); } else { hoistedParameterNames = ImmutableHashSet<string>.Empty; displayClassVariableNamesInOrder = ImmutableArray<string>.Empty; displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; } displayClassTypes.Free(); displayClassInstances.Free(); } /// <summary> /// Return the set of display class instances that can be reached /// from the given local. A particular display class may be reachable /// from multiple locals. In those cases, the instance from the /// shortest path (fewest intermediate fields) is returned. /// </summary> private static int GetDisplayClassInstances( HashSet<NamedTypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, int depth) { Debug.Assert(displayClassInstances.All(p => p.Depth <= depth)); var atDepth = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance(); atDepth.AddRange(displayClassInstances.Where(p => p.Depth == depth)); Debug.Assert(atDepth.Count > 0); int n = 0; foreach (var instance in atDepth) { n += GetDisplayClassInstances(displayClassTypes, displayClassInstances, instance); } atDepth.Free(); return n; } private static int GetDisplayClassInstances( HashSet<NamedTypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, DisplayClassInstanceAndFields instance) { // Display class instance. The display class fields are variables. int n = 0; foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldType = field.Type; var fieldKind = GeneratedNames.GetKind(field.Name); if (fieldKind == GeneratedNameKind.DisplayClassLocalOrField || (fieldKind == GeneratedNameKind.ThisProxyField && GeneratedNames.GetKind(fieldType.Name) == GeneratedNameKind.LambdaDisplayClass)) // Async lambda case. { Debug.Assert(!field.IsStatic); // A local that is itself a display class instance. if (displayClassTypes.Add((NamedTypeSymbol)fieldType)) { var other = instance.FromField(field); displayClassInstances.Add(other); n++; } } } return n; } private static void GetDisplayClassVariables( ArrayBuilder<string> displayClassVariableNamesInOrderBuilder, Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder, HashSet<string> parameterNames, ImmutableSortedSet<int> inScopeHoistedLocalIndices, DisplayClassInstanceAndFields instance, HashSet<string> hoistedParameterNames) { // Display class instance. The display class fields are variables. foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldName = field.Name; DisplayClassVariableKind variableKind; string variableName; GeneratedNameKind fieldKind; int openBracketOffset; int closeBracketOffset; GeneratedNames.TryParseGeneratedName(fieldName, out fieldKind, out openBracketOffset, out closeBracketOffset); switch (fieldKind) { case GeneratedNameKind.DisplayClassLocalOrField: // A local that is itself a display class instance. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.HoistedLocalField: // Filter out hoisted locals that are known to be out-of-scope at the current IL offset. // Hoisted locals with invalid indices will be included since more information is better // than less in error scenarios. int slotIndex; if (GeneratedNames.TryParseSlotIndex(fieldName, out slotIndex) && !inScopeHoistedLocalIndices.Contains(slotIndex)) { continue; } variableName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); variableKind = DisplayClassVariableKind.Local; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.ThisProxyField: // A reference to "this". variableName = fieldName; variableKind = DisplayClassVariableKind.This; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.None: // A reference to a parameter or local. variableName = fieldName; if (parameterNames.Contains(variableName)) { variableKind = DisplayClassVariableKind.Parameter; hoistedParameterNames.Add(variableName); } else { variableKind = DisplayClassVariableKind.Local; } Debug.Assert(!field.IsStatic); break; default: continue; } if (displayClassVariablesBuilder.ContainsKey(variableName)) { // Only expecting duplicates for async state machine // fields (that should be at the top-level). Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1); Debug.Assert(instance.Fields.Count() >= 1); // greater depth Debug.Assert(variableKind == DisplayClassVariableKind.Parameter); } else if (variableKind != DisplayClassVariableKind.This || GeneratedNames.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass) { // In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one. // In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one). displayClassVariableNamesInOrderBuilder.Add(variableName); displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field)); } } } private static bool IsDisplayClassType(NamedTypeSymbol type) { switch (GeneratedNames.GetKind(type.Name)) { case GeneratedNameKind.LambdaDisplayClass: case GeneratedNameKind.StateMachineType: return true; default: return false; } } private static NamedTypeSymbol GetNonDisplayClassContainer(NamedTypeSymbol type) { // 1) Display class and state machine types are always nested within the types // that use them (so that they can access private members of those types). // 2) The native compiler used to produce nested display classes for nested lambdas, // so we may have to walk out more than one level. while (IsDisplayClassType(type)) { type = type.ContainingType; } Debug.Assert((object)type != null); return type; } /// <summary> /// Identifies the method in which binding should occur. /// </summary> /// <param name="candidateSubstitutedSourceMethod"> /// The symbol of the method that is currently on top of the callstack, with /// EE type parameters substituted in place of the original type parameters. /// </param> /// <param name="hasDisplayClassThis"> /// True if "this" is available via a display class in the current context. /// </param> /// <returns> /// If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated, /// then we will attempt to determine which user-defined method caused it to be /// generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/> /// is a state machine MoveNext method, then we will try to find the iterator or /// async method for which it was generated. If we are able to find the original /// method, then we will substitute in the EE type parameters. Otherwise, we will /// return <paramref name="candidateSubstitutedSourceMethod"/>. /// </returns> /// <remarks> /// In the event that the original method is overloaded, we may not be able to determine /// which overload actually corresponds to the state machine. In particular, we do not /// have information about the signature of the original method (i.e. number of parameters, /// parameter types and ref-kinds, return type). However, we conjecture that this /// level of uncertainty is acceptable, since parameters are managed by a separate binder /// in the synthesized binder chain and we have enough information to check the other method /// properties that are used during binding (e.g. static-ness, generic arity, type parameter /// constraints). /// </remarks> internal static MethodSymbol GetSubstitutedSourceMethod( MethodSymbol candidateSubstitutedSourceMethod, bool hasDisplayClassThis) { var candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType; string desiredMethodName; if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceType.Name, GeneratedNameKind.StateMachineType, out desiredMethodName) || GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LambdaMethod, out desiredMethodName)) { // We could be in the MoveNext method of an async lambda. string tempMethodName; if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LambdaMethod, out tempMethodName)) { desiredMethodName = tempMethodName; var containing = candidateSubstitutedSourceType.ContainingType; Debug.Assert((object)containing != null); if (GeneratedNames.GetKind(containing.Name) == GeneratedNameKind.LambdaDisplayClass) { candidateSubstitutedSourceType = containing; hasDisplayClassThis = candidateSubstitutedSourceType.MemberNames.Select(GeneratedNames.GetKind).Contains(GeneratedNameKind.ThisProxyField); } } var desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters; // We need to use a ThreeState, rather than a bool, because we can't distinguish between // a roslyn lambda that only captures "this" and a dev12 lambda that captures nothing // (neither introduces a display class). This is unnecessary in the state machine case, // because then "this" is hoisted unconditionally. var isDesiredMethodStatic = hasDisplayClassThis ? ThreeState.False : (GeneratedNames.GetKind(candidateSubstitutedSourceType.Name) == GeneratedNameKind.StateMachineType) ? ThreeState.True : ThreeState.Unknown; // Type containing the original iterator, async, or lambda-containing method. var substitutedSourceType = GetNonDisplayClassContainer(candidateSubstitutedSourceType); foreach (var candidateMethod in substitutedSourceType.GetMembers().OfType<MethodSymbol>()) { if (IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, isDesiredMethodStatic)) { return desiredTypeParameters.Length == 0 ? candidateMethod : candidateMethod.Construct(candidateSubstitutedSourceType.TypeArguments); } } Debug.Assert(false, "Why didn't we find a substituted source method for " + candidateSubstitutedSourceMethod + "?"); } return candidateSubstitutedSourceMethod; } private static bool IsViableSourceMethod(MethodSymbol candidateMethod, string desiredMethodName, ImmutableArray<TypeParameterSymbol> desiredTypeParameters, ThreeState isDesiredMethodStatic) { return !candidateMethod.IsAbstract && (isDesiredMethodStatic == ThreeState.Unknown || isDesiredMethodStatic.Value() == candidateMethod.IsStatic) && candidateMethod.Name == desiredMethodName && HaveSameConstraints(candidateMethod.TypeParameters, desiredTypeParameters); } private static bool HaveSameConstraints(ImmutableArray<TypeParameterSymbol> candidateTypeParameters, ImmutableArray<TypeParameterSymbol> desiredTypeParameters) { int arity = candidateTypeParameters.Length; if (arity != desiredTypeParameters.Length) { return false; } else if (arity == 0) { return true; } var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var candidateTypeMap = new TypeMap(candidateTypeParameters, indexedTypeParameters, allowAlpha: true); var desiredTypeMap = new TypeMap(desiredTypeParameters, indexedTypeParameters, allowAlpha: true); return MemberSignatureComparer.HaveSameConstraints(candidateTypeParameters, candidateTypeMap, desiredTypeParameters, desiredTypeMap); } private struct DisplayClassInstanceAndFields { internal readonly DisplayClassInstance Instance; internal readonly ConsList<FieldSymbol> Fields; internal DisplayClassInstanceAndFields(DisplayClassInstance instance) : this(instance, ConsList<FieldSymbol>.Empty) { Debug.Assert(IsDisplayClassType(instance.Type)); } private DisplayClassInstanceAndFields(DisplayClassInstance instance, ConsList<FieldSymbol> fields) { this.Instance = instance; this.Fields = fields; } internal NamedTypeSymbol Type { get { return this.Fields.Any() ? (NamedTypeSymbol)this.Fields.Head.Type : this.Instance.Type; } } internal int Depth { get { return this.Fields.Count(); } } internal DisplayClassInstanceAndFields FromField(FieldSymbol field) { Debug.Assert(IsDisplayClassType((NamedTypeSymbol)field.Type)); return new DisplayClassInstanceAndFields(this.Instance, this.Fields.Prepend(field)); } internal DisplayClassVariable ToVariable(string name, DisplayClassVariableKind kind, FieldSymbol field) { return new DisplayClassVariable(name, kind, this.Instance, this.Fields.Prepend(field)); } } } }
using EqualsVerifier.Util; using System.Collections.Generic; using System.Reflection; using System.Linq; using System; namespace EqualsVerifier.Checker { public class FieldsChecker<T> : AbstractChecker { readonly ClassAccessor _classAccessor; readonly ISet<Warning> _warningsToSuppress; readonly bool _allFieldsShouldBeUsed; readonly ISet<string> _allFieldsShouldBeUsedExceptions; readonly PrefabValues _prefabValues; public FieldsChecker( ClassAccessor classAccessor, ISet<Warning> warningsToSuppress, bool allFieldsShouldBeUsed, ISet<string> allFieldsShouldBeUsedExceptions) { _classAccessor = classAccessor; _prefabValues = classAccessor.PrefabValues; _warningsToSuppress = new HashSet<Warning>(warningsToSuppress); _allFieldsShouldBeUsed = allFieldsShouldBeUsed; _allFieldsShouldBeUsedExceptions = allFieldsShouldBeUsedExceptions; } public override void Check() { var inspector = new FieldInspector<T>(_classAccessor); if (_classAccessor.DeclaresEquals()) { inspector.Check(new ArrayFieldCheck()); inspector.Check(new FloatAndDoubleFieldCheck()); inspector.Check(new ReflexivityFieldCheck(_classAccessor, _prefabValues, _warningsToSuppress)); } if (!IgnoreMutability()) { inspector.Check(new MutableStateFieldCheck(_prefabValues)); } inspector.Check(new SignificantFieldCheck( _classAccessor, _prefabValues, _allFieldsShouldBeUsed, _allFieldsShouldBeUsedExceptions)); inspector.Check(new SymmetryFieldCheck(_prefabValues)); inspector.Check(new TransitivityFieldCheck(_prefabValues)); } bool IgnoreMutability() { return _warningsToSuppress.Contains(Warning.NONFINAL_FIELDS) || _classAccessor.HasAttribute(SupportedAttributes.IMMUTABLE); } class SymmetryFieldCheck : IFieldCheck { readonly PrefabValues _prefabValues; public SymmetryFieldCheck(PrefabValues prefabValues) { _prefabValues = prefabValues; } public void Execute(FieldAccessor referenceAccessor, FieldAccessor changedAccessor) { CheckSymmetry(referenceAccessor, changedAccessor); changedAccessor.ChangeField(_prefabValues); CheckSymmetry(referenceAccessor, changedAccessor); referenceAccessor.ChangeField(_prefabValues); CheckSymmetry(referenceAccessor, changedAccessor); } static void CheckSymmetry(FieldAccessor referenceAccessor, FieldAccessor changedAccessor) { var left = referenceAccessor.Object; var right = changedAccessor.Object; AssertTrue( ObjectFormatter.Of("Symmetry: objects are not symmetric:\n %%\nand\n %%", left, right), left.Equals(right) == right.Equals(left)); } } class TransitivityFieldCheck: IFieldCheck { readonly PrefabValues _prefabValues; public TransitivityFieldCheck(PrefabValues prefabValues) { _prefabValues = prefabValues; } public void Execute(FieldAccessor referenceAccessor, FieldAccessor changedAccessor) { var a1 = referenceAccessor.Object; var b1 = BuildB1(changedAccessor); var b2 = BuildB2(a1, referenceAccessor.Field); var x = a1.Equals(b1); var y = b1.Equals(b2); var z = a1.Equals(b2); if (CountFalses(x, y, z) == 1) { TestFrameworkBridge.Fail(ObjectFormatter.Of( "Transitivity: two of these three instances are equal to each other, so the third one should be, too:\n- %%\n- %%\n- %%", a1, b1, b2)); } } object BuildB1(FieldAccessor accessor) { accessor.ChangeField(_prefabValues); return accessor.Object; } object BuildB2(object a1, FieldInfo referenceField) { var result = ObjectAccessor.Of(a1).Copy(); var objectAccessor = ObjectAccessor.Of(result); objectAccessor.FieldAccessorFor(referenceField).ChangeField(_prefabValues); foreach (var field in FieldEnumerable.Of(result.GetType())) { if (!field.Equals(referenceField)) objectAccessor.FieldAccessorFor(field).ChangeField(_prefabValues); } return result; } static int CountFalses(params bool[] bools) { return bools.Count(b => !b); } } class SignificantFieldCheck : IFieldCheck { readonly PrefabValues _prefabValues; readonly bool _allFieldsShouldBeUsed; readonly ISet<string> _allFieldsShouldBeUsedExceptions; readonly ClassAccessor _classAccessor; public SignificantFieldCheck( ClassAccessor classAccessor, PrefabValues prefabValues, bool allFieldsShouldBeUsed, ISet<string> allFieldsShouldBeUsedExceptions) { _classAccessor = classAccessor; _prefabValues = prefabValues; _allFieldsShouldBeUsed = allFieldsShouldBeUsed; _allFieldsShouldBeUsedExceptions = allFieldsShouldBeUsedExceptions; } public void Execute(FieldAccessor referenceAccessor, FieldAccessor changedAccessor) { var reference = referenceAccessor.Object; var changed = changedAccessor.Object; var fieldName = referenceAccessor.FieldName; changedAccessor.ChangeField(_prefabValues); var equalsChanged = !reference.Equals(changed); var hashCodeChanged = reference.GetHashCode() != changed.GetHashCode(); if (equalsChanged != hashCodeChanged) { AssertFalse( ObjectFormatter.Of( "Significant fields: Equals relies on %%, but GetHashCode does not.", fieldName), equalsChanged); AssertFalse(ObjectFormatter.Of( "Significant fields: GetHashCode relies on %%, but Equals does not.", fieldName), hashCodeChanged); } if (_allFieldsShouldBeUsed && !referenceAccessor.IsStatic) { var thisFieldShouldBeUsed = _allFieldsShouldBeUsed && !_allFieldsShouldBeUsedExceptions.Contains(fieldName); AssertTrue( ObjectFormatter.Of("Significant fields: Equals does not use %%.", fieldName), !thisFieldShouldBeUsed || equalsChanged); AssertTrue(ObjectFormatter.Of( "Significant fields: Equals should not use %%, but it does.", fieldName), thisFieldShouldBeUsed || !equalsChanged); if (_classAccessor.DeclaresField(referenceAccessor.Field)) { AssertTrue( ObjectFormatter.Of( "Significant fields: all fields should be used, but %% has not defined an Equals method.", _classAccessor.Type.Name), _classAccessor.DeclaresEquals()); } } referenceAccessor.ChangeField(_prefabValues); } } class ArrayFieldCheck: IFieldCheck { public void Execute(FieldAccessor referenceAccessor, FieldAccessor changedAccessor) { var arrayType = referenceAccessor.FieldType; if (!arrayType.IsArray) return; var fieldName = referenceAccessor.FieldName; var reference = referenceAccessor.Object; var changed = changedAccessor.Object; ReplaceInnermostArrayValue(changedAccessor); if (arrayType.GetElementType().IsArray) { AssertDeep(fieldName, reference, changed); } else { AssertArray(fieldName, reference, changed); } } void ReplaceInnermostArrayValue(FieldAccessor accessor) { var newArray = ArrayCopy(accessor.Get()); accessor.Set(newArray); } object ArrayCopy(object arrayObject) { var array = ArrayExtensions.ToArray(arrayObject); var componentType = arrayObject.GetType().GetElementType(); var result = Array.CreateInstance(componentType, 1); if (componentType.IsArray) { result.SetValue(ArrayCopy(array.GetValue(0)), 0); } else { result.SetValue(array.GetValue(0), 0); } return result; } static void AssertDeep(string fieldName, object reference, object changed) { TestFrameworkBridge.AssertEquals( ObjectFormatter.Of( "Multidimensional array: == or regular Equals() used for field %%.", fieldName), reference, changed); TestFrameworkBridge.AssertEquals( ObjectFormatter.Of( "Multidimensional array: regular GetHashCode() used for field %%.", fieldName), reference.GetHashCode(), changed.GetHashCode()); } static void AssertArray(string fieldName, object reference, object changed) { TestFrameworkBridge.AssertEquals( ObjectFormatter.Of( "Array: == or regular Equals() used for field %%.", fieldName), reference, changed); TestFrameworkBridge.AssertEquals( ObjectFormatter.Of( "Array: regular GetHashCode() used for field %%.", fieldName), reference.GetHashCode(), changed.GetHashCode()); } } class FloatAndDoubleFieldCheck : IFieldCheck { public void Execute(FieldAccessor referenceAccessor, FieldAccessor changedAccessor) { var type = referenceAccessor.FieldType; if (IsFloat(type)) { referenceAccessor.Set(float.NaN); changedAccessor.Set(float.NaN); TestFrameworkBridge.AssertEquals( ObjectFormatter.Of( "Float: Equals uses reference comparison for field %%.", referenceAccessor.FieldName), referenceAccessor.Object, changedAccessor.Object); } if (IsDouble(type)) { referenceAccessor.Set(double.NaN); changedAccessor.Set(double.NaN); TestFrameworkBridge.AssertEquals( ObjectFormatter.Of( "Double: Equals uses reference comparison for field %%.", referenceAccessor.FieldName), referenceAccessor.Object, changedAccessor.Object); } } static bool IsFloat(Type type) { return type == typeof(float); } static bool IsDouble(Type type) { return type == typeof(double); } } class ReflexivityFieldCheck : IFieldCheck { readonly ClassAccessor _classAccessor; readonly ISet<Warning> _warningsToSuppress; readonly PrefabValues _prefabValues; public ReflexivityFieldCheck( ClassAccessor classAccessor, PrefabValues prefabValues, ISet<Warning> warningsToSuppress) { _classAccessor = classAccessor; _prefabValues = prefabValues; _warningsToSuppress = warningsToSuppress; } public void Execute(FieldAccessor referenceAccessor, FieldAccessor changedAccessor) { if (_warningsToSuppress.Contains(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY)) return; referenceAccessor.ChangeField(_prefabValues); changedAccessor.ChangeField(_prefabValues); CheckReflexivityFor(referenceAccessor, changedAccessor); var fieldIsPrimitive = referenceAccessor.IsPrimitive; var fieldIsNonNull = _classAccessor.FieldHasAttribute( referenceAccessor.Field, SupportedAttributes.NONNULL); var ignoreNull = fieldIsNonNull || _warningsToSuppress.Contains(Warning.NULL_FIELDS); if (fieldIsPrimitive || !ignoreNull) { referenceAccessor.DefaultField(); changedAccessor.DefaultField(); CheckReflexivityFor(referenceAccessor, changedAccessor); } } void CheckReflexivityFor(FieldAccessor referenceAccessor, FieldAccessor changedAccessor) { var left = referenceAccessor.Object; var right = changedAccessor.Object; if (_warningsToSuppress.Contains(Warning.IDENTICAL_COPY)) { TestFrameworkBridge.AssertFalse( ObjectFormatter.Of( "Unnecessary suppression: %%. Two identical copies are equal.", Warning.IDENTICAL_COPY.ToString()), left.Equals(right)); } else { var f = ObjectFormatter.Of( "Reflexivity: object does not equal an identical copy of itself:\n %%" + "\nIf this is intentional, consider suppressing Warning.%%", left, Warning.IDENTICAL_COPY.ToString()); TestFrameworkBridge.AssertEquals(f, left, right); } } } class MutableStateFieldCheck : IFieldCheck { readonly PrefabValues _prefabValues; public MutableStateFieldCheck(PrefabValues prefabValues) { _prefabValues = prefabValues; } public void Execute(FieldAccessor referenceAccessor, FieldAccessor changedAccessor) { var reference = referenceAccessor.Object; var changed = changedAccessor.Object; changedAccessor.ChangeField(_prefabValues); var equalsChanged = !reference.Equals(changed); if (equalsChanged && !referenceAccessor.IsReadonly) { TestFrameworkBridge.Fail( ObjectFormatter.Of( "Mutability: equals depends on mutable field %%.", referenceAccessor.FieldName)); } referenceAccessor.ChangeField(_prefabValues); } } } }
#if NO_NATIVESHA1 using System; using NBitcoin.BouncyCastle.Crypto.Utilities; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Digests { /** * implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349. * * It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5 * is the "endianness" of the word processing! */ internal class Sha1Digest : GeneralDigest { private const int DigestLength = 20; private uint H1, H2, H3, H4, H5; private uint[] X = new uint[80]; private int xOff; public Sha1Digest() { Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Sha1Digest(Sha1Digest t) : base(t) { CopyIn(t); } private void CopyIn(Sha1Digest t) { base.CopyIn(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "SHA-1"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff] = Pack.BE_To_UInt32(input, inOff); if (++xOff == 16) { ProcessBlock(); } } internal override void ProcessLength(long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (uint)((ulong)bitLength >> 32); X[15] = (uint)((ulong)bitLength); } public override int DoFinal( byte[] output, int outOff) { Finish(); Pack.UInt32_To_BE(H1, output, outOff); Pack.UInt32_To_BE(H2, output, outOff + 4); Pack.UInt32_To_BE(H3, output, outOff + 8); Pack.UInt32_To_BE(H4, output, outOff + 12); Pack.UInt32_To_BE(H5, output, outOff + 16); Reset(); return DigestLength; } /** * reset the chaining variables */ public override void Reset() { base.Reset(); H1 = 0x67452301; H2 = 0xefcdab89; H3 = 0x98badcfe; H4 = 0x10325476; H5 = 0xc3d2e1f0; xOff = 0; Array.Clear(X, 0, X.Length); } // // Additive constants // private const uint Y1 = 0x5a827999; private const uint Y2 = 0x6ed9eba1; private const uint Y3 = 0x8f1bbcdc; private const uint Y4 = 0xca62c1d6; private static uint F(uint u, uint v, uint w) { return (u & v) | (~u & w); } private static uint H(uint u, uint v, uint w) { return u ^ v ^ w; } private static uint G(uint u, uint v, uint w) { return (u & v) | (u & w) | (v & w); } internal override void ProcessBlock() { // // expand 16 word block into 80 word block. // for (int i = 16; i < 80; i++) { uint t = X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16]; X[i] = t << 1 | t >> 31; } // // set up working variables. // uint A = H1; uint B = H2; uint C = H3; uint D = H4; uint E = H5; // // round 1 // int idx = 0; for (int j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + F(B, C, D) + E + X[idx++] + Y1 // B = rotateLeft(B, 30) E += (A << 5 | (A >> 27)) + F(B, C, D) + X[idx++] + Y1; B = B << 30 | (B >> 2); D += (E << 5 | (E >> 27)) + F(A, B, C) + X[idx++] + Y1; A = A << 30 | (A >> 2); C += (D << 5 | (D >> 27)) + F(E, A, B) + X[idx++] + Y1; E = E << 30 | (E >> 2); B += (C << 5 | (C >> 27)) + F(D, E, A) + X[idx++] + Y1; D = D << 30 | (D >> 2); A += (B << 5 | (B >> 27)) + F(C, D, E) + X[idx++] + Y1; C = C << 30 | (C >> 2); } // // round 2 // for (int j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y2 // B = rotateLeft(B, 30) E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y2; B = B << 30 | (B >> 2); D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y2; A = A << 30 | (A >> 2); C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y2; E = E << 30 | (E >> 2); B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y2; D = D << 30 | (D >> 2); A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y2; C = C << 30 | (C >> 2); } // // round 3 // for (int j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + G(B, C, D) + E + X[idx++] + Y3 // B = rotateLeft(B, 30) E += (A << 5 | (A >> 27)) + G(B, C, D) + X[idx++] + Y3; B = B << 30 | (B >> 2); D += (E << 5 | (E >> 27)) + G(A, B, C) + X[idx++] + Y3; A = A << 30 | (A >> 2); C += (D << 5 | (D >> 27)) + G(E, A, B) + X[idx++] + Y3; E = E << 30 | (E >> 2); B += (C << 5 | (C >> 27)) + G(D, E, A) + X[idx++] + Y3; D = D << 30 | (D >> 2); A += (B << 5 | (B >> 27)) + G(C, D, E) + X[idx++] + Y3; C = C << 30 | (C >> 2); } // // round 4 // for (int j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y4 // B = rotateLeft(B, 30) E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y4; B = B << 30 | (B >> 2); D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y4; A = A << 30 | (A >> 2); C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y4; E = E << 30 | (E >> 2); B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y4; D = D << 30 | (D >> 2); A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y4; C = C << 30 | (C >> 2); } H1 += A; H2 += B; H3 += C; H4 += D; H5 += E; // // reset start of the buffer. // xOff = 0; Array.Clear(X, 0, 16); } #if !NO_BC public override IMemoable Copy() { return new Sha1Digest(this); } public override void Reset(IMemoable other) { Sha1Digest d = (Sha1Digest)other; CopyIn(d); } #endif } } #endif
// HotKeyConfig.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using CoreUtilities; using System.Windows.Forms; using System.Collections.Generic; using System.IO; using database; using HotKeys; namespace appframe { public class HotKeyConfig: iConfig, IDisposable { #region const const string TableName = "hotkeys"; const string columnGUID ="guid"; const string columnID = "id"; const string columnKeyModifier="keymodifier"; const string columnKey="key"; const int columnCount= 4; #endregion #region variables // if true on save we know it is safe to try to save (because interface exists) bool PanelWasMade = false; public string ConfigName { get { return Loc.Instance.GetString ("Hotkeys");} } List<KeyData> HotKeys = null; string DatabaseName; Panel configPanel; #endregion #region delegates MainFormBase.GetAValidDatabase GetBaseDatabase=null; #endregion #region interface #endregion public void Dispose () { if (configPanel != null) { configPanel.Dispose(); } } BaseDatabase CreateDatabase (string DatabaseName) { BaseDatabase db = GetBaseDatabase(DatabaseName); // BaseDatabase db = new SqlLiteDatabase (DatabaseName); //BaseDatabase db = Layout.MasterOfLayouts.GetDatabaseType(DatabaseName); db.CreateTableIfDoesNotExist (TableName, new string[columnCount] {columnID, columnGUID, columnKeyModifier, columnKey}, new string[columnCount] { "INTEGER", "TEXT","TEXT","TEXT" }, "id" ); return db; } public List<KeyData> GetListOfModifiedKeys (string DatabaseName) { BaseDatabase db = CreateDatabase (DatabaseName); List<object[]> myList = db.GetValues (TableName, new string[3] {columnGUID, columnKeyModifier, columnKey}, "any", "*"); // convert list into something nicer List<KeyData> newList = new List<KeyData> (); foreach (object[] o in myList) { if (o.Length == columnCount-1) { // we only care about KeyModifier and Key KeyData keysy= new KeyData("", null,(Keys) Enum.Parse (typeof(Keys), o[1].ToString ()), (Keys) Enum.Parse (typeof(Keys),o[2].ToString ()), "", false, o[0].ToString ()); newList.Add (keysy); } } db.Dispose (); return newList; } /// <summary> /// Updates the keys. This is similar to RebuildListOfKeys but is called on Application /// load to handle modification of the keys. /// /// THIS Will override any TEMPORARY modifications made by RebuildListOfKeys (as long as it is called when the form is closed) /// </summary> public void UpdateKeys (List<KeyData> HotKeys, string DatabaseName) { List<KeyData> ModifiedKeys = GetListOfModifiedKeys (DatabaseName); foreach (KeyData keysy in HotKeys) { KeyData keyModified = ModifiedKeys.Find (KeyData => KeyData.GetGUID () == keysy.GetGUID ()); if (keyModified != null) { // we have an overriden key keysy.Key = keyModified.Key; keysy.ModifyingKey = keyModified.ModifyingKey; } } } private void RebuildListOfKeys () { configPanel.Controls.Clear (); HotKeys.Sort (); List<KeyData> ModifiedKeys = GetListOfModifiedKeys (DatabaseName); //NewMessage.Show (HotKeys.Count.ToString()); foreach (KeyData keysy in HotKeys) { KeyData keyModified = ModifiedKeys.Find (KeyData => KeyData.GetGUID () == keysy.GetGUID ()); if (keyModified != null) { // we have an overriden key keysy.Key = keyModified.Key; keysy.ModifyingKey = keyModified.ModifyingKey; } VisualKey keyPanel = new VisualKey (keysy, MainFormBase.MainFormIcon, AfterKeyEdit); // apply any overrides from database storage configPanel.Controls.Add (keyPanel); keyPanel.Dock = DockStyle.Top; } Button Reset = new Button(); Reset.Text = Loc.Instance.GetString ("Reset"); Reset.Dock = DockStyle.Top; Reset.Click+= HandleResetClick; configPanel.Controls.Add (Reset); Reset.BringToFront(); CheckForErrors (); } void HandleResetClick (object sender, EventArgs e) { if (NewMessage.Show (Loc.Instance.GetString ("Reset Hotkeys?"), Loc.Instance.GetStringFmt ("If you do this you will lose any custom hotkey assignments."), MessageBoxButtons.YesNo, null) == DialogResult.Yes) { BaseDatabase db = CreateDatabase (DatabaseName); db.DropTableIfExists (TableName); db.Dispose (); // okay to call Rebuild because we have wiped modification data RebuildListOfKeys (); } } public int Duplicates=0; void CheckForErrors() { Duplicates =0; // update for duplicates? System.Collections.Hashtable hash = new System.Collections.Hashtable(); foreach (Control control in configPanel.Controls) { if (control is VisualKey) { ((VisualKey)control).IsDuplicate(false); if (hash[((VisualKey)control).UniqueCode()] != null) { Duplicates++; // this combination already exist. ((VisualKey)control).IsDuplicate(true); } else // how to know if we have a duplicate? A simple hash, if key already present? hash.Add(((VisualKey)control).UniqueCode(),"present"); } } } void AfterKeyEdit (string GUID) { CheckForErrors (); // this does not make sense now that we are not storing until a SAVE... we need to use the GUI // KeyData keyDuplicate = ModifiedKeys.Find ( (KeyData => (KeyData.ModifyingKey == keysy.ModifyingKey && KeyData.Key == KeyData.Key)) ); // if (keyDuplicate!= null) // { // keyPanel.IsDuplicate(true); // } // do we need to actually do anything? // for (int i = 0; i < configPanel.Controls.Count; i++) // { // if (configPanel.Controls[i] is VisualKey) // { // if ( ((VisualKey)configPanel.Controls[i]).IsModified == true && ((VisualKey)configPanel.Controls[i]).keyOut != null) // { // if (((VisualKey)configPanel.Controls[i]).keyOut.GetGUID() == GUID) // { // // we have f // } // } // } // } } /// <summary> /// Gets the config panel for AddIns /// </summary> /// <returns> /// The config panel. /// </returns> public Panel GetConfigPanel () { // if panel made then leave it alone // if (PanelWasMade == true) // return configPanel; // unlike other option forms we need to rebuild this each time PanelWasMade = true; configPanel = new Panel (); configPanel.AutoScroll = true; RebuildListOfKeys(); return configPanel; } public HotKeyConfig (string storage, ref List<KeyData> _HotKeys, MainFormBase.GetAValidDatabase _GetBaseDatabase) { HotKeys = _HotKeys; if (Constants.BLANK == storage) { throw new Exception("must specify a nonBlank database name to store the HotKeyModifications inside of."); } GetBaseDatabase = _GetBaseDatabase; DatabaseName = storage; } public void SaveRequested () { BaseDatabase db = CreateDatabase (DatabaseName); // if we did not create the panel then do not waste time trying to save if (false == PanelWasMade) return; for (int i = 0; i < configPanel.Controls.Count; i++) { if (configPanel.Controls[i] is VisualKey) { VisualKey key = (VisualKey)configPanel.Controls [i]; if (true == key.IsModified && key.keyOut != null) { // we have a modified key and it should be stored into the database if (db.Exists (TableName, columnGUID, key.keyOut.GetGUID ())) { // modified existing db.UpdateSpecificColumnData (TableName, new string[columnCount - 1] { columnGUID, columnKeyModifier, columnKey }, new object[columnCount - 1] { key.keyOut.GetGUID (), key.keyOut.ModifyingKey.ToString (), key.keyOut.Key.ToString () }, columnGUID, key.keyOut.GetGUID ()); } else { // add new db.InsertData (TableName, new string[columnCount - 1] { columnGUID, columnKeyModifier, columnKey }, new object[columnCount - 1] { key.keyOut.GetGUID (), key.keyOut.ModifyingKey.ToString (), key.keyOut.Key.ToString () }); } } } } db.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public class X509StoreTests { [Fact] public static void OpenMyStore() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); } } [Fact] public static void Constructor_DefaultStoreName() { using (X509Store store = new X509Store(StoreLocation.CurrentUser)) { Assert.Equal("My", store.Name); } } [Fact] public static void Constructor_DefaultStoreLocation() { using (X509Store store = new X509Store(StoreName.My)) { Assert.Equal(StoreLocation.CurrentUser, store.Location); } using (X509Store store = new X509Store("My")) { Assert.Equal(StoreLocation.CurrentUser, store.Location); } } [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] // Not supported via OpenSSL [Fact] public static void Constructor_StoreHandle() { using (X509Store store1 = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store1.Open(OpenFlags.ReadOnly); bool hadCerts; using (var coll = new ImportedCollection(store1.Certificates)) { // Use >1 instead of >0 in case the one is an ephemeral accident. hadCerts = coll.Collection.Count > 1; Assert.True(coll.Collection.Count >= 0); } using (X509Store store2 = new X509Store(store1.StoreHandle)) { using (var coll = new ImportedCollection(store2.Certificates)) { if (hadCerts) { // Use InRange here instead of True >= 0 so that the error message // is different, and we can diagnose a bit of what state we might have been in. Assert.InRange(coll.Collection.Count, 1, int.MaxValue); } else { Assert.True(coll.Collection.Count >= 0); } } } } } [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] // API not supported via OpenSSL [Fact] public static void Constructor_StoreHandle_Unix() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); Assert.Equal(IntPtr.Zero, store.StoreHandle); } Assert.Throws<PlatformNotSupportedException>(() => new X509Chain(IntPtr.Zero)); } [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] // StoreHandle not supported via OpenSSL [Fact] public static void TestDispose() { X509Store store; using (store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); Assert.NotEqual(IntPtr.Zero, store.StoreHandle); } Assert.Throws<CryptographicException>(() => store.StoreHandle); } [Fact] public static void ReadMyCertificates() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); using (var coll = new ImportedCollection(store.Certificates)) { int certCount = coll.Collection.Count; // This assert is just so certCount appears to be used, the test really // is that store.get_Certificates didn't throw. Assert.True(certCount >= 0); } } } [Fact] public static void OpenNotExistent() { using (X509Store store = new X509Store(Guid.NewGuid().ToString("N"), StoreLocation.CurrentUser)) { Assert.ThrowsAny<CryptographicException>(() => store.Open(OpenFlags.OpenExistingOnly)); } } [Fact] public static void AddReadOnlyThrows() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadOnly); using (var coll = new ImportedCollection(store.Certificates)) { // Add only throws when it has to do work. If, for some reason, this certificate // is already present in the CurrentUser\My store, we can't really test this // functionality. if (!coll.Collection.Contains(cert)) { Assert.ThrowsAny<CryptographicException>(() => store.Add(cert)); } } } } [Fact] public static void AddReadOnlyThrowsWhenCertificateExists() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); X509Certificate2 toAdd = null; // Look through the certificates to find one with no private key to call add on. // (The private key restriction is so that in the event of an "accidental success" // that no potential permissions would be modified) using (var coll = new ImportedCollection(store.Certificates)) { foreach (X509Certificate2 cert in coll.Collection) { if (!cert.HasPrivateKey) { toAdd = cert; break; } } if (toAdd != null) { Assert.ThrowsAny<CryptographicException>(() => store.Add(toAdd)); } } } } [Fact] public static void RemoveReadOnlyThrowsWhenFound() { // This test is unfortunate, in that it will mostly never test. // In order to do so it would have to open the store ReadWrite, put in a known value, // and call Remove on a ReadOnly copy. // // Just calling Remove on the first item found could also work (when the store isn't empty), // but if it fails the cost is too high. // // So what's the purpose of this test, you ask? To record why we're not unit testing it. // And someone could test it manually if they wanted. using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadOnly); using (var coll = new ImportedCollection(store.Certificates)) { if (coll.Collection.Contains(cert)) { Assert.ThrowsAny<CryptographicException>(() => store.Remove(cert)); } } } } /* Placeholder information for these tests until they can be written to run reliably. * Currently such tests would create physical files (Unix) and\or certificates (Windows) * which can collide with other running tests that use the same cert, or from a * test suite running more than once at the same time on the same machine. * Ideally, we use a GUID-named store to aoiv collitions with proper cleanup on Unix and Windows * and\or have lower testing hooks or use Microsoft Fakes Framework to redirect * and encapsulate the actual storage logic so it can be tested, along with mock exceptions * to verify exception handling. * See issue https://github.com/dotnet/corefx/issues/12833 * and https://github.com/dotnet/corefx/issues/12223 [Fact] public static void TestAddAndRemove() {} [Fact] public static void TestAddRangeAndRemoveRange() {} */ [Fact] public static void EnumerateClosedIsEmpty() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { int count = store.Certificates.Count; Assert.Equal(0, count); } } [Fact] public static void AddClosedThrows() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { Assert.ThrowsAny<CryptographicException>(() => store.Add(cert)); } } [Fact] public static void RemoveClosedThrows() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { Assert.ThrowsAny<CryptographicException>(() => store.Remove(cert)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] public static void OpenMachineMyStore_Supported() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadOnly); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] public static void OpenMachineMyStore_NotSupported() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { Assert.Throws<PlatformNotSupportedException>(() => store.Open(OpenFlags.ReadOnly)); } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] [InlineData(OpenFlags.ReadOnly, false)] [InlineData(OpenFlags.MaxAllowed, false)] [InlineData(OpenFlags.ReadWrite, true)] public static void OpenMachineRootStore_Permissions(OpenFlags permissions, bool shouldThrow) { using (X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) { if (shouldThrow) { Assert.Throws<PlatformNotSupportedException>(() => store.Open(permissions)); } else { // Assert.DoesNotThrow store.Open(permissions); } } } [Fact] public static void MachineRootStore_NonEmpty() { // This test will fail on systems where the administrator has gone out of their // way to prune the trusted CA list down below this threshold. // // As of 2016-01-25, Ubuntu 14.04 has 169, and CentOS 7.1 has 175, so that'd be // quite a lot of pruning. // // And as of 2016-01-29 we understand the Homebrew-installed root store, with 180. const int MinimumThreshold = 5; using (X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadOnly); using (var storeCerts = new ImportedCollection(store.Certificates)) { int certCount = storeCerts.Collection.Count; Assert.InRange(certCount, MinimumThreshold, int.MaxValue); } } } [Theory] [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] [InlineData(StoreLocation.CurrentUser)] [InlineData(StoreLocation.LocalMachine)] public static void EnumerateDisallowedStore(StoreLocation location) { using (X509Store store = new X509Store(StoreName.Disallowed, location)) { store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); using (var storeCerts = new ImportedCollection(store.Certificates)) { // That's all. We enumerated it. // There might not even be data in it. } } } } }
// Copyright (C) 2004-2007 MySQL AB // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as published by // the Free Software Foundation // // There are special exceptions to the terms and conditions of the GPL // as it is applied to this software. View the full text of the // exception in file EXCEPTIONS in the directory of this software // distribution. // // 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 using System; using System.Data; using System.Data.Common; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using MySql.Data.Common; using MySql.Data.Types; using System.Collections.Specialized; using System.Collections; using System.Text.RegularExpressions; namespace MySql.Data.MySqlClient { internal class SchemaProvider { protected MySqlConnection connection; public static string MetaCollection = "MetaDataCollections"; public SchemaProvider(MySqlConnection connectionToUse) { connection = connectionToUse; } public virtual DataTable GetSchema(string collection, String[] restrictions) { if (connection.State != ConnectionState.Open) throw new MySqlException("GetSchema can only be called on an open connection."); collection = collection.ToLower(); DataTable dt = GetSchemaInternal(collection, restrictions); if (dt == null) throw new MySqlException("Invalid collection name"); return dt; } public virtual DataTable GetDatabases(string[] restrictions) { Regex regex = null; int caseSetting = Int32.Parse(connection.driver.Property("lower_case_table_names")); string sql = "SHOW DATABASES"; // if lower_case_table_names is zero, then case lookup should be sensitive // so we can use LIKE to do the matching. if (caseSetting == 0) { if (restrictions != null && restrictions.Length >= 1) sql = sql + " LIKE '" + restrictions[0] + "'"; } else if (restrictions != null && restrictions.Length >= 1 && restrictions[0] != null) regex = new Regex(restrictions[0], RegexOptions.IgnoreCase); MySqlDataAdapter da = new MySqlDataAdapter(sql, connection); DataTable dt = new DataTable(); da.Fill(dt); DataTable table = new DataTable("Databases"); table.Columns.Add("CATALOG_NAME", typeof (string)); table.Columns.Add("SCHEMA_NAME", typeof (string)); foreach (DataRow row in dt.Rows) { if (caseSetting != 0 && regex != null && !regex.Match(row[0].ToString()).Success) continue; DataRow newRow = table.NewRow(); newRow[1] = row[0]; table.Rows.Add(newRow); } return table; } public virtual DataTable GetTables(string[] restrictions) { DataTable dt = new DataTable("Tables"); dt.Columns.Add("TABLE_CATALOG", typeof (string)); dt.Columns.Add("TABLE_SCHEMA", typeof (string)); dt.Columns.Add("TABLE_NAME", typeof (string)); dt.Columns.Add("TABLE_TYPE", typeof (string)); dt.Columns.Add("ENGINE", typeof (string)); dt.Columns.Add("VERSION", typeof (long)); dt.Columns.Add("ROW_FORMAT", typeof (string)); dt.Columns.Add("TABLE_ROWS", typeof (long)); dt.Columns.Add("AVG_ROW_LENGTH", typeof (long)); dt.Columns.Add("DATA_LENGTH", typeof (long)); dt.Columns.Add("MAX_DATA_LENGTH", typeof (long)); dt.Columns.Add("INDEX_LENGTH", typeof (long)); dt.Columns.Add("DATA_FREE", typeof (long)); dt.Columns.Add("AUTO_INCREMENT", typeof (long)); dt.Columns.Add("CREATE_TIME", typeof (DateTime)); dt.Columns.Add("UPDATE_TIME", typeof (DateTime)); dt.Columns.Add("CHECK_TIME", typeof (DateTime)); dt.Columns.Add("TABLE_COLLATION", typeof (string)); dt.Columns.Add("CHECKSUM", typeof (long)); dt.Columns.Add("CREATE_OPTIONS", typeof (string)); dt.Columns.Add("TABLE_COMMENT", typeof (string)); // we have to new up a new restriction array here since // GetDatabases takes the database in the first slot string[] dbRestriction = new string[4]; if (restrictions != null && restrictions.Length >= 2) dbRestriction[0] = restrictions[1]; DataTable databases = GetDatabases(dbRestriction); if (restrictions != null) Array.Copy(restrictions, dbRestriction, Math.Min(dbRestriction.Length, restrictions.Length)); foreach (DataRow db in databases.Rows) { dbRestriction[1] = db["SCHEMA_NAME"].ToString(); FindTables(dt, dbRestriction); } return dt; } public virtual DataTable GetColumns(string[] restrictions) { DataTable dt = new DataTable("Columns"); dt.Columns.Add("TABLE_CATALOG", typeof (string)); dt.Columns.Add("TABLE_SCHEMA", typeof (string)); dt.Columns.Add("TABLE_NAME", typeof (string)); dt.Columns.Add("COLUMN_NAME", typeof (string)); dt.Columns.Add("ORDINAL_POSITION", typeof (long)); dt.Columns.Add("COLUMN_DEFAULT", typeof (string)); dt.Columns.Add("IS_NULLABLE", typeof (string)); dt.Columns.Add("DATA_TYPE", typeof (string)); dt.Columns.Add("CHARACTER_MAXIMUM_LENGTH", typeof (long)); dt.Columns.Add("CHARACTER_OCTET_LENGTH", typeof (long)); dt.Columns.Add("NUMERIC_PRECISION", typeof (long)); dt.Columns.Add("NUMERIC_SCALE", typeof (long)); dt.Columns.Add("CHARACTER_SET_NAME", typeof (string)); dt.Columns.Add("COLLATION_NAME", typeof (string)); dt.Columns.Add("COLUMN_TYPE", typeof (string)); dt.Columns.Add("COLUMN_KEY", typeof (string)); dt.Columns.Add("EXTRA", typeof (string)); dt.Columns.Add("PRIVILEGES", typeof (string)); dt.Columns.Add("COLUMN_COMMENT", typeof (string)); // we don't allow restricting on table type here string columnName = null; if (restrictions != null && restrictions.Length == 4) { columnName = restrictions[3]; restrictions[3] = null; } DataTable tables = GetTables(restrictions); foreach (DataRow row in tables.Rows) LoadTableColumns(dt, row["TABLE_SCHEMA"].ToString(), row["TABLE_NAME"].ToString(), columnName); return dt; } private void LoadTableColumns(DataTable dt, string schema, string tableName, string columnRestriction) { string sql = String.Format("SHOW FULL COLUMNS FROM `{0}`.`{1}`", schema, tableName); MySqlCommand cmd = new MySqlCommand(sql, connection); int pos = 1; using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { string colName = reader.GetString(0); if (columnRestriction != null && colName != columnRestriction) continue; DataRow row = dt.NewRow(); row["TABLE_CATALOG"] = DBNull.Value; row["TABLE_SCHEMA"] = schema; row["TABLE_NAME"] = tableName; row["COLUMN_NAME"] = colName; row["ORDINAL_POSITION"] = pos++; row["COLUMN_DEFAULT"] = reader.GetValue(5); row["IS_NULLABLE"] = reader.GetString(3); row["DATA_TYPE"] = reader.GetString(1); row["CHARACTER_MAXIMUM_LENGTH"] = DBNull.Value; row["NUMERIC_PRECISION"] = DBNull.Value; row["NUMERIC_SCALE"] = DBNull.Value; row["CHARACTER_SET_NAME"] = reader.GetValue(2); row["COLLATION_NAME"] = row["CHARACTER_SET_NAME"]; row["COLUMN_TYPE"] = reader.GetString(1); row["COLUMN_KEY"] = reader.GetString(4); row["EXTRA"] = reader.GetString(6); row["PRIVILEGES"] = reader.GetString(7); row["COLUMN_COMMENT"] = reader.GetString(8); ParseColumnRow(row); dt.Rows.Add(row); } } } private static void ParseColumnRow(DataRow row) { // first parse the character set name string charset = row["CHARACTER_SET_NAME"].ToString(); int index = charset.IndexOf('_'); if (index != -1) row["CHARACTER_SET_NAME"] = charset.Substring(0, index); // now parse the data type string dataType = row["DATA_TYPE"].ToString(); index = dataType.IndexOf('('); if (index == -1) return; row["DATA_TYPE"] = dataType.Substring(0, index); int stop = dataType.IndexOf(')', index); string dataLen = dataType.Substring(index + 1, stop - (index + 1)); string lowerType = row["DATA_TYPE"].ToString().ToLower(); if (lowerType == "char" || lowerType == "varchar") row["CHARACTER_MAXIMUM_LENGTH"] = dataLen; else { string[] lenparts = dataLen.Split(new char[] {','}); row["NUMERIC_PRECISION"] = lenparts[0]; if (lenparts.Length == 2) row["NUMERIC_SCALE"] = lenparts[1]; } } public virtual DataTable GetIndexes(string[] restrictions) { DataTable dt = new DataTable("Indexes"); dt.Columns.Add("INDEX_CATALOG", typeof (string)); dt.Columns.Add("INDEX_SCHEMA", typeof (string)); dt.Columns.Add("INDEX_NAME", typeof (string)); dt.Columns.Add("TABLE_NAME", typeof (string)); dt.Columns.Add("UNIQUE", typeof (bool)); dt.Columns.Add("PRIMARY", typeof (bool)); // Get the list of tables first int max = restrictions == null ? 4 : restrictions.Length; string[] tableRestrictions = new string[Math.Max(max, 4)]; if (restrictions != null) restrictions.CopyTo(tableRestrictions, 0); tableRestrictions[3] = "BASE TABLE"; DataTable tables = GetTables(tableRestrictions); foreach (DataRow table in tables.Rows) { string sql = String.Format("SHOW INDEX FROM `{0}`.`{1}`", table["TABLE_SCHEMA"], table["TABLE_NAME"]); MySqlDataAdapter da = new MySqlDataAdapter(sql, connection); DataTable indexes = new DataTable(); da.Fill(indexes); foreach (DataRow index in indexes.Rows) { long seq_index = (long) index["SEQ_IN_INDEX"]; if (seq_index != 1) continue; if (restrictions != null && restrictions.Length == 4 && restrictions[3] != null && !index["KEY_NAME"].Equals(restrictions[3])) continue; DataRow row = dt.NewRow(); row["INDEX_CATALOG"] = null; row["INDEX_SCHEMA"] = table["TABLE_SCHEMA"]; row["INDEX_NAME"] = index["KEY_NAME"]; row["TABLE_NAME"] = index["TABLE"]; row["UNIQUE"] = (long) index["NON_UNIQUE"] == 0; row["PRIMARY"] = index["KEY_NAME"].Equals("PRIMARY"); dt.Rows.Add(row); } } return dt; } public virtual DataTable GetIndexColumns(string[] restrictions) { DataTable dt = new DataTable("IndexColumns"); dt.Columns.Add("INDEX_CATALOG", typeof (string)); dt.Columns.Add("INDEX_SCHEMA", typeof (string)); dt.Columns.Add("INDEX_NAME", typeof (string)); dt.Columns.Add("TABLE_NAME", typeof (string)); dt.Columns.Add("COLUMN_NAME", typeof (string)); dt.Columns.Add("ORDINAL_POSITION", typeof (int)); int max = restrictions == null ? 4 : restrictions.Length; string[] tableRestrictions = new string[Math.Max(max, 4)]; if (restrictions != null) restrictions.CopyTo(tableRestrictions, 0); tableRestrictions[3] = "BASE TABLE"; DataTable tables = GetTables(tableRestrictions); foreach (DataRow table in tables.Rows) { string sql = String.Format("SHOW INDEX FROM `{0}`.`{1}`", table["TABLE_SCHEMA"], table["TABLE_NAME"]); MySqlCommand cmd = new MySqlCommand(sql, connection); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { string key_name = GetString(reader, reader.GetOrdinal("KEY_NAME")); string col_name = GetString(reader, reader.GetOrdinal("COLUMN_NAME")); if (restrictions != null) { if (restrictions.Length >= 4 && restrictions[3] != null && key_name != restrictions[3]) continue; if (restrictions.Length >= 5 && restrictions[4] != null && col_name != restrictions[4]) continue; } DataRow row = dt.NewRow(); row["INDEX_CATALOG"] = null; row["INDEX_SCHEMA"] = table["TABLE_SCHEMA"]; row["INDEX_NAME"] = key_name; row["TABLE_NAME"] = GetString(reader, reader.GetOrdinal("TABLE")); row["COLUMN_NAME"] = col_name; row["ORDINAL_POSITION"] = reader.GetValue(reader.GetOrdinal("SEQ_IN_INDEX")); dt.Rows.Add(row); } } } return dt; } public virtual DataTable GetForeignKeys(string[] restrictions, bool includeColumns) { DataTable dt = new DataTable("Foreign Keys"); dt.Columns.Add("CONSTRAINT_CATALOG", typeof (string)); dt.Columns.Add("CONSTRAINT_SCHEMA", typeof (string)); dt.Columns.Add("CONSTRAINT_NAME", typeof (string)); dt.Columns.Add("TABLE_CATALOG", typeof(string)); dt.Columns.Add("TABLE_SCHEMA", typeof (string)); dt.Columns.Add("TABLE_NAME", typeof (string)); if (includeColumns) { dt.Columns.Add("COLUMN_NAME", typeof(string)); dt.Columns.Add("ORDINAL_POSITION", typeof(int)); } dt.Columns.Add("REFERENCED_TABLE_CATALOG", typeof (string)); dt.Columns.Add("REFERENCED_TABLE_SCHEMA", typeof (string)); dt.Columns.Add("REFERENCED_TABLE_NAME", typeof (string)); if (includeColumns) dt.Columns.Add("REFERENCED_COLUMN_NAME", typeof(string)); // first we use our restrictions to get a list of tables that should be // consulted. We save the keyname restriction since GetTables doesn't // understand that. string keyName = null; if (restrictions != null && restrictions.Length >= 4) { keyName = restrictions[3]; restrictions[3] = null; } DataTable tables = GetTables(restrictions); // now for each table retrieved, we call our helper function to // parse it's foreign keys foreach (DataRow table in tables.Rows) GetForeignKeysOnTable(dt, table, keyName, includeColumns); return dt; } private string GetSqlMode() { MySqlCommand cmd = new MySqlCommand("SELECT @@SQL_MODE", connection); return cmd.ExecuteScalar().ToString(); } #region Foreign Key routines /// <summary> /// GetForeignKeysOnTable retrieves the foreign keys on the given table. /// Since MySQL supports foreign keys on versions prior to 5.0, we can't use /// information schema. MySQL also does not include any type of SHOW command /// for foreign keys so we have to resort to use SHOW CREATE TABLE and parsing /// the output. /// </summary> /// <param name="fkTable">The table to store the key info in.</param> /// <param name="tableToParse">The table to get the foeign key info for.</param> /// <param name="filterName">Only get foreign keys that match this name.</param> /// <param name="includeColumns">Should column information be included in the table.</param> private void GetForeignKeysOnTable(DataTable fkTable, DataRow tableToParse, string filterName, bool includeColumns) { string sqlMode = GetSqlMode(); if (filterName != null) filterName = filterName.ToLower(); string sql = string.Format("SHOW CREATE TABLE `{0}`.`{1}`", tableToParse["TABLE_SCHEMA"], tableToParse["TABLE_NAME"]); string lowerBody = null, body = null; MySqlCommand cmd = new MySqlCommand(sql, connection); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); body = reader.GetString(1); lowerBody = body.ToLower(); } SqlTokenizer tokenizer = new SqlTokenizer(lowerBody); tokenizer.AnsiQuotes = sqlMode.IndexOf("ANSI_QUOTES") != -1; tokenizer.BackslashEscapes = sqlMode.IndexOf("NO_BACKSLASH_ESCAPES") != -1; while (true) { string token = tokenizer.NextToken(); // look for a starting contraint while (token != null && (token != "constraint" || tokenizer.Quoted)) token = tokenizer.NextToken(); if (token == null) break; ParseConstraint(fkTable, tableToParse, tokenizer, includeColumns); } } private void ParseConstraint(DataTable fkTable, DataRow table, SqlTokenizer tokenizer, bool includeColumns) { string name = tokenizer.NextToken(); DataRow row = fkTable.NewRow(); // make sure this constraint is a FK string token = tokenizer.NextToken(); if (token != "foreign" || tokenizer.Quoted) return; tokenizer.NextToken(); // read off the 'KEY' symbol tokenizer.NextToken(); // read off the '(' symbol row["CONSTRAINT_CATALOG"] = table["TABLE_CATALOG"]; row["CONSTRAINT_SCHEMA"] = table["TABLE_SCHEMA"]; row["TABLE_CATALOG"] = table["TABLE_CATALOG"]; row["TABLE_SCHEMA"] = table["TABLE_SCHEMA"]; row["TABLE_NAME"] = table["TABLE_NAME"]; row["REFERENCED_TABLE_CATALOG"] = null; row["CONSTRAINT_NAME"] = name; ArrayList srcColumns = includeColumns ? ParseColumns(tokenizer) : null; // now look for the references section while (token != "references" || tokenizer.Quoted) token = tokenizer.NextToken(); string target1 = tokenizer.NextToken(); string target2 = tokenizer.NextToken(); if (target2.StartsWith(".")) { row["REFERENCED_TABLE_SCHEMA"] = target1; row["REFERENCED_TABLE_NAME"] = target2.Substring(1); tokenizer.NextToken(); // read off the '(' } else { row["REFERENCED_TABLE_SCHEMA"] = table["TABLE_SCHEMA"]; row["REFERENCED_TABLE_NAME"] = target1; } // if we are supposed to include columns, read the target columns ArrayList targetColumns = includeColumns ? ParseColumns(tokenizer) : null; if (includeColumns) ProcessColumns(fkTable, row, srcColumns, targetColumns); else fkTable.Rows.Add(row); } private ArrayList ParseColumns(SqlTokenizer tokenizer) { ArrayList sc = new ArrayList(); string token = tokenizer.NextToken(); while (token != ")") { if (token != ",") sc.Add(token); token = tokenizer.NextToken(); } return sc; } private void ProcessColumns(DataTable fkTable, DataRow row, ArrayList srcColumns, ArrayList targetColumns) { for (int i = 0; i < srcColumns.Count; i++) { DataRow newRow = fkTable.NewRow(); newRow.ItemArray = row.ItemArray; newRow["COLUMN_NAME"] = (string)srcColumns[i]; newRow["ORDINAL_POSITION"] = i; newRow["REFERENCED_COLUMN_NAME"] = (string)targetColumns[i]; fkTable.Rows.Add(newRow); } } #endregion public virtual DataTable GetUsers(string[] restrictions) { StringBuilder sb = new StringBuilder("SELECT Host, User FROM mysql.user"); if (restrictions != null && restrictions.Length > 0) sb.AppendFormat(CultureInfo.InvariantCulture, " WHERE User LIKE '{0}'", restrictions[0]); MySqlDataAdapter da = new MySqlDataAdapter(sb.ToString(), connection); DataTable dt = new DataTable(); da.Fill(dt); dt.TableName = "Users"; dt.Columns[0].ColumnName = "HOST"; dt.Columns[1].ColumnName = "USERNAME"; return dt; } public virtual DataTable GetProcedures(string[] restrictions) { DataTable dt = new DataTable("Procedures"); dt.Columns.Add(new DataColumn("SPECIFIC_NAME", typeof(string))); dt.Columns.Add(new DataColumn("ROUTINE_CATALOG", typeof(string))); dt.Columns.Add(new DataColumn("ROUTINE_SCHEMA", typeof(string))); dt.Columns.Add(new DataColumn("ROUTINE_NAME", typeof(string))); dt.Columns.Add(new DataColumn("ROUTINE_TYPE", typeof(string))); dt.Columns.Add(new DataColumn("DTD_IDENTIFIER", typeof(string))); dt.Columns.Add(new DataColumn("ROUTINE_BODY", typeof(string))); dt.Columns.Add(new DataColumn("ROUTINE_DEFINITION", typeof(string))); dt.Columns.Add(new DataColumn("EXTERNAL_NAME", typeof(string))); dt.Columns.Add(new DataColumn("EXTERNAL_LANGUAGE", typeof(string))); dt.Columns.Add(new DataColumn("PARAMETER_STYLE", typeof(string))); dt.Columns.Add(new DataColumn("IS_DETERMINISTIC", typeof(string))); dt.Columns.Add(new DataColumn("SQL_DATA_ACCESS", typeof(string))); dt.Columns.Add(new DataColumn("SQL_PATH", typeof(string))); dt.Columns.Add(new DataColumn("SECURITY_TYPE", typeof(string))); dt.Columns.Add(new DataColumn("CREATED", typeof(DateTime))); dt.Columns.Add(new DataColumn("LAST_ALTERED", typeof(DateTime))); dt.Columns.Add(new DataColumn("SQL_MODE", typeof(string))); dt.Columns.Add(new DataColumn("ROUTINE_COMMENT", typeof(string))); dt.Columns.Add(new DataColumn("DEFINER", typeof(string))); StringBuilder sql = new StringBuilder("SELECT * FROM mysql.proc WHERE 1=1"); if (restrictions != null) { if (restrictions.Length >= 2 && restrictions[1] != null) sql.AppendFormat(CultureInfo.InvariantCulture, " AND db LIKE '{0}'", restrictions[1]); if (restrictions.Length >= 3 && restrictions[2] != null) sql.AppendFormat(CultureInfo.InvariantCulture, " AND name LIKE '{0}'", restrictions[2]); if (restrictions.Length >= 4 && restrictions[3] != null) sql.AppendFormat(CultureInfo.InvariantCulture, " AND type LIKE '{0}'", restrictions[3]); } MySqlCommand cmd = new MySqlCommand(sql.ToString(), connection); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { DataRow row = dt.NewRow(); row["SPECIFIC_NAME"] = reader.GetString("specific_name"); row["ROUTINE_CATALOG"] = DBNull.Value; row["ROUTINE_SCHEMA"] = reader.GetString("db"); row["ROUTINE_NAME"] = reader.GetString("name"); string routineType = reader.GetString("type"); row["ROUTINE_TYPE"] = routineType; row["DTD_IDENTIFIER"] = routineType.ToLower() == "function" ? (object)reader.GetString("returns") : DBNull.Value; row["ROUTINE_BODY"] = "SQL"; row["ROUTINE_DEFINITION"] = reader.GetString("body"); row["EXTERNAL_NAME"] = DBNull.Value; row["EXTERNAL_LANGUAGE"] = DBNull.Value; row["PARAMETER_STYLE"] = "SQL"; row["IS_DETERMINISTIC"] = reader.GetString("is_deterministic"); row["SQL_DATA_ACCESS"] = reader.GetString("sql_data_access"); row["SQL_PATH"] = DBNull.Value; row["SECURITY_TYPE"] = reader.GetString("security_type"); row["CREATED"] = reader.GetDateTime("created"); row["LAST_ALTERED"] = reader.GetDateTime("modified"); row["SQL_MODE"] = reader.GetString("sql_mode"); row["ROUTINE_COMMENT"] = reader.GetString("comment"); row["DEFINER"] = reader.GetString("definer"); dt.Rows.Add(row); } } return dt; } protected virtual DataTable GetCollections() { object[][] collections = new object[][] { new object[] {"MetaDataCollections", 0, 0}, new object[] {"DataSourceInformation", 0, 0}, new object[] {"DataTypes", 0, 0}, new object[] {"Restrictions", 0, 0}, new object[] {"ReservedWords", 0, 0}, new object[] {"Databases", 1, 1}, new object[] {"Tables", 4, 2}, new object[] {"Columns", 4, 4}, new object[] {"Users", 1, 1}, new object[] {"Foreign Keys", 4, 3}, new object[] {"IndexColumns", 5, 4}, new object[] {"Indexes", 4, 3}, new object[] {"Foreign Key Columns", 4, 3} }; DataTable dt = new DataTable("MetaDataCollections"); dt.Columns.Add(new DataColumn("CollectionName", typeof (string))); dt.Columns.Add(new DataColumn("NumberOfRestrictions", typeof(int))); dt.Columns.Add(new DataColumn("NumberOfIdentifierParts", typeof (int))); FillTable(dt, collections); return dt; } private DataTable GetDataSourceInformation() { #if CF throw new NotSupportedException(); #else DataTable dt = new DataTable("DataSourceInformation"); dt.Columns.Add("CompositeIdentifierSeparatorPattern", typeof (string)); dt.Columns.Add("DataSourceProductName", typeof (string)); dt.Columns.Add("DataSourceProductVersion", typeof (string)); dt.Columns.Add("DataSourceProductVersionNormalized", typeof (string)); dt.Columns.Add("GroupByBehavior", typeof (GroupByBehavior)); dt.Columns.Add("IdentifierPattern", typeof (string)); dt.Columns.Add("IdentifierCase", typeof (IdentifierCase)); dt.Columns.Add("OrderByColumnsInSelect", typeof (bool)); dt.Columns.Add("ParameterMarkerFormat", typeof (string)); dt.Columns.Add("ParameterMarkerPattern", typeof (string)); dt.Columns.Add("ParameterNameMaxLength", typeof (int)); dt.Columns.Add("ParameterNamePattern", typeof (string)); dt.Columns.Add("QuotedIdentifierPattern", typeof (string)); dt.Columns.Add("QuotedIdentifierCase", typeof (IdentifierCase)); dt.Columns.Add("StatementSeparatorPattern", typeof (string)); dt.Columns.Add("StringLiteralPattern", typeof (string)); dt.Columns.Add("SupportedJoinOperators", typeof (SupportedJoinOperators)); DBVersion v = connection.driver.Version; string ver = String.Format("{0:0}.{1:0}.{2:0}", v.Major, v.Minor, v.Build); DataRow row = dt.NewRow(); row["CompositeIdentifierSeparatorPattern"] = "\\."; row["DataSourceProductName"] = "MySQL"; row["DataSourceProductVersion"] = connection.ServerVersion; row["DataSourceProductVersionNormalized"] = ver; row["GroupByBehavior"] = GroupByBehavior.Unrelated; row["IdentifierPattern"] = @"(^\`\p{Lo}\p{Lu}\p{Ll}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Nd}@$#_]*$)|(^\`[^\`\0]|\`\`+\`$)|(^\"" + [^\""\0]|\""\""+\""$)"; row["IdentifierCase"] = IdentifierCase.Insensitive; row["OrderByColumnsInSelect"] = false; row["ParameterMarkerFormat"] = "{0}"; row["ParameterMarkerPattern"] = "(@[A-Za-z0-9_$#]*)"; row["ParameterNameMaxLength"] = 128; row["ParameterNamePattern"] = @"^[\p{Lo}\p{Lu}\p{Ll}\p{Lm}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Lm}\p{Nd}\uff3f_@#\$]*(?=\s+|$)"; row["QuotedIdentifierPattern"] = @"(([^\`]|\`\`)*)"; row["QuotedIdentifierCase"] = IdentifierCase.Sensitive; row["StatementSeparatorPattern"] = ";"; row["StringLiteralPattern"] = "'(([^']|'')*)'"; row["SupportedJoinOperators"] = 15; dt.Rows.Add(row); return dt; #endif } private static DataTable GetDataTypes() { DataTable dt = new DataTable("DataTypes"); dt.Columns.Add(new DataColumn("TypeName", typeof (string))); dt.Columns.Add(new DataColumn("ProviderDbType", typeof (int))); dt.Columns.Add(new DataColumn("ColumnSize", typeof (long))); dt.Columns.Add(new DataColumn("CreateFormat", typeof (string))); dt.Columns.Add(new DataColumn("CreateParameters", typeof (string))); dt.Columns.Add(new DataColumn("DataType", typeof (string))); dt.Columns.Add(new DataColumn("IsAutoincrementable", typeof (bool))); dt.Columns.Add(new DataColumn("IsBestMatch", typeof (bool))); dt.Columns.Add(new DataColumn("IsCaseSensitive", typeof (bool))); dt.Columns.Add(new DataColumn("IsFixedLength", typeof (bool))); dt.Columns.Add(new DataColumn("IsFixedPrecisionScale", typeof (bool))); dt.Columns.Add(new DataColumn("IsLong", typeof (bool))); dt.Columns.Add(new DataColumn("IsNullable", typeof (bool))); dt.Columns.Add(new DataColumn("IsSearchable", typeof (bool))); dt.Columns.Add(new DataColumn("IsSearchableWithLike", typeof (bool))); dt.Columns.Add(new DataColumn("IsUnsigned", typeof (bool))); dt.Columns.Add(new DataColumn("MaximumScale", typeof (short))); dt.Columns.Add(new DataColumn("MinimumScale", typeof (short))); dt.Columns.Add(new DataColumn("IsConcurrencyType", typeof (bool))); dt.Columns.Add(new DataColumn("IsLiteralsSupported", typeof (bool))); dt.Columns.Add(new DataColumn("LiteralPrefix", typeof (string))); dt.Columns.Add(new DataColumn("LiteralSuffix", typeof (string))); dt.Columns.Add(new DataColumn("NativeDataType", typeof (string))); // have each one of the types contribute to the datatypes collection MySqlBit.SetDSInfo(dt); MySqlBinary.SetDSInfo(dt); MySqlDateTime.SetDSInfo(dt); MySqlTimeSpan.SetDSInfo(dt); MySqlString.SetDSInfo(dt); MySqlDouble.SetDSInfo(dt); MySqlSingle.SetDSInfo(dt); MySqlByte.SetDSInfo(dt); MySqlInt16.SetDSInfo(dt); MySqlInt32.SetDSInfo(dt); MySqlInt64.SetDSInfo(dt); MySqlDecimal.SetDSInfo(dt); MySqlUByte.SetDSInfo(dt); MySqlUInt16.SetDSInfo(dt); MySqlUInt32.SetDSInfo(dt); MySqlUInt64.SetDSInfo(dt); return dt; } protected virtual DataTable GetRestrictions() { object[][] restrictions = new object[][] { new object[] {"Users", "Name", "", 0}, new object[] {"Databases", "Name", "", 0}, new object[] {"Tables", "Database", "", 0}, new object[] {"Tables", "Schema", "", 1}, new object[] {"Tables", "Table", "", 2}, new object[] {"Tables", "TableType", "", 3}, new object[] {"Columns", "Database", "", 0}, new object[] {"Columns", "Schema", "", 1}, new object[] {"Columns", "Table", "", 2}, new object[] {"Columns", "Column", "", 3}, new object[] {"Indexes", "Database", "", 0}, new object[] {"Indexes", "Schema", "", 1}, new object[] {"Indexes", "Table", "", 2}, new object[] {"Indexes", "Name", "", 3}, new object[] {"IndexColumns", "Database", "", 0}, new object[] {"IndexColumns", "Schema", "", 1}, new object[] {"IndexColumns", "Table", "", 2}, new object[] {"IndexColumns", "ConstraintName", "", 3}, new object[] {"IndexColumns", "Column", "", 4}, new object[] {"Foreign Keys", "Database", "", 0}, new object[] {"Foreign Keys", "Schema", "", 1}, new object[] {"Foreign Keys", "Table", "", 2}, new object[] {"Foreign Keys", "Constraint Name", "", 3}, new object[] {"Foreign Key Columns", "Catalog", "", 0}, new object[] {"Foreign Key Columns", "Schema", "", 1}, new object[] {"Foreign Key Columns", "Table", "", 2}, new object[] {"Foreign Key Columns", "Constraint Name", "", 3}, }; DataTable dt = new DataTable("Restrictions"); dt.Columns.Add(new DataColumn("CollectionName", typeof (string))); dt.Columns.Add(new DataColumn("RestrictionName", typeof (string))); dt.Columns.Add(new DataColumn("RestrictionDefault", typeof (string))); dt.Columns.Add(new DataColumn("RestrictionNumber", typeof (int))); FillTable(dt, restrictions); return dt; } private static DataTable GetReservedWords() { DataTable dt = new DataTable("ReservedWords"); dt.Columns.Add(new DataColumn(DbMetaDataColumnNames.ReservedWord, typeof(string))); Stream str = Assembly.GetExecutingAssembly().GetManifestResourceStream( "MySql.Data.MySqlClient.Properties.ReservedWords.txt"); StreamReader sr = new StreamReader(str); string line = sr.ReadLine(); while (line != null) { string[] keywords = line.Split(new char[] {' '}); foreach (string s in keywords) { if (String.IsNullOrEmpty(s)) continue; DataRow row = dt.NewRow(); row[0] = s; dt.Rows.Add(row); } line = sr.ReadLine(); } sr.Close(); str.Close(); return dt; } protected static void FillTable(DataTable dt, object[][] data) { foreach (object[] dataItem in data) { DataRow row = dt.NewRow(); for (int i = 0; i < dataItem.Length; i++) row[i] = dataItem[i]; dt.Rows.Add(row); } } private void FindTables(DataTable schemaTable, string[] restrictions) { StringBuilder sql = new StringBuilder(); StringBuilder where = new StringBuilder(); sql.AppendFormat(CultureInfo.InvariantCulture, "SHOW TABLE STATUS FROM `{0}`", restrictions[1]); if (restrictions != null && restrictions.Length >= 3 && restrictions[2] != null) where.AppendFormat(CultureInfo.InvariantCulture, " LIKE '{0}'", restrictions[2]); sql.Append(where.ToString()); string table_type = restrictions[1].ToLower() == "information_schema" ? "SYSTEM VIEW" : "BASE TABLE"; MySqlCommand cmd = new MySqlCommand(sql.ToString(), connection); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { DataRow row = schemaTable.NewRow(); row["TABLE_CATALOG"] = null; row["TABLE_SCHEMA"] = restrictions[1]; row["TABLE_NAME"] = reader.GetString(0); row["TABLE_TYPE"] = table_type; row["ENGINE"] = GetString(reader, 1); row["VERSION"] = reader.GetValue(2); row["ROW_FORMAT"] = GetString(reader, 3); row["TABLE_ROWS"] = reader.GetValue(4); row["AVG_ROW_LENGTH"] = reader.GetValue(5); row["DATA_LENGTH"] = reader.GetValue(6); row["MAX_DATA_LENGTH"] = reader.GetValue(7); row["INDEX_LENGTH"] = reader.GetValue(8); row["DATA_FREE"] = reader.GetValue(9); row["AUTO_INCREMENT"] = reader.GetValue(10); row["CREATE_TIME"] = reader.GetValue(11); row["UPDATE_TIME"] = reader.GetValue(12); row["CHECK_TIME"] = reader.GetValue(13); row["TABLE_COLLATION"] = GetString(reader, 14); row["CHECKSUM"] = reader.GetValue(15); row["CREATE_OPTIONS"] = GetString(reader, 16); row["TABLE_COMMENT"] = GetString(reader, 17); schemaTable.Rows.Add(row); } } } private static string GetString(MySqlDataReader reader, int index) { if (reader.IsDBNull(index)) return null; return reader.GetString(index); } protected virtual DataTable GetSchemaInternal(string collection, string[] restrictions) { switch (collection) { // common collections case "metadatacollections": return GetCollections(); case "datasourceinformation": return GetDataSourceInformation(); case "datatypes": return GetDataTypes(); case "restrictions": return GetRestrictions(); case "reservedwords": return GetReservedWords(); // collections specific to our provider case "users": return GetUsers(restrictions); case "databases": return GetDatabases(restrictions); } // if we have a current database and our users have // not specified a database, then default to the currently // selected one. if (restrictions == null) restrictions = new string[2]; if (connection != null && connection.Database != null && connection.Database.Length > 0 && restrictions.Length > 1 && restrictions[1] == null) restrictions[1] = connection.Database; switch (collection) { case "tables": return GetTables(restrictions); case "columns": return GetColumns(restrictions); case "indexes": return GetIndexes(restrictions); case "indexcolumns": return GetIndexColumns(restrictions); case "foreign keys": return GetForeignKeys(restrictions, false); case "foreign key columns": return GetForeignKeys(restrictions, true); } return null; } } }
using System; using System.Runtime.InteropServices; using System.Text; namespace LuaInterface { #pragma warning disable 414 public class MonoPInvokeCallbackAttribute : System.Attribute { private Type type; public MonoPInvokeCallbackAttribute(Type t) { type = t; } } #pragma warning restore 414 public enum LuaTypes : int { LUA_TNONE = -1, LUA_TNIL = 0, LUA_TBOOLEAN = 1, LUA_TLIGHTUSERDATA = 2, LUA_TNUMBER = 3, LUA_TSTRING = 4, LUA_TTABLE = 5, LUA_TFUNCTION = 6, LUA_TUSERDATA = 7, LUA_TTHREAD = 8, } public enum LuaGCOptions { LUA_GCSTOP = 0, LUA_GCRESTART = 1, LUA_GCCOLLECT = 2, LUA_GCCOUNT = 3, LUA_GCCOUNTB = 4, LUA_GCSTEP = 5, LUA_GCSETPAUSE = 6, LUA_GCSETSTEPMUL = 7, } public enum LuaThreadStatus { LUA_YIELD = 1, LUA_ERRRUN = 2, LUA_ERRSYNTAX = 3, LUA_ERRMEM = 4, LUA_ERRERR = 5, } sealed class LuaIndexes { #if LUA_5_3 // for lua5.3 public static int LUA_REGISTRYINDEX = -1000000 - 1000; #else // for lua5.1 or luajit public static int LUA_REGISTRYINDEX = -10000; public static int LUA_GLOBALSINDEX = -10002; #endif } [StructLayout(LayoutKind.Sequential)] public struct ReaderInfo { public String chunkData; public bool finished; } public delegate int LuaCSFunction(IntPtr luaState); public delegate string LuaChunkReader(IntPtr luaState, ref ReaderInfo data, ref uint size); public delegate int LuaFunctionCallback(IntPtr luaState); public class LuaDLL { public static int LUA_MULTRET = -1; #if UNITY_IPHONE && !UNITY_EDITOR const string LUADLL = "__Internal"; #else const string LUADLL = "slua"; #endif // Thread Funcs [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_tothread(IntPtr L, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_xmove(IntPtr from, IntPtr to, int n); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_newthread(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_status(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pushthread(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_gc(IntPtr luaState, LuaGCOptions what, int data); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_typename(IntPtr luaState, int type); public static string lua_typenamestr(IntPtr luaState, LuaTypes type) { IntPtr p = lua_typename(luaState, (int)type); return Marshal.PtrToStringAnsi(p); } public static string luaL_typename(IntPtr luaState, int stackPos) { return LuaDLL.lua_typenamestr(luaState, LuaDLL.lua_type(luaState, stackPos)); } public static bool lua_isfunction(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TFUNCTION; } public static bool lua_islightuserdata(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TLIGHTUSERDATA; } public static bool lua_istable(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TTABLE; } public static bool lua_isthread(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TTHREAD; } public static void luaL_error(IntPtr luaState, string message) { LuaDLL.luaL_where(luaState, 1); LuaDLL.lua_pushstring(luaState, message); LuaDLL.lua_concat(luaState, 2); LuaDLL.lua_error(luaState); } public static void luaL_error(IntPtr luaState, string fmt, params object[] args) { string str = string.Format(fmt, args); luaL_error(luaState, str); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern string luaL_gsub(IntPtr luaState, string str, string pattern, string replacement); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_isuserdata(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_rawequal(IntPtr luaState, int stackPos1, int stackPos2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setfield(IntPtr luaState, int stackPos, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_callmeta(IntPtr luaState, int stackPos, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaL_newstate(); /// <summary>DEPRECATED - use luaL_newstate() instead!</summary> public static IntPtr lua_open() { return LuaDLL.luaL_newstate(); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_close(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_openlibs(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadstring(IntPtr luaState, string chunk); public static int luaL_dostring(IntPtr luaState, string chunk) { int result = LuaDLL.luaL_loadstring(luaState, chunk); if (result != 0) return result; return LuaDLL.lua_pcall(luaState, 0, -1, 0); } /// <summary>DEPRECATED - use luaL_dostring(IntPtr luaState, string chunk) instead!</summary> public static int lua_dostring(IntPtr luaState, string chunk) { return LuaDLL.luaL_dostring(luaState, chunk); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_createtable(IntPtr luaState, int narr, int nrec); public static void lua_newtable(IntPtr luaState) { LuaDLL.lua_createtable(luaState, 0, 0); } #if LUA_5_3 [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getglobal(IntPtr luaState, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setglobal(IntPtr luaState, string name); public static void lua_insert(IntPtr luaState, int newTop) { lua_rotate(luaState, newTop, 1); } public static void lua_pushglobaltable(IntPtr l) { lua_rawgeti(l, LuaIndexes.LUA_REGISTRYINDEX, 2); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_rotate(IntPtr luaState, int index, int n); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_rawlen(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadbufferx(IntPtr luaState, byte[] buff, int size, string name, IntPtr x); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_callk(IntPtr luaState, int nArgs, int nResults,int ctx,IntPtr k); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pcallk(IntPtr luaState, int nArgs, int nResults, int errfunc,int ctx,IntPtr k); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc); public static int lua_call(IntPtr luaState, int nArgs, int nResults) { return lua_callk(luaState, nArgs, nResults, 0, IntPtr.Zero); } public static int lua_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc) { return luaS_pcall(luaState, nArgs, nResults, errfunc); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern double lua_tonumberx(IntPtr luaState, int index, IntPtr x); public static double lua_tonumber(IntPtr luaState, int index) { return lua_tonumberx(luaState, index, IntPtr.Zero); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern Int64 lua_tointegerx(IntPtr luaState, int index,IntPtr x); public static int lua_tointeger(IntPtr luaState, int index) { return (int)lua_tointegerx(luaState, index, IntPtr.Zero); } public static int luaL_loadbuffer(IntPtr luaState, byte[] buff, int size, string name) { return luaL_loadbufferx(luaState, buff, size, name, IntPtr.Zero); } public static void lua_remove(IntPtr l, int idx) { lua_rotate(l, (idx), -1); lua_pop(l, 1); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawgeti(IntPtr luaState, int tableIndex, Int64 index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawseti(IntPtr luaState, int tableIndex, Int64 index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushinteger(IntPtr luaState, Int64 i); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern Int64 luaL_checkinteger(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_yield(IntPtr luaState,int nrets); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_resume(IntPtr L, IntPtr from, int narg); #else [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_resume(IntPtr L, int narg); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_lessthan(IntPtr luaState, int stackPos1, int stackPos2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getfenv(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_yield(IntPtr L, int nresults); public static void lua_getglobal(IntPtr luaState, string name) { LuaDLL.lua_pushstring(luaState, name); LuaDLL.lua_gettable(luaState, LuaIndexes.LUA_GLOBALSINDEX); } public static void lua_setglobal(IntPtr luaState, string name) { LuaDLL.lua_pushstring(luaState, name); LuaDLL.lua_insert(luaState, -2); LuaDLL.lua_settable(luaState, LuaIndexes.LUA_GLOBALSINDEX); } public static void lua_pushglobaltable(IntPtr l) { LuaDLL.lua_pushvalue(l, LuaIndexes.LUA_GLOBALSINDEX); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_insert(IntPtr luaState, int newTop); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_objlen(IntPtr luaState, int stackPos); public static int lua_rawlen(IntPtr luaState, int stackPos) { return lua_objlen(luaState, stackPos); } public static int lua_strlen(IntPtr luaState, int stackPos) { return lua_rawlen(luaState, stackPos); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_call(IntPtr luaState, int nArgs, int nResults); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern double lua_tonumber(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_tointeger(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadbuffer(IntPtr luaState, byte[] buff, int size, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_remove(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawgeti(IntPtr luaState, int tableIndex, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawseti(IntPtr luaState, int tableIndex, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushinteger(IntPtr luaState, int i); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_checkinteger(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_replace(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_setfenv(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_equal(IntPtr luaState, int index1, int index2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadfile(IntPtr luaState, string filename); #endif [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_settop(IntPtr luaState, int newTop); public static void lua_pop(IntPtr luaState, int amount) { LuaDLL.lua_settop(luaState, -(amount) - 1); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_gettable(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawget(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_settable(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawset(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setmetatable(IntPtr luaState, int objIndex); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_getmetatable(IntPtr luaState, int objIndex); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushvalue(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_gettop(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern LuaTypes lua_type(IntPtr luaState, int index); public static bool lua_isnil(IntPtr luaState, int index) { return (LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TNIL); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_isnumber(IntPtr luaState, int index); public static bool lua_isboolean(IntPtr luaState, int index) { return LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TBOOLEAN; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_ref(IntPtr luaState, int registryIndex); public static void lua_getref(IntPtr luaState, int reference) { LuaDLL.lua_rawgeti(luaState,LuaIndexes.LUA_REGISTRYINDEX, reference); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_unref(IntPtr luaState, int registryIndex, int reference); public static void lua_unref(IntPtr luaState, int reference) { LuaDLL.luaL_unref(luaState, LuaIndexes.LUA_REGISTRYINDEX, reference); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_isstring(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_iscfunction(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushnil(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushstdcallcfunction(IntPtr luaState, IntPtr wrapper); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_checktype(IntPtr luaState, int p, LuaTypes t); public static void lua_pushstdcallcfunction(IntPtr luaState, LuaCSFunction function) { IntPtr fn = Marshal.GetFunctionPointerForDelegate(function); lua_pushstdcallcfunction(luaState, fn); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_tocfunction(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_toboolean(IntPtr luaState, int index); #if UNITY_IPHONE && !UNITY_EDITOR [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaS_tolstring32(IntPtr luaState, int index, out int strLen); #else [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_tolstring(IntPtr luaState, int index, out int strLen); #endif public static string lua_tostring(IntPtr luaState, int index) { int strlen; #if UNITY_IPHONE && !UNITY_EDITOR IntPtr str = luaS_tolstring32(luaState, index, out strlen); // fix il2cpp 64 bit #else IntPtr str = lua_tolstring(luaState, index, out strlen); #endif if (str != IntPtr.Zero) { return Marshal.PtrToStringAnsi(str, strlen); } return null; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_atpanic(IntPtr luaState, LuaCSFunction panicf); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushnumber(IntPtr luaState, double number); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushboolean(IntPtr luaState, bool value); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushstring(IntPtr luaState, string str); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushlstring(IntPtr luaState, byte[] str, int size); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_newmetatable(IntPtr luaState, string meta); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getfield(IntPtr luaState, int stackPos, string meta); public static void luaL_getmetatable(IntPtr luaState, string meta) { LuaDLL.lua_getfield(luaState, LuaIndexes.LUA_REGISTRYINDEX, meta); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaL_checkudata(IntPtr luaState, int stackPos, string meta); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern bool luaL_getmetafield(IntPtr luaState, int stackPos, string field); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_load(IntPtr luaState, LuaChunkReader chunkReader, ref ReaderInfo data, string chunkName); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_error(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_checkstack(IntPtr luaState, int extra); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_next(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushlightuserdata(IntPtr luaState, IntPtr udata); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_where(IntPtr luaState, int level); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern double luaL_checknumber(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_concat(IntPtr luaState, int n); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_newuserdata(IntPtr luaState, int val); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_rawnetobj(IntPtr luaState, int obj); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_touserdata(IntPtr luaState, int index); public static int lua_absindex(IntPtr luaState,int index) { return index > 0 ? index : lua_gettop(luaState) + index + 1; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Common.Core; using Microsoft.UnitTests.Core.Threading; using Xunit.Abstractions; using Xunit.Sdk; namespace Microsoft.UnitTests.Core.XUnit { internal sealed class TestMethodRunner : XunitTestMethodRunner { private readonly IReadOnlyDictionary<Type, object> _assemblyFixtureMappings; private readonly IReadOnlyDictionary<int, Type> _methodFixtureTypes; private readonly XunitTestEnvironment _testEnvironment; private readonly IMessageSink _diagnosticMessageSink; private readonly object[] _constructorArguments; private readonly ITestMainThreadFixture _testMainThreadFixture; private readonly Stopwatch _stopwatch; public TestMethodRunner(ITestMethod testMethod, IReflectionTypeInfo @class, IReflectionMethodInfo method, IEnumerable<IXunitTestCase> testCases, IMessageSink diagnosticMessageSink, IMessageBus messageBus, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource, object[] constructorArguments, IReadOnlyDictionary<int, Type> methodFixtureTypes, IReadOnlyDictionary<Type, object> assemblyFixtureMappings, XunitTestEnvironment testEnvironment) : base(testMethod, @class, method, testCases, diagnosticMessageSink, messageBus, aggregator, cancellationTokenSource, constructorArguments) { _assemblyFixtureMappings = assemblyFixtureMappings; _testEnvironment = testEnvironment; _diagnosticMessageSink = diagnosticMessageSink; _constructorArguments = constructorArguments; _methodFixtureTypes = methodFixtureTypes; _testMainThreadFixture = assemblyFixtureMappings.TryGetValue(typeof(ITestMainThreadFixture), out object fixture) ? (ITestMainThreadFixture) fixture : NullTestMainThreadFixture.Instance; _stopwatch = new Stopwatch(); } protected override async Task<RunSummary> RunTestCaseAsync(IXunitTestCase testCase) { using (var testMainThread = _testMainThreadFixture.CreateTestMainThread()) using (var taskObserver = _testEnvironment.UseTaskObserver(_testMainThreadFixture)) { if (_methodFixtureTypes.Any()) { return await RunTestCaseWithMethodFixturesAsync(testCase, taskObserver, testMainThread); } var testCaseRunSummay = await GetTestRunSummary(RunTestCaseAsync(testCase, _constructorArguments), taskObserver.Task); await WaitForObservedTasksAsync(testCase, testCaseRunSummay, taskObserver, testMainThread); return testCaseRunSummay; } } private async Task<RunSummary> RunTestCaseWithMethodFixturesAsync(IXunitTestCase testCase, TaskObserver taskObserver, ITestMainThread testMainThread) { var runSummary = new RunSummary(); var methodFixtures = CreateMethodFixtures(testCase, runSummary); if (Aggregator.HasExceptions) { return runSummary; } var testCaseConstructorArguments = await InitializeMethodFixturesAsync(testCase, runSummary, methodFixtures); if (!Aggregator.HasExceptions) { var testCaseRunSummary = await GetTestRunSummary(RunTestCaseAsync(testCase, testCaseConstructorArguments), taskObserver.Task); runSummary.Aggregate(testCaseRunSummary); } await DisposeMethodFixturesAsync(testCase, runSummary, methodFixtures); await WaitForObservedTasksAsync(testCase, runSummary, taskObserver, testMainThread); return runSummary; } private IDictionary<int, object> CreateMethodFixtures(IXunitTestCase testCase, RunSummary runSummary) { try { _stopwatch.Restart(); var methodFixtures = MethodFixtureProvider.CreateMethodFixtures(_methodFixtureTypes, _assemblyFixtureMappings); _stopwatch.Stop(); runSummary.Aggregate(new RunSummary { Time = (decimal)_stopwatch.Elapsed.TotalSeconds }); return methodFixtures; } catch (Exception exception) { _stopwatch.Stop(); runSummary.Aggregate(RegisterFailedRunSummary(testCase, (decimal)_stopwatch.Elapsed.TotalSeconds, exception)); return null; } } private async Task<object[]> InitializeMethodFixturesAsync(IXunitTestCase testCase, RunSummary runSummary, IDictionary<int, object> methodFixtures) { var constructorArguments = GetConstructorArguments(methodFixtures); var testInput = CreateTestInput(testCase, constructorArguments); foreach (var methodFixture in methodFixtures.Values.OfType<IMethodFixture>().Distinct()) { await RunActionAsync(testCase, () => methodFixture.InitializeAsync(testInput, MessageBus), runSummary, $"Method fixture {methodFixture.GetType()} needs too much time to initialize"); } return constructorArguments; } private async Task DisposeMethodFixturesAsync(IXunitTestCase testCase, RunSummary runSummary, IDictionary<int, object> methodFixtures) { foreach (var methodFixture in methodFixtures.Values.OfType<IMethodFixture>().Distinct()) { await RunActionAsync(testCase, () => methodFixture.DisposeAsync(runSummary, MessageBus), runSummary, $"Method fixture {methodFixture.GetType()} needs too much time to dispose"); } } private Task WaitForObservedTasksAsync(IXunitTestCase testCase, RunSummary runSummary, TaskObserver taskObserver, ITestMainThread testMainThread) { testMainThread.CancelPendingTasks(); taskObserver.TestCompleted(); return RunActionAsync(testCase, () => taskObserver.Task, runSummary, "Tasks that have been started during test run are still not completed"); } private ITestInput CreateTestInput(IXunitTestCase testCase, object[] testCaseConstructorArguments) { return new TestInput(testCase, Class.Type, TestMethod.Method.ToRuntimeMethod(), testCase.DisplayName, testCaseConstructorArguments, testCase.TestMethodArguments); } private object[] GetConstructorArguments(IDictionary<int, object> methodFixtures) { var testCaseConstructorArguments = new object[_constructorArguments.Length]; for (var i = 0; i < _constructorArguments.Length; i++) { var argument = _constructorArguments[i]; if (argument == null && methodFixtures.TryGetValue(i, out var fixture)) { testCaseConstructorArguments[i] = fixture; } else { testCaseConstructorArguments[i] = argument; } } return testCaseConstructorArguments; } private Task<RunSummary> RunTestCaseAsync(IXunitTestCase xunitTestCase, object[] constructorArguments) { if (xunitTestCase is TestCase testCase) { testCase.MainThreadFixture = _testMainThreadFixture; } return xunitTestCase.RunAsync(_diagnosticMessageSink, MessageBus, constructorArguments, new ExceptionAggregator(Aggregator), CancellationTokenSource); } private async Task<RunSummary> GetTestRunSummary(Task<RunSummary> testCaseRunTask, Task<Exception> taskObserverTask) { await Task.WhenAny(testCaseRunTask, taskObserverTask); if (testCaseRunTask.IsCompleted) { return testCaseRunTask.Result; } CancellationTokenSource.Cancel(); var testCaseSummary = await testCaseRunTask; if (taskObserverTask.IsFaulted) { Aggregator.Add(taskObserverTask.Exception); testCaseSummary.Failed = 1; } return testCaseSummary; } private async Task RunActionAsync(IXunitTestCase testCase, Func<Task> action, RunSummary runSummary, string timeoutMessage) { Exception exception = null; _stopwatch.Restart(); try { var task = action(); await ParallelTools.When(task, 60_000, timeoutMessage); } catch (Exception ex) { exception = ex; } _stopwatch.Stop(); var time = (decimal) _stopwatch.Elapsed.TotalSeconds; var taskRunSummary = exception != null ? RegisterFailedRunSummary(testCase, time, exception) : new RunSummary {Time = time}; runSummary.Aggregate(taskRunSummary); } private RunSummary RegisterFailedRunSummary(IXunitTestCase testCase, decimal time, Exception exception) { Aggregator.Add(exception); var caseSummary = new RunSummary {Total = 1, Failed = 1, Time = time}; MessageBus.QueueMessage(new TestFailed(new XunitTest(testCase, testCase.DisplayName), caseSummary.Time, string.Empty, exception)); return caseSummary; } private class TestInput : ITestInput { public IXunitTestCase TestCase { get; } public Type TestClass { get; } public MethodInfo TestMethod { get; } public string DisplayName { get; } public string FileSytemSafeName { get; } public IReadOnlyList<object> ConstructorArguments { get; } public IReadOnlyList<object> TestMethodArguments { get; } public TestInput(IXunitTestCase testCase, Type testClass, MethodInfo testMethod, string displayName, object[] constructorArguments, object[] testMethodArguments) { TestCase = testCase; TestClass = testClass; TestMethod = testMethod; DisplayName = displayName; FileSytemSafeName = $"{GetFileSystemSafeName(testClass)}_{testMethod.Name}"; ConstructorArguments = new ReadOnlyCollection<object>(constructorArguments); TestMethodArguments = new ReadOnlyCollection<object>(testMethodArguments ?? new object[0]); } private static string GetFileSystemSafeName(Type type) { var sb = new StringBuilder(type.ToString()) .Replace('+', '-') .Replace('#', '-'); for (var i = sb.Length - 1; i >= 0; i--) { if (sb[i] == '`') { sb.Remove(i, 1); } } return sb.ToString(); } } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ /*************************************************************************** Copyright (c) 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.CodeDom; using System.CodeDom.Compiler; using System.Diagnostics.CodeAnalysis; using EnvDTE; using System.Diagnostics; using System.Runtime.InteropServices; namespace Microsoft.Samples.VisualStudio.CodeDomCodeModel { [ComVisible(true)] [SuppressMessage("Microsoft.Interoperability", "CA1409:ComVisibleTypesShouldBeCreatable")] [SuppressMessage("Microsoft.Interoperability", "CA1405:ComVisibleTypeBaseTypesShouldBeComVisible")] public class CodeDomCodeClass : CodeDomCodeType<CodeTypeDeclaration>, CodeClass { //!!! need to deal w/ indexing of interfaces & bases - we combine them in CodeDom but not here. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "0#dte")] public CodeDomCodeClass(DTE dte, CodeElement parent, string name, object bases, object interfaces, vsCMAccess access) : base(dte, parent, name) { CodeObject = new CodeTypeDeclaration(name); CodeObject.UserData[CodeKey] = this; CodeObject.IsClass = true; Initialize(bases, interfaces, access); } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "0#dte")] public CodeDomCodeClass(DTE dte, CodeElement parent, CodeTypeDeclaration declaration) : base(dte, parent, (null==declaration) ? null : declaration.Name) { CodeObject = declaration; } #region CodeClass Members public CodeClass AddClass(string Name, object Position, object Bases, object ImplementedInterfaces, vsCMAccess Access) { CodeDomCodeClass codeClass = new CodeDomCodeClass(DTE, this, Name, Bases, ImplementedInterfaces, Access); CodeObject.Members.Insert(PositionToIndex(Position), codeClass.CodeObject); CommitChanges(); return codeClass; } public CodeDelegate AddDelegate(string Name, object Type, object Position, vsCMAccess Access) { CodeDomCodeDelegate codeDelegate = new CodeDomCodeDelegate(DTE, this, Name, Type); CodeObject.Members.Insert(PositionToIndex(Position), codeDelegate.CodeObject); CommitChanges(); return codeDelegate; } public CodeEnum AddEnum(string Name, object Position, object Bases, vsCMAccess Access) { CodeDomCodeEnum codeEnum = new CodeDomCodeEnum(DTE, this, Name, Bases, Access); CodeObject.Members.Insert(PositionToIndex(Position), codeEnum.CodeObject); CommitChanges(); return codeEnum; } public CodeFunction AddFunction(string Name, vsCMFunction Kind, object Type, object Position, vsCMAccess Access, object Location) { CodeDomCodeFunction codeFunc = new CodeDomCodeFunction(DTE, this, Name, Kind, Type, Access); CodeObject.Members.Insert(PositionToIndex(Position), codeFunc.CodeObject); CommitChanges(); return codeFunc; } /// <summary> /// AddImplementedInterface adds a reference to an interface that the CodeClass promises to implement. AddImplementedInterface does not insert method stubs for the interface members. /// </summary> /// <param name="Base">Required. The interface the class will implement. This is either a CodeInterface or a fully qualified type name.</param> /// <param name="Position">Optional. Default = 0. The code element after which to add the new element. If the value is a CodeElement, then the new element is added immediately after it. /// /// If the value is a Long data type, then AddImplementedInterface indicates the element after which to add the new element. /// /// Because collections begin their count at 1, passing 0 indicates that the new element should be placed at the beginning of the collection. A value of -1 means the element should be placed at the end. /// </param> /// <returns>A CodeInterface object. </returns> public CodeInterface AddImplementedInterface(object Base, object Position) { CodeTypeReference ctr; CodeDomCodeInterface iface = Base as CodeDomCodeInterface; if (iface != null) ctr = new CodeTypeReference(iface.FullName); else ctr = new CodeTypeReference((string)Base); CodeObject.BaseTypes.Insert(PositionToInterfaceIndex(Position), ctr); CommitChanges(); return new CodeDomCodeInterface(DTE, this, ctr.BaseType, System.Reflection.Missing.Value, vsCMAccess.vsCMAccessDefault); } public CodeProperty AddProperty(string GetterName, string PutterName, object Type, object Position, vsCMAccess Access, object Location) { CodeDomCodeProperty res = new CodeDomCodeProperty(DTE, this, GetterName, PutterName, Type, Access); CodeObject.Members.Insert(PositionToIndex(Position), res.CodeObject); CommitChanges(); return res; } public CodeStruct AddStruct(string Name, object Position, object Bases, object ImplementedInterfaces, vsCMAccess Access) { CodeDomCodeStruct codeStruct = new CodeDomCodeStruct(DTE, this, Name, Bases, ImplementedInterfaces, Access); CodeObject.Members.Insert(PositionToIndex(Position), codeStruct.CodeObject); CommitChanges(); return codeStruct; } /// <summary> /// Creates a new variable code construct and inserts the code in the correct location. /// </summary> /// <param name="Name">Required. The name of the new variable.</param> /// <param name="Type">Required. A vsCMTypeRef constant indicating the data type that the function returns. This can be a CodeTypeRef object, a vsCMTypeRef constant, or a fully qualified type name.</param> /// <param name="Position">Optional. Default = 0. The code element after which to add the new element. If the value is a CodeElement, then the new element is added immediately after it. /// /// If the value is a Long, then AddVariable indicates the element after which to add the new element. /// /// Because collections begin their count at 1, passing 0 indicates that the new element should be placed at the beginning of the collection. A value of -1 means the element should be placed at the end. /// </param> /// <param name="Access">Optional. A vsCMAccess constant.</param> /// <param name="Location">Optional. The path and file name for the new variable definition. Depending on the language, the file name is either relative or absolute to the project file. The file is added to the project if it is not already a project item. If the file cannot be created and added to the project, then AddVariable fails.</param> /// <returns></returns> public CodeVariable AddVariable(string Name, object Type, object Position, vsCMAccess Access, object Location) { CodeDomCodeVariable codeVar = new CodeDomCodeVariable(DTE, this, Name, ObjectToTypeRef(Type), Access); CodeObject.Members.Insert(PositionToIndex(Position), codeVar.CodeObject); CommitChanges(); return codeVar; } public bool IsAbstract { get { return (CodeObject.Attributes & MemberAttributes.Abstract) != 0; } [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")] set { if (value) CodeObject.Attributes |= MemberAttributes.Abstract; else CodeObject.Attributes &= ~(MemberAttributes.Abstract); CommitChanges(); } } public void RemoveInterface(object Element) { int index = 0; foreach (CodeTypeReference typeRef in CodeObject.BaseTypes) { if (Element == ((CodeDomCodeTypeRef)typeRef.UserData[CodeKey]).CodeType) { CodeObject.BaseTypes.RemoveAt(index); break; } index++; } CommitChanges(); } #endregion public override vsCMElement Kind { get { return vsCMElement.vsCMElementClass; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using DynamicWrapper; using NUnit.Framework; namespace DynamicWrapperTests { [TestFixture] public class DynamicWrapperTests { public class TestEventArgs : EventArgs { public string Message { get; set; } } public interface ITester { string Respond(string message); int Return5(); void VoidMethod(); void Add6ToParam(ref int param); void SetOutParamTo7(out int param); int Property { get; set; } event EventHandler<TestEventArgs> MyEvent; } public interface ITester2 { string Respond(string message); } public interface IGenericTester { bool IsTypeOf<T>(); bool TypesAreSame<TOneT, TWoT>(); T GenericReturn<T>(); T GenericParameter<T>(T value); bool GenericCompare<TOneT, TWoT>(TOneT one, TWoT two); IEnumerable<T> Return3<T>(Func<int, T> generate); } public class MyTester { public string Respond(string message) { return message + " response"; } public int Return5() { return 5; } public void VoidMethod() { throw new Exception("VoidMethod"); } public void Add6ToParam(ref int param) { param = param + 6; } public void SetOutParamTo7(out int param) { param = 7; } public int Property { get; set; } public bool IsTypeOf<T>() { return typeof(T) == GetType(); } public bool TypesAreSame<TOneT, TWoT>() { return typeof(TOneT) == typeof(TWoT); } public T GenericReturn<T>() { return (T) Activator.CreateInstance(typeof(T)); } public T GenericParameter<T>(T value) { return value; } public bool GenericCompare<TOneT, TWoT>(TOneT one, TWoT two) { return one.Equals(two); } public IEnumerable<T> Return3<T>(Func<int, T> generate) { for (int i = 0; i < 3; i++) yield return generate(i); } public event EventHandler<TestEventArgs> MyEvent; public void FireEvent(string message) { var handlers = MyEvent; if (handlers != null) handlers(this, new TestEventArgs {Message = message}); } } public interface IGenericInterface<out T, out TF> { T GetT(); TF GetF(); } public class GenericClass<T, TF> { public T Val; public TF FVal; public T GetT() { return Val; } public TF GetF() { return FVal; } } private MyTester _realObject; [SetUp] public virtual void SetUp() { _realObject = new MyTester(); } [Test] public void Calling_Wrapper_Proxies_To_RealObject() { var wrappedObject = _realObject.As<ITester>(); Assert.That(wrappedObject.Respond("Foo"), Is.EqualTo("Foo response")); } [Test] public void Casting_More_Than_Once_Does_Not_Fail() { var wrappedObject1 = _realObject.As<ITester>(); var wrappedObject2 = _realObject.As<ITester>(); Assert.That(wrappedObject1.Respond("Foo"), Is.EqualTo("Foo response")); Assert.That(wrappedObject2.Respond("Foo"), Is.EqualTo("Foo response")); } [Test] public void Two_Interface_Wrappers_For_The_Same_Class() { var wrappedObject1 = _realObject.As<ITester>(); var wrappedObject2 = _realObject.As<ITester2>(); Assert.That(wrappedObject1.Respond("Foo"), Is.EqualTo(wrappedObject2.Respond("Foo"))); } [Test] public void Parameterless_Methods_Wrap_Properly() { var wrappedObject = _realObject.As<ITester>(); Assert.That(wrappedObject.Return5(), Is.EqualTo(5)); } [Test] public void Reference_Parameters_Wrap_Properly() { var wrappedObject = _realObject.As<ITester>(); int foo = 5; wrappedObject.Add6ToParam(ref foo); Assert.That(foo, Is.EqualTo(11)); } [Test] public void Out_Parameters_Wrap_Properly() { var wrappedObject = _realObject.As<ITester>(); int foo; wrappedObject.SetOutParamTo7(out foo); Assert.That(foo, Is.EqualTo(7)); } [Test] public void Void_Methods_Wrap_Properly() { var wrappedObject = _realObject.As<ITester>(); Exception exception = null; try { wrappedObject.VoidMethod(); } catch (Exception e) { exception = e; } Assert.That(exception, Is.Not.Null); Assert.That(exception.Message, Is.EqualTo("VoidMethod")); } [Test] public void Set_Properties_Wrap_Properly() { var wrappedObject = _realObject.As<ITester>(); wrappedObject.Property = 55; Assert.That(_realObject.Property, Is.EqualTo(55)); } [Test] public void Get_Properties_Wrap_Properly() { var wrappedObject = _realObject.As<ITester>(); _realObject.Property = 66; Assert.That(wrappedObject.Property, Is.EqualTo(66)); } [Test] public void Generic_Methods_With_One_Argument_Generates_Properly() { var wrappedObject = _realObject.As<IGenericTester>(); Assert.That(wrappedObject.IsTypeOf<string>(), Is.False); } [Test] public void Generic_Methods_With_Multiple_Arguments_Generates_Properly() { var wrappedObject = _realObject.As<IGenericTester>(); Assert.That(wrappedObject.TypesAreSame<string, string>(), Is.True); } [Test] public void Generic_Return_Value_Generates_Properly() { var wrappedObject = _realObject.As<IGenericTester>(); Assert.That(wrappedObject.GenericReturn<int>(), Is.EqualTo(0)); Assert.That(wrappedObject.GenericReturn<DateTime>(), Is.EqualTo(DateTime.MinValue)); } [Test] public void Generic_Parameter_Generates_Properly() { var wrappedObject = _realObject.As<IGenericTester>(); Assert.That(wrappedObject.GenericParameter("FOO"), Is.EqualTo("FOO")); } [Test] public void Multiple_Generic_Parameters_Generates_Properly() { var wrappedObject = _realObject.As<IGenericTester>(); Assert.That(wrappedObject.GenericCompare("FOO", "FOO")); Assert.That(wrappedObject.GenericCompare("FOO", "BAR"), Is.False); } [Test] public void Complex_Generic_Method_Generates_Properly() { var wrappedObject = _realObject.As<IGenericTester>(); var values = wrappedObject.Return3(i => i.ToString()).ToList(); Assert.That(values.Count, Is.EqualTo(3)); Assert.That(values[0], Is.EqualTo("0")); Assert.That(values[1], Is.EqualTo("1")); Assert.That(values[2], Is.EqualTo("2")); } [Test] public void Generic_Interface_Generates_Properly() { var realObject = new GenericClass<string, int> {Val = "FOO", FVal = 99}; var wrappedObject = realObject.As<IGenericInterface<string, int>>(); Assert.That(wrappedObject.GetT(), Is.EqualTo("FOO")); Assert.That(wrappedObject.GetF(), Is.EqualTo(99)); } [Test] public void Events_Wrap_Properly() { var wrappedObject = _realObject.As<ITester>(); object eventSender = null; string eventMessage = string.Empty; wrappedObject.MyEvent += (sender, args) => { eventSender = sender; eventMessage = args.Message; }; _realObject.FireEvent("FOO"); Assert.That(eventSender, Is.EqualTo(_realObject)); Assert.That(eventMessage, Is.EqualTo(eventMessage)); } [Test] public void GetRealObjectBack() { var wrappedObject = _realObject.As<ITester>(); Assert.That(wrappedObject.AsReal<MyTester>(), Is.EqualTo(_realObject)); } [Test] public void GetRealObject_When_Type_Implements_Interface() { IList list = new List<string>(); var list2 = list.AsReal<List<string>>(); Assert.That(list, Is.EqualTo(list2)); } [Test] public void GetRealObject_When_Wrong_Type_Returns_Null() { IList list = new List<string>(); Assert.That(list.AsReal<MyTester>(), Is.Null); } public interface INotWrappable { void NotWrappable(); } [Test] [ExpectedException(typeof(MissingMethodException))] public void Bad_Mapping_Throws_Execption() { _realObject.As<INotWrappable>(); } public interface IDerived : IDisposable { string Foo(); } public class MultiIf { private string _message = "Bar"; public void Dispose() { _message = "Disposed"; } [SuppressMessage("ReSharper", "MemberHidesStaticFromOuterClass")] public string Foo() { return _message; } } [Test] public void Derived_Interfaces_Generate_Properly() { var realObject = new MultiIf(); var wrappedObject = realObject.As<IDerived>(); Assert.That(wrappedObject.Foo(), Is.EqualTo("Bar")); wrappedObject.Dispose(); Assert.That(wrappedObject.Foo(), Is.EqualTo("Disposed")); } public interface IFoo {} public class Foo : IFoo {} [Test] public void When_Class_Explicitly_Implements_Interface_Do_Not_Wrap() { var realObject = new Foo(); var foo = realObject.As<IFoo>(); Assert.That(realObject, Is.EqualTo(foo)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Scheduler { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for JobsOperations. /// </summary> public static partial class JobsOperationsExtensions { /// <summary> /// Gets a job. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobName'> /// The job name. /// </param> public static JobDefinition Get(this IJobsOperations operations, string resourceGroupName, string jobCollectionName, string jobName) { return Task.Factory.StartNew(s => ((IJobsOperations)s).GetAsync(resourceGroupName, jobCollectionName, jobName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a job. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobName'> /// The job name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobDefinition> GetAsync(this IJobsOperations operations, string resourceGroupName, string jobCollectionName, string jobName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, jobCollectionName, jobName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Provisions a new job or updates an existing job. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobName'> /// The job name. /// </param> /// <param name='job'> /// The job definition. /// </param> public static JobDefinition CreateOrUpdate(this IJobsOperations operations, string resourceGroupName, string jobCollectionName, string jobName, JobDefinition job) { return Task.Factory.StartNew(s => ((IJobsOperations)s).CreateOrUpdateAsync(resourceGroupName, jobCollectionName, jobName, job), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Provisions a new job or updates an existing job. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobName'> /// The job name. /// </param> /// <param name='job'> /// The job definition. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobDefinition> CreateOrUpdateAsync(this IJobsOperations operations, string resourceGroupName, string jobCollectionName, string jobName, JobDefinition job, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, jobCollectionName, jobName, job, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Patches an existing job. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobName'> /// The job name. /// </param> /// <param name='job'> /// The job definition. /// </param> public static JobDefinition Patch(this IJobsOperations operations, string resourceGroupName, string jobCollectionName, string jobName, JobDefinition job) { return Task.Factory.StartNew(s => ((IJobsOperations)s).PatchAsync(resourceGroupName, jobCollectionName, jobName, job), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Patches an existing job. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobName'> /// The job name. /// </param> /// <param name='job'> /// The job definition. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobDefinition> PatchAsync(this IJobsOperations operations, string resourceGroupName, string jobCollectionName, string jobName, JobDefinition job, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PatchWithHttpMessagesAsync(resourceGroupName, jobCollectionName, jobName, job, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a job. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobName'> /// The job name. /// </param> public static void Delete(this IJobsOperations operations, string resourceGroupName, string jobCollectionName, string jobName) { Task.Factory.StartNew(s => ((IJobsOperations)s).DeleteAsync(resourceGroupName, jobCollectionName, jobName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a job. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobName'> /// The job name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IJobsOperations operations, string resourceGroupName, string jobCollectionName, string jobName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, jobCollectionName, jobName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Runs a job. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobName'> /// The job name. /// </param> public static void Run(this IJobsOperations operations, string resourceGroupName, string jobCollectionName, string jobName) { Task.Factory.StartNew(s => ((IJobsOperations)s).RunAsync(resourceGroupName, jobCollectionName, jobName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Runs a job. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobName'> /// The job name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task RunAsync(this IJobsOperations operations, string resourceGroupName, string jobCollectionName, string jobName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.RunWithHttpMessagesAsync(resourceGroupName, jobCollectionName, jobName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Lists all jobs under the specified job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<JobDefinition> List(this IJobsOperations operations, string resourceGroupName, string jobCollectionName, ODataQuery<JobStateFilter> odataQuery = default(ODataQuery<JobStateFilter>)) { return Task.Factory.StartNew(s => ((IJobsOperations)s).ListAsync(resourceGroupName, jobCollectionName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all jobs under the specified job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<JobDefinition>> ListAsync(this IJobsOperations operations, string resourceGroupName, string jobCollectionName, ODataQuery<JobStateFilter> odataQuery = default(ODataQuery<JobStateFilter>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, jobCollectionName, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists job history. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobName'> /// The job name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<JobHistoryDefinition> ListJobHistory(this IJobsOperations operations, string resourceGroupName, string jobCollectionName, string jobName, ODataQuery<JobHistoryFilter> odataQuery = default(ODataQuery<JobHistoryFilter>)) { return Task.Factory.StartNew(s => ((IJobsOperations)s).ListJobHistoryAsync(resourceGroupName, jobCollectionName, jobName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists job history. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobName'> /// The job name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<JobHistoryDefinition>> ListJobHistoryAsync(this IJobsOperations operations, string resourceGroupName, string jobCollectionName, string jobName, ODataQuery<JobHistoryFilter> odataQuery = default(ODataQuery<JobHistoryFilter>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListJobHistoryWithHttpMessagesAsync(resourceGroupName, jobCollectionName, jobName, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all jobs under the specified job collection. /// </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<JobDefinition> ListNext(this IJobsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IJobsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all jobs under the specified job collection. /// </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<JobDefinition>> ListNextAsync(this IJobsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists job history. /// </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<JobHistoryDefinition> ListJobHistoryNext(this IJobsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IJobsOperations)s).ListJobHistoryNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists job history. /// </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<JobHistoryDefinition>> ListJobHistoryNextAsync(this IJobsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListJobHistoryNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/******************************************************************************* * Copyright 2009-2015 Amazon Services. 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://aws.amazon.com/apache2.0 * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. ******************************************************************************* * Marketplace Web Service Products * API Version: 2011-10-01 * Library Version: 2015-09-01 * Generated: Thu Sep 10 06:52:19 PDT 2015 */ using System; using MarketplaceWebServiceProducts.Model; using MWSClientCsRuntime; namespace MarketplaceWebServiceProducts { /// <summary> /// Configuration for a connection /// </summary> public class MarketplaceWebServiceProductsConfig { private const string DEFAULT_SERVICE_PATH = "Products/2011-10-01"; private const string SERVICE_VERSION = "2011-10-01"; private string servicePath; private MwsConnection cc = new MwsConnection(); /// <summary> /// Get a clone of the configured connection /// </summary> /// <returns>A clone of the configured connection</returns> internal MwsConnection CopyConnection() { return (MwsConnection) cc.Clone(); } /// <summary> /// Gets the service version this client library is compatible with /// </summary> public string ServiceVersion { get { return SERVICE_VERSION; } } /// <summary> /// Gets and sets of the SignatureMethod used to authenticate with MWS /// </summary> public string SignatureMethod { get { return cc.SignatureMethod; } set { cc.SignatureMethod = value; } } /// <summary> /// Sets the SignatureMethod used to authenticate with MWS /// </summary> /// <param name="signatureMethod">Signature method to use (ex: HmacSHA256)</param> /// <returns>this instance</returns> public MarketplaceWebServiceProductsConfig WithSignatureMethod(string signatureMethod) { this.SignatureMethod = signatureMethod; return this; } /// <summary> /// Checks if SignatureMethod is set /// </summary> /// <returns>true if SignatureMethod is set</returns> public bool IsSetSignatureMethod() { return this.SignatureMethod != null; } /// <summary> /// Gets and sets of the SignatureVersion used to authenticate with MWS /// </summary> public string SignatureVersion { get { return cc.SignatureVersion; } set { cc.SignatureVersion = value; } } /// <summary> /// Sets the SignatureVersion used to authenticate with MWS /// </summary> /// <param name="signatureMethod">Signature version to use (ex: 2)</param> /// <returns>this instance</returns> public MarketplaceWebServiceProductsConfig WithSignatureVersion(string signatureVersion) { this.SignatureVersion = signatureVersion; return this; } /// <summary> /// Checks if SignatureVersion is set /// </summary> /// <returns>true if SignatureVersion is set</returns> public bool IsSetSignatureVersion() { return this.SignatureVersion != null; } /// <summary> /// Gets the UserAgent /// </summary> public string UserAgent { get { return cc.UserAgent ; } } /// <summary> /// Sets the UserAgent property /// </summary> /// <param name="userAgent">UserAgent property</param> /// <returns>this instance</returns> public MarketplaceWebServiceProductsConfig WithUserAgent(String userAgent) { cc.UserAgent = userAgent; return this; } public void SetUserAgentHeader( string applicationName, string applicationVersion, string programmingLanguage, params string[] additionalNameValuePairs) { cc.SetUserAgent(applicationName,applicationVersion,programmingLanguage,additionalNameValuePairs); } /// <summary> /// Sets the UserAgent /// </summary> /// <param name="applicationName">Your application's name, e.g. "MyMWSApp"</param> /// <param name="applicationVersion">Your application's version, e.g. "1.0"</param> /// <returns>this instance</returns> public MarketplaceWebServiceProductsConfig WithUserAgent(string applicationName, string applicationVersion) { SetUserAgent(applicationName, applicationVersion); return this; } public void SetUserAgent(string applicationName, string applicationVersion) { cc.ApplicationName = applicationName; cc.ApplicationVersion = applicationVersion; } /// <summary> /// Checks if UserAgent is set /// </summary> /// <returns>true if UserAgent is set</returns> public bool IsSetUserAgent() { return this.UserAgent != null; } /// <summary> /// Gets and sets of the URL to base MWS calls on /// May include the path to make MWS calls to. Defaults to Products/2011-10-01 /// </summary> public string ServiceURL { get { return new Uri(cc.Endpoint, servicePath).ToString(); } set { try { Uri fullUri = new Uri(value); cc.Endpoint = new Uri(fullUri.Scheme + "://" + fullUri.Authority); // Strip slashes String path = fullUri.PathAndQuery; if(path != null) { path = path.Trim(new[] {'/'}); } if(String.IsNullOrEmpty(path)) { this.servicePath = DEFAULT_SERVICE_PATH; } else { this.servicePath = path; } } catch (Exception e) { throw MwsUtil.Wrap(e); } } } /// <summary> /// Sets the ServiceURL property /// </summary> /// <param name="serviceURL">ServiceURL property</param> /// <returns>this instance</returns> public MarketplaceWebServiceProductsConfig WithServiceURL(string serviceURL) { this.ServiceURL = serviceURL; return this; } /// <summary> /// Checks if Service URL is set /// </summary> /// <returns>true if Service URL is set</returns> public bool IsSetServiceURL() { return cc.Endpoint != null; } internal string ServicePath { get { return servicePath; } } /// <summary> /// Gets and sets the host to use as a proxy server /// </summary> public string ProxyHost { get { return cc.ProxyHost; } set { cc.ProxyHost = value; } } /// <summary> /// Sets the host to use as a proxy server /// </summary> /// <param name="proxyHost">proxy host</param> /// <returns>this instance</returns> public MarketplaceWebServiceProductsConfig WithProxyHost(string proxyHost) { this.ProxyHost = proxyHost; return this; } /// <summary> /// Checks if proxy host is set /// </summary> /// <returns>true if proxy host is set</returns> public bool IsSetProxyHost() { return this.ProxyHost != null; } /// <summary> /// Gets and sets the port on your proxy server to use /// </summary> public int ProxyPort { get { return cc.ProxyPort; } set { cc.ProxyPort = value; } } /// <summary> /// Sets the port on your proxy server to use /// </summary> /// <param name="proxyPort">port number</param> /// <returns>this instance</returns> public MarketplaceWebServiceProductsConfig WithProxyPort(int proxyPort) { this.ProxyPort = proxyPort; return this; } /// <summary> /// Checks if proxy port is set /// </summary> /// <returns>true if proxy port is set</returns> public bool IsSetProxyPort() { return cc.ProxyPort != -1; } /// <summary> /// Gets and sets the username to use with your proxy server /// </summary> public string ProxyUsername { get { return cc.ProxyUsername; } set { cc.ProxyUsername = value; } } /// <summary> /// Sets the username to use with your proxy server /// </summary> /// <param name="proxyUsername">proxy username</param> /// <returns>this instance</returns> public MarketplaceWebServiceProductsConfig WithProxyUsername(string proxyUsername) { this.ProxyUsername = proxyUsername; return this; } /// <summary> /// Checks if proxy username is set /// </summary> /// <returns>true if proxy username is set</returns> public bool IsSetProxyUsername() { return this.ProxyUsername != null; } /// <summary> /// Gets and sets the password to use with your proxy server /// </summary> public string ProxyPassword { get { return cc.ProxyPassword; } set { cc.ProxyPassword = value; } } /// <summary> /// Sets the password to use with your proxy server /// </summary> /// <param name="proxyPassword">proxy password</param> /// <returns>this instance</returns> public MarketplaceWebServiceProductsConfig WithProxyPassword(string proxyPassword) { this.ProxyPassword = proxyPassword; return this; } /// <summary> /// Checks if proxy password is set /// </summary> /// <returns>true if proxy password is set</returns> public bool IsSetProxyPassword() { return this.ProxyPassword != null; } /// <summary> /// Gets and sets the maximum number of times to retry failed requests /// </summary> public int MaxErrorRetry { get { return cc.MaxErrorRetry; } set { cc.MaxErrorRetry = value; } } /// <summary> /// Sets the maximum number of times to retry failed requests /// </summary> /// <param name="maxErrorRetry">times to retry</param> /// <returns>this instance</returns> public MarketplaceWebServiceProductsConfig WithMaxErrorRetry(int maxErrorRetry) { cc.MaxErrorRetry = maxErrorRetry; return this; } /// <summary> /// Checks if MaxErrorRetry is set /// </summary> /// <returns>true if MaxErrorRetry is set</returns> public bool IsSetMaxErrorRetry() { return cc.MaxErrorRetry != -1; } /// <summary> /// Sets the value of a request header to be included on every request /// </summary> /// <param name="name">the name of the header to set</param> /// <param name="value">value to send with header</param> public void IncludeRequestHeader(string name, string value) { cc.IncludeRequestHeader(name, value); } /// <summary> /// Sets the value of a request header to be included on every request /// </summary> /// <param name="name">the name of the header to set</param> /// <param name="value">value to send with header</param> /// <returns>the current config object</returns> public MarketplaceWebServiceProductsConfig WithRequestHeader(string name, string value) { cc.IncludeRequestHeader(name, value); return this; } /// <summary> /// Gets the currently set value of a request header /// </summary> /// <param name="name">name the name of the header to get</param> /// <returns>value of specified header, or null if not defined</returns> public string GetRequestHeader(string name) { return cc.GetRequestHeader(name); } /// <summary> /// Checks if a request header is set /// </summary> /// <param name="name">the name of the header to check</param> /// <returns>true, if the header is set</returns> public bool IsSetRequestHeader(string name) { return cc.GetRequestHeader(name) != null; } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System.Collections; // IEnumerator using System.Collections.Generic; // List<T> using System.Collections.Specialized; // NotifyCollectionChangedEventHandler using System.Collections.ObjectModel; // Collection using System.ComponentModel; // PropertyChangedEventArgs using System.Diagnostics; // Debug using System.Windows.Media; // VisualOperations using MS.Internal.Controls; // EmptyEnumerator namespace System.Windows.Controls.Primitives { /// <summary> /// Base class for GridViewfRowPresenter and HeaderRowPresenter. /// </summary> public abstract class GridViewRowPresenterBase : FrameworkElement, IWeakEventListener { //------------------------------------------------------------------- // // Public Methods // //------------------------------------------------------------------- #region Public Methods /// <summary> /// Returns a string representation of this object. /// </summary> /// <returns></returns> public override string ToString() { return SR.Get(SRID.ToStringFormatString_GridViewRowPresenterBase, this.GetType(), (Columns != null) ? Columns.Count : 0); } #endregion //------------------------------------------------------------------- // // Public Properties // //------------------------------------------------------------------- #region Public Properties /// <summary> /// Columns DependencyProperty /// </summary> public static readonly DependencyProperty ColumnsProperty = DependencyProperty.Register( "Columns", typeof(GridViewColumnCollection), typeof(GridViewRowPresenterBase), new FrameworkPropertyMetadata( (GridViewColumnCollection)null /* default value */, FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(ColumnsPropertyChanged)) ); /// <summary> /// Columns Property /// </summary> public GridViewColumnCollection Columns { get { return (GridViewColumnCollection)GetValue(ColumnsProperty); } set { SetValue(ColumnsProperty, value); } } #endregion //------------------------------------------------------------------- // // Protected Methods / Properties // //------------------------------------------------------------------- #region Protected Methods / Properties /// <summary> /// Returns enumerator to logical children. /// </summary> protected internal override IEnumerator LogicalChildren { get { if (InternalChildren.Count == 0) { // empty GridViewRowPresenterBase has *no* logical children; give empty enumerator return EmptyEnumerator.Instance; } // otherwise, its logical children is its visual children return InternalChildren.GetEnumerator(); } } /// <summary> /// Gets the Visual children count. /// </summary> protected override int VisualChildrenCount { get { if (_uiElementCollection == null) { return 0; } else { return _uiElementCollection.Count; } } } /// <summary> /// Gets the Visual child at the specified index. /// </summary> protected override Visual GetVisualChild(int index) { if (_uiElementCollection == null) { throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange)); } return _uiElementCollection[index]; } #endregion //------------------------------------------------------------------- // // Internal Methods / Properties // //------------------------------------------------------------------- #region Internal Methods /// <summary> /// process the column collection chagned event /// </summary> internal virtual void OnColumnCollectionChanged(GridViewColumnCollectionChangedEventArgs e) { if (DesiredWidthList != null) { if (e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Replace) { // NOTE: The steps to make DesiredWidthList.Count <= e.ActualIndex // // 1. init with 3 auto columns; // 2. add 1 column to the column collection with width 90.0; // 3. remove the column we jsut added to the the collection; // // Now we have DesiredWidthList.Count equals to 3 while the removed column // has ActualIndex equals to 3. // if (DesiredWidthList.Count > e.ActualIndex) { DesiredWidthList.RemoveAt(e.ActualIndex); } } else if (e.Action == NotifyCollectionChangedAction.Reset) { DesiredWidthList = null; } } } /// <summary> /// process the column property chagned event /// </summary> internal abstract void OnColumnPropertyChanged(GridViewColumn column, string propertyName); /// <summary> /// ensure ShareStateList have at least columns.Count items /// </summary> internal void EnsureDesiredWidthList() { GridViewColumnCollection columns = Columns; if (columns != null) { int count = columns.Count; if (DesiredWidthList == null) { DesiredWidthList = new List<double>(count); } int c = count - DesiredWidthList.Count; for (int i = 0; i < c; i++) { DesiredWidthList.Add(Double.NaN); } } } /// <summary> /// list of currently reached max value of DesiredWidth of cell in the column /// </summary> internal List<double> DesiredWidthList { get { return _desiredWidthList; } private set { _desiredWidthList = value; } } /// <summary> /// if visual tree is out of date /// </summary> internal bool NeedUpdateVisualTree { get { return _needUpdateVisualTree; } set { _needUpdateVisualTree = value; } } /// <summary> /// collection if children /// </summary> internal UIElementCollection InternalChildren { get { if (_uiElementCollection == null) //nobody used it yet { _uiElementCollection = new UIElementCollection(this /* visual parent */, this /* logical parent */); } return _uiElementCollection; } } // the minimum width for dummy header when measure internal const double c_PaddingHeaderMinWidth = 2.0; #endregion //------------------------------------------------------------------- // // Private Methods / Properties / Fields // //------------------------------------------------------------------- #region Private Methods / Properties / Fields // Property invalidation callback invoked when ColumnCollectionProperty is invalidated private static void ColumnsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { GridViewRowPresenterBase c = (GridViewRowPresenterBase)d; GridViewColumnCollection oldCollection = (GridViewColumnCollection)e.OldValue; if (oldCollection != null) { InternalCollectionChangedEventManager.RemoveHandler(oldCollection, c.ColumnCollectionChanged); // NOTE: // If the collection is NOT in view mode (a.k.a owner isn't GridView), // RowPresenter is responsible to be or to find one to be the collection's mentor. // if (!oldCollection.InViewMode && oldCollection.Owner == c.GetStableAncester()) { oldCollection.Owner = null; } } GridViewColumnCollection newCollection = (GridViewColumnCollection)e.NewValue; if (newCollection != null) { InternalCollectionChangedEventManager.AddHandler(newCollection, c.ColumnCollectionChanged); // Similar to what we do to oldCollection. But, of course, in a reverse way. if (!newCollection.InViewMode && newCollection.Owner == null) { newCollection.Owner = c.GetStableAncester(); } } c.NeedUpdateVisualTree = true; c.InvalidateMeasure(); } // // NOTE: // // If the collection is NOT in view mode, RowPresenter should be mentor of the Collection. // But if presenter + collection are used to restyle ListBoxItems and the ItemsPanel is // VSP, there are 2 problems: // // 1. each RowPresenter want to be the mentor, too many context change event // 2. when doing scroll, VSP will dispose those LB items which are out of view. But they // are still referenced by the Collecion (at the Owner property) - memory leak. // // Solution: // If RowPresenter is inside an ItemsControl (IC\LB\CB), use the ItemsControl as the // mentor. Therefore, // - context change is minimized because ItemsControl for different items is the same; // - no memory leak because when viturlizing, only dispose items not the IC itself. // private FrameworkElement GetStableAncester() { ItemsControl ic = ItemsControl.ItemsControlFromItemContainer(TemplatedParent); return (ic != null) ? ic : (FrameworkElement)this; } // if and only if both conditions below are satisfied, row presenter visual is ready. // 1. is initialized, which ensures RowPresenter is created // 2. !NeedUpdateVisualTree, which ensures all visual elements generated by RowPresenter are created private bool IsPresenterVisualReady { get { return (IsInitialized && !NeedUpdateVisualTree); } } /// <summary> /// Handle events from the centralized event table /// </summary> bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs args) { return false; // this method is no longer used (but must remain, for compat) } /// <summary> /// Handler of GridViewColumnCollection.CollectionChanged event. /// </summary> private void ColumnCollectionChanged(object sender, NotifyCollectionChangedEventArgs arg) { GridViewColumnCollectionChangedEventArgs e = arg as GridViewColumnCollectionChangedEventArgs; if (e != null && IsPresenterVisualReady)// if and only if rowpresenter's visual is ready, shall rowpresenter go ahead process the event. { // Property of one column changed if (e.Column != null) { OnColumnPropertyChanged(e.Column, e.PropertyName); } else { OnColumnCollectionChanged(e); } } } private UIElementCollection _uiElementCollection; private bool _needUpdateVisualTree = true; private List<double> _desiredWidthList; #endregion } /// <summary> /// Manager for the GridViewColumnCollection.CollectionChanged event. /// </summary> internal class InternalCollectionChangedEventManager : WeakEventManager { #region Constructors // // Constructors // private InternalCollectionChangedEventManager() { } #endregion Constructors #region Public Methods // // Public Methods // /// <summary> /// Add a listener to the given source's event. /// </summary> public static void AddListener(GridViewColumnCollection source, IWeakEventListener listener) { if (source == null) throw new ArgumentNullException("source"); if (listener == null) throw new ArgumentNullException("listener"); CurrentManager.ProtectedAddListener(source, listener); } /// <summary> /// Remove a listener to the given source's event. /// </summary> public static void RemoveListener(GridViewColumnCollection source, IWeakEventListener listener) { if (source == null) throw new ArgumentNullException("source"); if (listener == null) throw new ArgumentNullException("listener"); CurrentManager.ProtectedRemoveListener(source, listener); } /// <summary> /// Add a handler for the given source's event. /// </summary> public static void AddHandler(GridViewColumnCollection source, EventHandler<NotifyCollectionChangedEventArgs> handler) { if (handler == null) throw new ArgumentNullException("handler"); CurrentManager.ProtectedAddHandler(source, handler); } /// <summary> /// Remove a handler for the given source's event. /// </summary> public static void RemoveHandler(GridViewColumnCollection source, EventHandler<NotifyCollectionChangedEventArgs> handler) { if (handler == null) throw new ArgumentNullException("handler"); CurrentManager.ProtectedRemoveHandler(source, handler); } #endregion Public Methods #region Protected Methods // // Protected Methods // /// <summary> /// Return a new list to hold listeners to the event. /// </summary> protected override ListenerList NewListenerList() { return new ListenerList<NotifyCollectionChangedEventArgs>(); } /// <summary> /// Listen to the given source for the event. /// </summary> protected override void StartListening(object source) { GridViewColumnCollection typedSource = (GridViewColumnCollection)source; typedSource.InternalCollectionChanged += new NotifyCollectionChangedEventHandler(OnCollectionChanged); } /// <summary> /// Stop listening to the given source for the event. /// </summary> protected override void StopListening(object source) { GridViewColumnCollection typedSource = (GridViewColumnCollection)source; typedSource.InternalCollectionChanged -= new NotifyCollectionChangedEventHandler(OnCollectionChanged); } #endregion Protected Methods #region Private Properties // // Private Properties // // get the event manager for the current thread private static InternalCollectionChangedEventManager CurrentManager { get { Type managerType = typeof(InternalCollectionChangedEventManager); InternalCollectionChangedEventManager manager = (InternalCollectionChangedEventManager)GetCurrentManager(managerType); // at first use, create and register a new manager if (manager == null) { manager = new InternalCollectionChangedEventManager(); SetCurrentManager(managerType, manager); } return manager; } } #endregion Private Properties #region Private Methods // // Private Methods // // event handler for CollectionChanged event private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs args) { DeliverEvent(sender, args); } #endregion Private Methods } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Collections.Generic; using System.Linq; namespace NLog.Layouts { using System; using System.Collections.ObjectModel; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; /// <summary> /// Represents a string with embedded placeholders that can render contextual information. /// </summary> /// <remarks> /// This layout is not meant to be used explicitly. Instead you can just use a string containing layout /// renderers everywhere the layout is required. /// </remarks> [Layout("SimpleLayout")] [ThreadAgnostic] [AppDomainFixedOutput] public class SimpleLayout : Layout, IUsesStackTrace { private const int MaxInitialRenderBufferLength = 16384; private int maxRenderedLength; private string fixedText; private string layoutText; private ConfigurationItemFactory configurationItemFactory; /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout" /> class. /// </summary> public SimpleLayout() : this(string.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout" /> class. /// </summary> /// <param name="txt">The layout string to parse.</param> public SimpleLayout(string txt) : this(txt, ConfigurationItemFactory.Default) { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout"/> class. /// </summary> /// <param name="txt">The layout string to parse.</param> /// <param name="configurationItemFactory">The NLog factories to use when creating references to layout renderers.</param> public SimpleLayout(string txt, ConfigurationItemFactory configurationItemFactory) { this.configurationItemFactory = configurationItemFactory; this.Text = txt; } internal SimpleLayout(LayoutRenderer[] renderers, string text, ConfigurationItemFactory configurationItemFactory) { this.configurationItemFactory = configurationItemFactory; this.SetRenderers(renderers, text); } /// <summary> /// Original text before compile to Layout renderes /// </summary> public string OriginalText { get; private set; } /// <summary> /// Gets or sets the layout text. /// </summary> /// <docgen category='Layout Options' order='10' /> public string Text { get { return this.layoutText; } set { OriginalText = value; LayoutRenderer[] renderers; string txt; renderers = LayoutParser.CompileLayout( this.configurationItemFactory, new SimpleStringReader(value), false, out txt); this.SetRenderers(renderers, txt); } } /// <summary> /// Is the message fixed? (no Layout renderers used) /// </summary> public bool IsFixedText { get { return this.fixedText != null; } } /// <summary> /// Get the fixed text. Only set when <see cref="IsFixedText"/> is <c>true</c> /// </summary> public string FixedText { get { return fixedText; } } /// <summary> /// Gets a collection of <see cref="LayoutRenderer"/> objects that make up this layout. /// </summary> public ReadOnlyCollection<LayoutRenderer> Renderers { get; private set; } /// <summary> /// Gets the level of stack trace information required for rendering. /// </summary> /// <remarks>Calculated when setting <see cref="Renderers"/>.</remarks> public StackTraceUsage StackTraceUsage { get; private set; } /// <summary> /// Converts a text to a simple layout. /// </summary> /// <param name="text">Text to be converted.</param> /// <returns>A <see cref="SimpleLayout"/> object.</returns> public static implicit operator SimpleLayout(string text) { return new SimpleLayout(text); } /// <summary> /// Escapes the passed text so that it can /// be used literally in all places where /// layout is normally expected without being /// treated as layout. /// </summary> /// <param name="text">The text to be escaped.</param> /// <returns>The escaped text.</returns> /// <remarks> /// Escaping is done by replacing all occurrences of /// '${' with '${literal:text=${}' /// </remarks> public static string Escape(string text) { return text.Replace("${", "${literal:text=${}"); } /// <summary> /// Evaluates the specified text by expanding all layout renderers. /// </summary> /// <param name="text">The text to be evaluated.</param> /// <param name="logEvent">Log event to be used for evaluation.</param> /// <returns>The input text with all occurrences of ${} replaced with /// values provided by the appropriate layout renderers.</returns> public static string Evaluate(string text, LogEventInfo logEvent) { var l = new SimpleLayout(text); return l.Render(logEvent); } /// <summary> /// Evaluates the specified text by expanding all layout renderers /// in new <see cref="LogEventInfo" /> context. /// </summary> /// <param name="text">The text to be evaluated.</param> /// <returns>The input text with all occurrences of ${} replaced with /// values provided by the appropriate layout renderers.</returns> public static string Evaluate(string text) { return Evaluate(text, LogEventInfo.CreateNullEvent()); } /// <summary> /// Returns a <see cref="T:System.String"></see> that represents the current object. /// </summary> /// <returns> /// A <see cref="T:System.String"></see> that represents the current object. /// </returns> public override string ToString() { return "'" + this.Text + "'"; } internal void SetRenderers(LayoutRenderer[] renderers, string text) { this.Renderers = new ReadOnlyCollection<LayoutRenderer>(renderers); if (this.Renderers.Count == 0) { //todo fixedText = null is also used if the text is fixed, but is a empty renderers not fixed? this.fixedText = null; this.StackTraceUsage = StackTraceUsage.None; } else if (this.Renderers.Count == 1 && this.Renderers[0] is LiteralLayoutRenderer) { this.fixedText = ((LiteralLayoutRenderer)this.Renderers[0]).Text; this.StackTraceUsage = StackTraceUsage.None; } else { this.fixedText = null; this.StackTraceUsage = this.Renderers.OfType<IUsesStackTrace>().DefaultIfEmpty().Max(usage => usage == null ? StackTraceUsage.None : usage.StackTraceUsage); } this.layoutText = text; } /// <summary> /// Initializes the layout. /// </summary> protected override void InitializeLayout() { for (int i = 0; i < this.Renderers.Count; i++) { LayoutRenderer renderer = this.Renderers[i]; try { renderer.Initialize(LoggingConfiguration); } catch (Exception exception) { //also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error //check for performance if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(exception, "Exception in '{0}.InitializeLayout()'", renderer.GetType().FullName); } if (exception.MustBeRethrown()) { throw; } } } base.InitializeLayout(); } /// <summary> /// Renders the layout for the specified logging event by invoking layout renderers /// that make up the event. /// </summary> /// <param name="logEvent">The logging event.</param> /// <returns>The rendered layout.</returns> protected override string GetFormattedMessage(LogEventInfo logEvent) { if (IsFixedText) { return this.fixedText; } string cachedValue; if (logEvent.TryGetCachedLayoutValue(this, out cachedValue)) { return cachedValue; } int initialSize = this.maxRenderedLength; if (initialSize > MaxInitialRenderBufferLength) { initialSize = MaxInitialRenderBufferLength; } var builder = new StringBuilder(initialSize); //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < this.Renderers.Count; i++) { LayoutRenderer renderer = this.Renderers[i]; try { renderer.Render(builder, logEvent); } catch (Exception exception) { //also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error //check for performance if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(exception, "Exception in '{0}.Append()'", renderer.GetType().FullName); } if (exception.MustBeRethrown()) { throw; } } } if (builder.Length > this.maxRenderedLength) { this.maxRenderedLength = builder.Length; } string value = builder.ToString(); logEvent.AddCachedLayoutValue(this, value); return value; } } }
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Log4NetIntegration.Logging { using System; using System.Globalization; using MassTransit.Logging; public class Log4NetLog : ILog { readonly log4net.ILog _log; public Log4NetLog(log4net.ILog log) { _log = log; } public void Debug(object message) { _log.Debug(message); } public void Debug(object message, Exception exception) { _log.Debug(message, exception); } public void Debug(LogOutputProvider messageProvider) { if (!IsDebugEnabled) return; _log.Debug(messageProvider()); } public void DebugFormat(string format, params object[] args) { _log.DebugFormat(format, args); } public void DebugFormat(IFormatProvider provider, string format, params object[] args) { _log.DebugFormat(provider, format, args); } public void Info(object message) { _log.Info(message); } public void Info(object message, Exception exception) { _log.Info(message, exception); } public void Info(LogOutputProvider messageProvider) { if (!IsInfoEnabled) return; _log.Info(messageProvider()); } public void InfoFormat(string format, params object[] args) { _log.InfoFormat(format, args); } public void InfoFormat(IFormatProvider provider, string format, params object[] args) { _log.InfoFormat(provider, format, args); } public void Warn(object message) { _log.Warn(message); } public void Warn(object message, Exception exception) { _log.Warn(message, exception); } public void Warn(LogOutputProvider messageProvider) { if (!IsWarnEnabled) return; _log.Warn(messageProvider()); } public void WarnFormat(string format, params object[] args) { _log.WarnFormat(format, args); } public void WarnFormat(IFormatProvider provider, string format, params object[] args) { _log.WarnFormat(provider, format, args); } public void Error(object message) { _log.Error(message); } public void Error(object message, Exception exception) { _log.Error(message, exception); } public void Error(LogOutputProvider messageProvider) { if (!IsErrorEnabled) return; _log.Error(messageProvider()); } public void ErrorFormat(string format, params object[] args) { _log.ErrorFormat(format, args); } public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { _log.ErrorFormat(provider, format, args); } public void Fatal(object message) { _log.Fatal(message); } public void Fatal(object message, Exception exception) { _log.Fatal(message, exception); } public void Fatal(LogOutputProvider messageProvider) { if (!IsFatalEnabled) return; _log.Fatal(messageProvider()); } public void FatalFormat(string format, params object[] args) { _log.FatalFormat(format, args); } public void FatalFormat(IFormatProvider provider, string format, params object[] args) { _log.FatalFormat(provider, format, args); } public bool IsDebugEnabled { get { return _log.IsDebugEnabled; } } public bool IsInfoEnabled { get { return _log.IsInfoEnabled; } } public bool IsWarnEnabled { get { return _log.IsWarnEnabled; } } public bool IsErrorEnabled { get { return _log.IsErrorEnabled; } } public bool IsFatalEnabled { get { return _log.IsFatalEnabled; } } public void Log(LogLevel level, object obj) { if (level == LogLevel.Fatal) Fatal(obj); else if (level == LogLevel.Error) Error(obj); else if (level == LogLevel.Warn) Warn(obj); else if (level == LogLevel.Info) Info(obj); else if (level >= LogLevel.Debug) Debug(obj); } public void Log(LogLevel level, object obj, Exception exception) { if (level == LogLevel.Fatal) Fatal(obj, exception); else if (level == LogLevel.Error) Error(obj, exception); else if (level == LogLevel.Warn) Warn(obj, exception); else if (level == LogLevel.Info) Info(obj, exception); else if (level >= LogLevel.Debug) Debug(obj, exception); } public void Log(LogLevel level, LogOutputProvider messageProvider) { if (level == LogLevel.Fatal) Fatal(messageProvider); else if (level == LogLevel.Error) Error(messageProvider); else if (level == LogLevel.Warn) Warn(messageProvider); else if (level == LogLevel.Info) Info(messageProvider); else if (level >= LogLevel.Debug) Debug(messageProvider); } public void LogFormat(LogLevel level, string format, params object[] args) { if (level == LogLevel.Fatal) FatalFormat(CultureInfo.InvariantCulture, format, args); else if (level == LogLevel.Error) ErrorFormat(CultureInfo.InvariantCulture, format, args); else if (level == LogLevel.Warn) WarnFormat(CultureInfo.InvariantCulture, format, args); else if (level == LogLevel.Info) InfoFormat(CultureInfo.InvariantCulture, format, args); else if (level >= LogLevel.Debug) DebugFormat(CultureInfo.InvariantCulture, format, args); } public void LogFormat(LogLevel level, IFormatProvider formatProvider, string format, params object[] args) { if (level == LogLevel.Fatal) FatalFormat(formatProvider, format, args); else if (level == LogLevel.Error) ErrorFormat(formatProvider, format, args); else if (level == LogLevel.Warn) WarnFormat(formatProvider, format, args); else if (level == LogLevel.Info) InfoFormat(formatProvider, format, args); else if (level >= LogLevel.Debug) DebugFormat(formatProvider, format, args); } } }
using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Serialization.Objects; using JsonApiDotNetCoreTests.Startups; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.Links { public sealed class RelativeLinksWithoutNamespaceTests : IClassFixture<IntegrationTestContext<RelativeLinksNoNamespaceStartup<LinksDbContext>, LinksDbContext>> { private readonly IntegrationTestContext<RelativeLinksNoNamespaceStartup<LinksDbContext>, LinksDbContext> _testContext; private readonly LinksFakers _fakers = new(); public RelativeLinksWithoutNamespaceTests(IntegrationTestContext<RelativeLinksNoNamespaceStartup<LinksDbContext>, LinksDbContext> testContext) { _testContext = testContext; testContext.UseController<PhotoAlbumsController>(); testContext.UseController<PhotosController>(); testContext.ConfigureServicesAfterStartup(services => { services.AddScoped(typeof(IResourceChangeTracker<>), typeof(NeverSameResourceChangeTracker<>)); }); var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>(); options.IncludeTotalResourceCount = true; } [Fact] public async Task Get_primary_resource_by_ID_returns_relative_links() { // Arrange PhotoAlbum album = _fakers.PhotoAlbum.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.PhotoAlbums.Add(album); await dbContext.SaveChangesAsync(); }); string route = $"/photoAlbums/{album.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Links.Self.Should().Be(route); responseDocument.Links.Related.Should().BeNull(); responseDocument.Links.First.Should().BeNull(); responseDocument.Links.Last.Should().BeNull(); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().BeNull(); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Links.Self.Should().Be(route); responseDocument.Data.SingleValue.Relationships["photos"].Links.Self.Should().Be($"{route}/relationships/photos"); responseDocument.Data.SingleValue.Relationships["photos"].Links.Related.Should().Be($"{route}/photos"); } [Fact] public async Task Get_primary_resources_with_include_returns_relative_links() { // Arrange PhotoAlbum album = _fakers.PhotoAlbum.Generate(); album.Photos = _fakers.Photo.Generate(1).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<PhotoAlbum>(); dbContext.PhotoAlbums.Add(album); await dbContext.SaveChangesAsync(); }); const string route = "/photoAlbums?include=photos"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Links.Self.Should().Be(route); responseDocument.Links.Related.Should().BeNull(); responseDocument.Links.First.Should().Be(route); responseDocument.Links.Last.Should().Be(route); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().BeNull(); string albumLink = $"/photoAlbums/{album.StringId}"; responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Links.Self.Should().Be(albumLink); responseDocument.Data.ManyValue[0].Relationships["photos"].Links.Self.Should().Be($"{albumLink}/relationships/photos"); responseDocument.Data.ManyValue[0].Relationships["photos"].Links.Related.Should().Be($"{albumLink}/photos"); string photoLink = $"/photos/{album.Photos.ElementAt(0).StringId}"; responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Links.Self.Should().Be(photoLink); responseDocument.Included[0].Relationships["album"].Links.Self.Should().Be($"{photoLink}/relationships/album"); responseDocument.Included[0].Relationships["album"].Links.Related.Should().Be($"{photoLink}/album"); } [Fact] public async Task Get_secondary_resource_returns_relative_links() { // Arrange Photo photo = _fakers.Photo.Generate(); photo.Album = _fakers.PhotoAlbum.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Photos.Add(photo); await dbContext.SaveChangesAsync(); }); string route = $"/photos/{photo.StringId}/album"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Links.Self.Should().Be(route); responseDocument.Links.Related.Should().BeNull(); responseDocument.Links.First.Should().BeNull(); responseDocument.Links.Last.Should().BeNull(); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().BeNull(); string albumLink = $"/photoAlbums/{photo.Album.StringId}"; responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Links.Self.Should().Be(albumLink); responseDocument.Data.SingleValue.Relationships["photos"].Links.Self.Should().Be($"{albumLink}/relationships/photos"); responseDocument.Data.SingleValue.Relationships["photos"].Links.Related.Should().Be($"{albumLink}/photos"); } [Fact] public async Task Get_secondary_resources_returns_relative_links() { // Arrange PhotoAlbum album = _fakers.PhotoAlbum.Generate(); album.Photos = _fakers.Photo.Generate(1).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.PhotoAlbums.Add(album); await dbContext.SaveChangesAsync(); }); string route = $"/photoAlbums/{album.StringId}/photos"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Links.Self.Should().Be(route); responseDocument.Links.Related.Should().BeNull(); responseDocument.Links.First.Should().Be(route); responseDocument.Links.Last.Should().BeNull(); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().BeNull(); string photoLink = $"/photos/{album.Photos.ElementAt(0).StringId}"; responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Links.Self.Should().Be(photoLink); responseDocument.Data.ManyValue[0].Relationships["album"].Links.Self.Should().Be($"{photoLink}/relationships/album"); responseDocument.Data.ManyValue[0].Relationships["album"].Links.Related.Should().Be($"{photoLink}/album"); } [Fact] public async Task Get_ToOne_relationship_returns_relative_links() { // Arrange Photo photo = _fakers.Photo.Generate(); photo.Album = _fakers.PhotoAlbum.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Photos.Add(photo); await dbContext.SaveChangesAsync(); }); string route = $"/photos/{photo.StringId}/relationships/album"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Links.Self.Should().Be(route); responseDocument.Links.Related.Should().Be($"/photos/{photo.StringId}/album"); responseDocument.Links.First.Should().BeNull(); responseDocument.Links.Last.Should().BeNull(); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().BeNull(); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Links.Should().BeNull(); responseDocument.Data.SingleValue.Relationships.Should().BeNull(); } [Fact] public async Task Get_ToMany_relationship_returns_relative_links() { // Arrange PhotoAlbum album = _fakers.PhotoAlbum.Generate(); album.Photos = _fakers.Photo.Generate(1).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.PhotoAlbums.Add(album); await dbContext.SaveChangesAsync(); }); string route = $"/photoAlbums/{album.StringId}/relationships/photos"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Links.Self.Should().Be(route); responseDocument.Links.Related.Should().Be($"/photoAlbums/{album.StringId}/photos"); responseDocument.Links.First.Should().Be(route); responseDocument.Links.Last.Should().BeNull(); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().BeNull(); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Links.Should().BeNull(); responseDocument.Data.ManyValue[0].Relationships.Should().BeNull(); } [Fact] public async Task Create_resource_with_side_effects_and_include_returns_relative_links() { // Arrange Photo existingPhoto = _fakers.Photo.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Photos.Add(existingPhoto); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "photoAlbums", relationships = new { photos = new { data = new[] { new { type = "photos", id = existingPhoto.StringId } } } } } }; const string route = "/photoAlbums?include=photos"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Links.Self.Should().Be(route); responseDocument.Links.Related.Should().BeNull(); responseDocument.Links.First.Should().BeNull(); responseDocument.Links.Last.Should().BeNull(); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().BeNull(); string albumLink = $"/photoAlbums/{responseDocument.Data.SingleValue.Id}"; responseDocument.Data.SingleValue.Links.Self.Should().Be(albumLink); responseDocument.Data.SingleValue.Relationships["photos"].Links.Self.Should().Be($"{albumLink}/relationships/photos"); responseDocument.Data.SingleValue.Relationships["photos"].Links.Related.Should().Be($"{albumLink}/photos"); string photoLink = $"/photos/{existingPhoto.StringId}"; responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Links.Self.Should().Be(photoLink); responseDocument.Included[0].Relationships["album"].Links.Self.Should().Be($"{photoLink}/relationships/album"); responseDocument.Included[0].Relationships["album"].Links.Related.Should().Be($"{photoLink}/album"); } [Fact] public async Task Update_resource_with_side_effects_and_include_returns_relative_links() { // Arrange Photo existingPhoto = _fakers.Photo.Generate(); PhotoAlbum existingAlbum = _fakers.PhotoAlbum.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingPhoto, existingAlbum); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "photos", id = existingPhoto.StringId, relationships = new { album = new { data = new { type = "photoAlbums", id = existingAlbum.StringId } } } } }; string route = $"/photos/{existingPhoto.StringId}?include=album"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Links.Self.Should().Be(route); responseDocument.Links.Related.Should().BeNull(); responseDocument.Links.First.Should().BeNull(); responseDocument.Links.Last.Should().BeNull(); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().BeNull(); string photoLink = $"/photos/{existingPhoto.StringId}"; responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Links.Self.Should().Be(photoLink); responseDocument.Data.SingleValue.Relationships["album"].Links.Self.Should().Be($"{photoLink}/relationships/album"); responseDocument.Data.SingleValue.Relationships["album"].Links.Related.Should().Be($"{photoLink}/album"); string albumLink = $"/photoAlbums/{existingAlbum.StringId}"; responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Links.Self.Should().Be(albumLink); responseDocument.Included[0].Relationships["photos"].Links.Self.Should().Be($"{albumLink}/relationships/photos"); responseDocument.Included[0].Relationships["photos"].Links.Related.Should().Be($"{albumLink}/photos"); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Data/PokedexEntry.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Data { /// <summary>Holder for reflection information generated from POGOProtos/Data/PokedexEntry.proto</summary> public static partial class PokedexEntryReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Data/PokedexEntry.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static PokedexEntryReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiJQT0dPUHJvdG9zL0RhdGEvUG9rZWRleEVudHJ5LnByb3RvEg9QT0dPUHJv", "dG9zLkRhdGEaIFBPR09Qcm90b3MvRW51bXMvUG9rZW1vbklkLnByb3RvIqwB", "CgxQb2tlZGV4RW50cnkSLwoKcG9rZW1vbl9pZBgBIAEoDjIbLlBPR09Qcm90", "b3MuRW51bXMuUG9rZW1vbklkEhkKEXRpbWVzX2VuY291bnRlcmVkGAIgASgF", "EhYKDnRpbWVzX2NhcHR1cmVkGAMgASgFEh4KFmV2b2x1dGlvbl9zdG9uZV9w", "aWVjZXMYBCABKAUSGAoQZXZvbHV0aW9uX3N0b25lcxgFIAEoBWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::POGOProtos.Enums.PokemonIdReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Data.PokedexEntry), global::POGOProtos.Data.PokedexEntry.Parser, new[]{ "PokemonId", "TimesEncountered", "TimesCaptured", "EvolutionStonePieces", "EvolutionStones" }, null, null, null) })); } #endregion } #region Messages public sealed partial class PokedexEntry : pb::IMessage<PokedexEntry> { private static readonly pb::MessageParser<PokedexEntry> _parser = new pb::MessageParser<PokedexEntry>(() => new PokedexEntry()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PokedexEntry> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Data.PokedexEntryReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PokedexEntry() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PokedexEntry(PokedexEntry other) : this() { pokemonId_ = other.pokemonId_; timesEncountered_ = other.timesEncountered_; timesCaptured_ = other.timesCaptured_; evolutionStonePieces_ = other.evolutionStonePieces_; evolutionStones_ = other.evolutionStones_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PokedexEntry Clone() { return new PokedexEntry(this); } /// <summary>Field number for the "pokemon_id" field.</summary> public const int PokemonIdFieldNumber = 1; private global::POGOProtos.Enums.PokemonId pokemonId_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Enums.PokemonId PokemonId { get { return pokemonId_; } set { pokemonId_ = value; } } /// <summary>Field number for the "times_encountered" field.</summary> public const int TimesEncounteredFieldNumber = 2; private int timesEncountered_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int TimesEncountered { get { return timesEncountered_; } set { timesEncountered_ = value; } } /// <summary>Field number for the "times_captured" field.</summary> public const int TimesCapturedFieldNumber = 3; private int timesCaptured_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int TimesCaptured { get { return timesCaptured_; } set { timesCaptured_ = value; } } /// <summary>Field number for the "evolution_stone_pieces" field.</summary> public const int EvolutionStonePiecesFieldNumber = 4; private int evolutionStonePieces_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int EvolutionStonePieces { get { return evolutionStonePieces_; } set { evolutionStonePieces_ = value; } } /// <summary>Field number for the "evolution_stones" field.</summary> public const int EvolutionStonesFieldNumber = 5; private int evolutionStones_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int EvolutionStones { get { return evolutionStones_; } set { evolutionStones_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PokedexEntry); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PokedexEntry other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (PokemonId != other.PokemonId) return false; if (TimesEncountered != other.TimesEncountered) return false; if (TimesCaptured != other.TimesCaptured) return false; if (EvolutionStonePieces != other.EvolutionStonePieces) return false; if (EvolutionStones != other.EvolutionStones) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (PokemonId != 0) hash ^= PokemonId.GetHashCode(); if (TimesEncountered != 0) hash ^= TimesEncountered.GetHashCode(); if (TimesCaptured != 0) hash ^= TimesCaptured.GetHashCode(); if (EvolutionStonePieces != 0) hash ^= EvolutionStonePieces.GetHashCode(); if (EvolutionStones != 0) hash ^= EvolutionStones.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (PokemonId != 0) { output.WriteRawTag(8); output.WriteEnum((int) PokemonId); } if (TimesEncountered != 0) { output.WriteRawTag(16); output.WriteInt32(TimesEncountered); } if (TimesCaptured != 0) { output.WriteRawTag(24); output.WriteInt32(TimesCaptured); } if (EvolutionStonePieces != 0) { output.WriteRawTag(32); output.WriteInt32(EvolutionStonePieces); } if (EvolutionStones != 0) { output.WriteRawTag(40); output.WriteInt32(EvolutionStones); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (PokemonId != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) PokemonId); } if (TimesEncountered != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(TimesEncountered); } if (TimesCaptured != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(TimesCaptured); } if (EvolutionStonePieces != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(EvolutionStonePieces); } if (EvolutionStones != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(EvolutionStones); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PokedexEntry other) { if (other == null) { return; } if (other.PokemonId != 0) { PokemonId = other.PokemonId; } if (other.TimesEncountered != 0) { TimesEncountered = other.TimesEncountered; } if (other.TimesCaptured != 0) { TimesCaptured = other.TimesCaptured; } if (other.EvolutionStonePieces != 0) { EvolutionStonePieces = other.EvolutionStonePieces; } if (other.EvolutionStones != 0) { EvolutionStones = other.EvolutionStones; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { pokemonId_ = (global::POGOProtos.Enums.PokemonId) input.ReadEnum(); break; } case 16: { TimesEncountered = input.ReadInt32(); break; } case 24: { TimesCaptured = input.ReadInt32(); break; } case 32: { EvolutionStonePieces = input.ReadInt32(); break; } case 40: { EvolutionStones = input.ReadInt32(); break; } } } } } #endregion } #endregion Designer generated code
using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using OmniSharp.Models.AutoComplete; using TestUtility; using Xunit; using Xunit.Abstractions; namespace OmniSharp.Roslyn.CSharp.Tests { public class SnippetFacts : AbstractAutoCompleteTestFixture { private readonly ILogger _logger; public SnippetFacts(ITestOutputHelper output, SharedOmniSharpHostFixture sharedOmniSharpHostFixture) : base(output, sharedOmniSharpHostFixture) { this._logger = this.LoggerFactory.CreateLogger<SnippetFacts>(); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Can_template_generic_type_argument(string filename) { const string source = @"public class Class1 { public Class1() { var l = new System.Collections.Generic.Lis$$ } }"; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("List<${1:T}>()$0", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Can_return_method_type_arguments_snippets(string filename) { const string source = @"using System.Collections.Generic; public class Test { public string Get<SomeType>() { } } public class Class1 { public Class1() { var someObj = new Test(); someObj.G$$ } }"; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("Get<${1:SomeType}>()$0 : string", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Does_not_include_tsource_argument_type(string filename) { const string source = @"using System.Collections.Generic; using System.Linq; public class Class1 { public Class1() { var l = new List<string>(); l.Firs$$ } }"; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("First()$0 : string", completions); #if NETCOREAPP ContainsSnippet("FirstOrDefault(${1:Func<string, bool> predicate})$0 : string?", completions); #else ContainsSnippet("FirstOrDefault(${1:Func<string, bool> predicate})$0 : string", completions); #endif } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Does_not_include_tresult_argument_type(string filename) { const string source = @"using System.Collections.Generic; using System.Linq; public class Class1 { public Class1() { var dict = new Dictionary<string, object>(); dict.Sel$$ } }"; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("Select(${1:Func<KeyValuePair<string, object>, TResult> selector})$0 : IEnumerable<TResult>", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Can_template_field(string filename) { const string source = @"using System.Collections.Generic; public class Class1 { public int someField; public Class1() { somef$$ } }"; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("someField$0 : int", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Can_return_all_constructors(string filename) { const string source = @"public class MyClass { public MyClass() {} public MyClass(int param) {} public MyClass(int param, string param) {} } public class Class2 { public Class2() { var c = new My$$ } }"; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("MyClass()$0", completions); ContainsSnippet("MyClass(${1:int param})$0", completions); ContainsSnippet("MyClass(${1:int param}, ${2:string param})$0", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Can_template_generic_type_arguments(string filename) { const string source = @"using System.Collections.Generic; public class Class1 { public Class1() { var l = new Dict$$ } }"; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("Dictionary<${1:TKey}, ${2:TValue}>()$0", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Can_template_parameter(string filename) { const string source = @"using System.Collections.Generic; public class Class1 { public Class1() { var l = new Lis$$ } }"; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("List<${1:T}>(${2:IEnumerable<T> collection})$0", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Can_complete_namespace(string filename) { const string source = "using Sys$$"; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("System$0", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Can_complete_variable(string filename) { const string source = @" public class Class1 { public Class1() { var aVariable = 1; av$$ } } "; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("aVariable$0 : int", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Void_methods_end_with_semicolons(string filename) { const string source = @" using System; public class Class1 { public Class1() { Array.Sor$$ } } "; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("Sort(${1:Array array});$0 : void", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Fuzzy_matches_are_returned_when_first_letters_match(string filename) { const string source = @" using System; public class Class1 { public Class1() { Guid.nwg$$ } } "; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("NewGuid()$0 : Guid", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Fuzzy_matches_are_not_returned_when_first_letters_do_not_match(string filename) { const string source = @" using System; public class Class1 { public Class1() { Console.rl$$ } } "; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); var snippetTexts = GetSnippetTexts(completions); Assert.DoesNotContain("WriteLine();$0 : void", snippetTexts); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Can_complete_parameter(string filename) { const string source = @" public class Class1 { public Class1() { } public Class2(Class1 class1) { clas$$ } } "; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("class1$0 : Class1", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Can_return_keywords(string filename) { const string source = "usin$$"; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("using", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Returns_enums(string filename) { const string source = @"public enum Colors { Red, Blue } public class MyClass1 { public MyClass1() { Col$$ } }"; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); Assert.Single(completions); ContainsSnippet("Colors$0", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Returns_event_without_event_keyword(string filename) { const string source = @" public class MyClass1 { public event TickHandler TickChanged; public MyClass1() { Tick$$ } }"; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); Assert.Single(completions); ContainsSnippet("TickChanged$0 : TickHandler", completions); } [Theory] [InlineData("dummy.cs")] [InlineData("dummy.csx")] public async Task Returns_method_without_optional_params(string filename) { const string source = @" public class Class1 { public void OptionalParam(int i, string s = null) { } public void DoSomething() { Opt$$ } } "; var completions = await FindCompletionsAsync(filename, source, wantSnippet: true); ContainsSnippet("OptionalParam(${1:int i});$0 : void", completions); ContainsSnippet("OptionalParam(${1:int i}, ${2:string s = null});$0 : void", completions); } [Fact] public async Task Can_complete_global_variable_in_CSX() { const string source = @" var aVariable = 1; av$$ "; var completions = await FindCompletionsAsync("dummy.csx", source, wantSnippet: true); ContainsSnippet("aVariable$0 : int", completions); } [Fact] public async Task Can_return_global_method_type_arguments_snippets_in_CSX() { const string source = @"using System.Collections.Generic; public string Get<SomeType>() { } G$$ "; var completions = await FindCompletionsAsync("dummy.csx", source, wantSnippet: true); ContainsSnippet("Get<${1:SomeType}>()$0 : string", completions); } private static IEnumerable<string> GetSnippetTexts(IEnumerable<AutoCompleteResponse> responses) { return responses.Select(r => r.ReturnType != null ? r.Snippet + " : " + r.ReturnType : r.Snippet); } private void ContainsSnippet(string expected, IEnumerable<AutoCompleteResponse> responses) { var snippetTexts = GetSnippetTexts(responses); if (!snippetTexts.Contains(expected)) { var builder = new StringBuilder(); builder.AppendLine("Did not find - " + expected); foreach (var snippetText in snippetTexts) { builder.AppendLine(snippetText); } this._logger.LogError(builder.ToString()); } Assert.Contains(expected, snippetTexts); } } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// ItemTaxExemption /// </summary> [DataContract] public partial class ItemTaxExemption : IEquatable<ItemTaxExemption>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ItemTaxExemption" /> class. /// </summary> /// <param name="city">City.</param> /// <param name="countryCode">Country code (ISO-3166 two letter).</param> /// <param name="county">County.</param> /// <param name="postalCode">Postal code.</param> /// <param name="stateCode">State code.</param> public ItemTaxExemption(string city = default(string), string countryCode = default(string), string county = default(string), string postalCode = default(string), string stateCode = default(string)) { this.City = city; this.CountryCode = countryCode; this.County = county; this.PostalCode = postalCode; this.StateCode = stateCode; } /// <summary> /// City /// </summary> /// <value>City</value> [DataMember(Name="city", EmitDefaultValue=false)] public string City { get; set; } /// <summary> /// Country code (ISO-3166 two letter) /// </summary> /// <value>Country code (ISO-3166 two letter)</value> [DataMember(Name="country_code", EmitDefaultValue=false)] public string CountryCode { get; set; } /// <summary> /// County /// </summary> /// <value>County</value> [DataMember(Name="county", EmitDefaultValue=false)] public string County { get; set; } /// <summary> /// Postal code /// </summary> /// <value>Postal code</value> [DataMember(Name="postal_code", EmitDefaultValue=false)] public string PostalCode { get; set; } /// <summary> /// State code /// </summary> /// <value>State code</value> [DataMember(Name="state_code", EmitDefaultValue=false)] public string StateCode { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ItemTaxExemption {\n"); sb.Append(" City: ").Append(City).Append("\n"); sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); sb.Append(" County: ").Append(County).Append("\n"); sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); sb.Append(" StateCode: ").Append(StateCode).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as ItemTaxExemption); } /// <summary> /// Returns true if ItemTaxExemption instances are equal /// </summary> /// <param name="input">Instance of ItemTaxExemption to be compared</param> /// <returns>Boolean</returns> public bool Equals(ItemTaxExemption input) { if (input == null) return false; return ( this.City == input.City || (this.City != null && this.City.Equals(input.City)) ) && ( this.CountryCode == input.CountryCode || (this.CountryCode != null && this.CountryCode.Equals(input.CountryCode)) ) && ( this.County == input.County || (this.County != null && this.County.Equals(input.County)) ) && ( this.PostalCode == input.PostalCode || (this.PostalCode != null && this.PostalCode.Equals(input.PostalCode)) ) && ( this.StateCode == input.StateCode || (this.StateCode != null && this.StateCode.Equals(input.StateCode)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.City != null) hashCode = hashCode * 59 + this.City.GetHashCode(); if (this.CountryCode != null) hashCode = hashCode * 59 + this.CountryCode.GetHashCode(); if (this.County != null) hashCode = hashCode * 59 + this.County.GetHashCode(); if (this.PostalCode != null) hashCode = hashCode * 59 + this.PostalCode.GetHashCode(); if (this.StateCode != null) hashCode = hashCode * 59 + this.StateCode.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { // City (string) maxLength if(this.City != null && this.City.Length > 32) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for City, length must be less than 32.", new [] { "City" }); } // CountryCode (string) maxLength if(this.CountryCode != null && this.CountryCode.Length > 2) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CountryCode, length must be less than 2.", new [] { "CountryCode" }); } // County (string) maxLength if(this.County != null && this.County.Length > 32) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for County, length must be less than 32.", new [] { "County" }); } // PostalCode (string) maxLength if(this.PostalCode != null && this.PostalCode.Length > 20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PostalCode, length must be less than 20.", new [] { "PostalCode" }); } // StateCode (string) maxLength if(this.StateCode != null && this.StateCode.Length > 32) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for StateCode, length must be less than 32.", new [] { "StateCode" }); } yield break; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Collections; using System.Text; using System.Diagnostics; using System.Globalization; namespace System.Xml { // Represents a single node in the document. [DebuggerDisplay("{debuggerDisplayProxy}")] public abstract class XmlNode : IEnumerable { internal XmlNode parentNode; //this pointer is reused to save the userdata information, need to prevent internal user access the pointer directly. internal XmlNode() { } internal XmlNode(XmlDocument doc) { if (doc == null) throw new ArgumentException(SR.Xdom_Node_Null_Doc); this.parentNode = doc; } // Gets the name of the node. public abstract string Name { get; } // Gets or sets the value of the node. public virtual string Value { get { return null; } set { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.Xdom_Node_SetVal, NodeType.ToString())); } } // Gets the type of the current node. public abstract XmlNodeType NodeType { get; } // Gets the parent of this node (for nodes that can have parents). public virtual XmlNode ParentNode { get { Debug.Assert(parentNode != null); if (parentNode.NodeType != XmlNodeType.Document) { return parentNode; } // Linear lookup through the children of the document XmlLinkedNode firstChild = parentNode.FirstChild as XmlLinkedNode; if (firstChild != null) { XmlLinkedNode node = firstChild; do { if (node == this) { return parentNode; } node = node.next; } while (node != null && node != firstChild); } return null; } } // Gets all children of this node. public virtual XmlNodeList ChildNodes { get { return new XmlChildNodes(this); } } // Gets the node immediately preceding this node. public virtual XmlNode PreviousSibling { get { return null; } } // Gets the node immediately following this node. public virtual XmlNode NextSibling { get { return null; } } // Gets a XmlAttributeCollection containing the attributes // of this node. public virtual XmlAttributeCollection Attributes { get { return null; } } // Gets the XmlDocument that contains this node. public virtual XmlDocument OwnerDocument { get { Debug.Assert(parentNode != null); if (parentNode.NodeType == XmlNodeType.Document) return (XmlDocument)parentNode; return parentNode.OwnerDocument; } } // Gets the first child of this node. public virtual XmlNode FirstChild { get { XmlLinkedNode linkedNode = LastNode; if (linkedNode != null) return linkedNode.next; return null; } } // Gets the last child of this node. public virtual XmlNode LastChild { get { return LastNode; } } internal virtual bool IsContainer { get { return false; } } internal virtual XmlLinkedNode LastNode { get { return null; } set { } } internal bool AncestorNode(XmlNode node) { XmlNode n = this.ParentNode; while (n != null && n != this) { if (n == node) return true; n = n.ParentNode; } return false; } //trace to the top to find out its parent node. internal bool IsConnected() { XmlNode parent = ParentNode; while (parent != null && !(parent.NodeType == XmlNodeType.Document)) parent = parent.ParentNode; return parent != null; } // Inserts the specified node immediately before the specified reference node. public virtual XmlNode InsertBefore(XmlNode newChild, XmlNode refChild) { if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); if (refChild == null) return AppendChild(newChild); if (!IsContainer) throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain); if (refChild.ParentNode != this) throw new ArgumentException(SR.Xdom_Node_Insert_Path); if (newChild == refChild) return newChild; XmlDocument childDoc = newChild.OwnerDocument; XmlDocument thisDoc = OwnerDocument; if (childDoc != null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); if (!CanInsertBefore(newChild, refChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); if (newChild.ParentNode != null) newChild.ParentNode.RemoveChild(newChild); // special case for doc-fragment. if (newChild.NodeType == XmlNodeType.DocumentFragment) { XmlNode first = newChild.FirstChild; XmlNode node = first; if (node != null) { newChild.RemoveChild(node); InsertBefore(node, refChild); // insert the rest of the children after this one. InsertAfter(newChild, node); } return first; } if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); XmlLinkedNode newNode = (XmlLinkedNode)newChild; XmlLinkedNode refNode = (XmlLinkedNode)refChild; string newChildValue = newChild.Value; XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); if (args != null) BeforeEvent(args); if (refNode == FirstChild) { newNode.next = refNode; LastNode.next = newNode; newNode.SetParent(this); if (newNode.IsText) { if (refNode.IsText) { NestTextNodes(newNode, refNode); } } } else { XmlLinkedNode prevNode = (XmlLinkedNode)refNode.PreviousSibling; newNode.next = refNode; prevNode.next = newNode; newNode.SetParent(this); if (prevNode.IsText) { if (newNode.IsText) { NestTextNodes(prevNode, newNode); if (refNode.IsText) { NestTextNodes(newNode, refNode); } } else { if (refNode.IsText) { UnnestTextNodes(prevNode, refNode); } } } else { if (newNode.IsText) { if (refNode.IsText) { NestTextNodes(newNode, refNode); } } } } if (args != null) AfterEvent(args); return newNode; } // Inserts the specified node immediately after the specified reference node. public virtual XmlNode InsertAfter(XmlNode newChild, XmlNode refChild) { if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); if (refChild == null) return PrependChild(newChild); if (!IsContainer) throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain); if (refChild.ParentNode != this) throw new ArgumentException(SR.Xdom_Node_Insert_Path); if (newChild == refChild) return newChild; XmlDocument childDoc = newChild.OwnerDocument; XmlDocument thisDoc = OwnerDocument; if (childDoc != null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); if (!CanInsertAfter(newChild, refChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); if (newChild.ParentNode != null) newChild.ParentNode.RemoveChild(newChild); // special case for doc-fragment. if (newChild.NodeType == XmlNodeType.DocumentFragment) { XmlNode last = refChild; XmlNode first = newChild.FirstChild; XmlNode node = first; while (node != null) { XmlNode next = node.NextSibling; newChild.RemoveChild(node); InsertAfter(node, last); last = node; node = next; } return first; } if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); XmlLinkedNode newNode = (XmlLinkedNode)newChild; XmlLinkedNode refNode = (XmlLinkedNode)refChild; string newChildValue = newChild.Value; XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); if (args != null) BeforeEvent(args); if (refNode == LastNode) { newNode.next = refNode.next; refNode.next = newNode; LastNode = newNode; newNode.SetParent(this); if (refNode.IsText) { if (newNode.IsText) { NestTextNodes(refNode, newNode); } } } else { XmlLinkedNode nextNode = refNode.next; newNode.next = nextNode; refNode.next = newNode; newNode.SetParent(this); if (refNode.IsText) { if (newNode.IsText) { NestTextNodes(refNode, newNode); if (nextNode.IsText) { NestTextNodes(newNode, nextNode); } } else { if (nextNode.IsText) { UnnestTextNodes(refNode, nextNode); } } } else { if (newNode.IsText) { if (nextNode.IsText) { NestTextNodes(newNode, nextNode); } } } } if (args != null) AfterEvent(args); return newNode; } // Replaces the child node oldChild with newChild node. public virtual XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild) { XmlNode nextNode = oldChild.NextSibling; RemoveChild(oldChild); XmlNode node = InsertBefore(newChild, nextNode); return oldChild; } // Removes specified child node. public virtual XmlNode RemoveChild(XmlNode oldChild) { if (!IsContainer) throw new InvalidOperationException(SR.Xdom_Node_Remove_Contain); if (oldChild.ParentNode != this) throw new ArgumentException(SR.Xdom_Node_Remove_Child); XmlLinkedNode oldNode = (XmlLinkedNode)oldChild; string oldNodeValue = oldNode.Value; XmlNodeChangedEventArgs args = GetEventArgs(oldNode, this, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove); if (args != null) BeforeEvent(args); XmlLinkedNode lastNode = LastNode; if (oldNode == FirstChild) { if (oldNode == lastNode) { LastNode = null; oldNode.next = null; oldNode.SetParent(null); } else { XmlLinkedNode nextNode = oldNode.next; if (nextNode.IsText) { if (oldNode.IsText) { UnnestTextNodes(oldNode, nextNode); } } lastNode.next = nextNode; oldNode.next = null; oldNode.SetParent(null); } } else { if (oldNode == lastNode) { XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling; prevNode.next = oldNode.next; LastNode = prevNode; oldNode.next = null; oldNode.SetParent(null); } else { XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling; XmlLinkedNode nextNode = oldNode.next; if (nextNode.IsText) { if (prevNode.IsText) { NestTextNodes(prevNode, nextNode); } else { if (oldNode.IsText) { UnnestTextNodes(oldNode, nextNode); } } } prevNode.next = nextNode; oldNode.next = null; oldNode.SetParent(null); } } if (args != null) AfterEvent(args); return oldChild; } // Adds the specified node to the beginning of the list of children of this node. public virtual XmlNode PrependChild(XmlNode newChild) { return InsertBefore(newChild, FirstChild); } // Adds the specified node to the end of the list of children of this node. public virtual XmlNode AppendChild(XmlNode newChild) { XmlDocument thisDoc = OwnerDocument; if (thisDoc == null) { thisDoc = this as XmlDocument; } if (!IsContainer) throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain); if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); if (newChild.ParentNode != null) newChild.ParentNode.RemoveChild(newChild); XmlDocument childDoc = newChild.OwnerDocument; if (childDoc != null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); // special case for doc-fragment. if (newChild.NodeType == XmlNodeType.DocumentFragment) { XmlNode first = newChild.FirstChild; XmlNode node = first; while (node != null) { XmlNode next = node.NextSibling; newChild.RemoveChild(node); AppendChild(node); node = next; } return first; } if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); if (!CanInsertAfter(newChild, LastChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); string newChildValue = newChild.Value; XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); if (args != null) BeforeEvent(args); XmlLinkedNode refNode = LastNode; XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (refNode == null) { newNode.next = newNode; LastNode = newNode; newNode.SetParent(this); } else { newNode.next = refNode.next; refNode.next = newNode; LastNode = newNode; newNode.SetParent(this); if (refNode.IsText) { if (newNode.IsText) { NestTextNodes(refNode, newNode); } } } if (args != null) AfterEvent(args); return newNode; } //the function is provided only at Load time to speed up Load process internal virtual XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this); if (args != null) doc.BeforeEvent(args); XmlLinkedNode refNode = LastNode; XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (refNode == null) { newNode.next = newNode; LastNode = newNode; newNode.SetParentForLoad(this); } else { newNode.next = refNode.next; refNode.next = newNode; LastNode = newNode; if (refNode.IsText && newNode.IsText) { NestTextNodes(refNode, newNode); } else { newNode.SetParentForLoad(this); } } if (args != null) doc.AfterEvent(args); return newNode; } internal virtual bool IsValidChildType(XmlNodeType type) { return false; } internal virtual bool CanInsertBefore(XmlNode newChild, XmlNode refChild) { return true; } internal virtual bool CanInsertAfter(XmlNode newChild, XmlNode refChild) { return true; } // Gets a value indicating whether this node has any child nodes. public virtual bool HasChildNodes { get { return LastNode != null; } } // Creates a duplicate of this node. public abstract XmlNode CloneNode(bool deep); internal virtual void CopyChildren(XmlDocument doc, XmlNode container, bool deep) { for (XmlNode child = container.FirstChild; child != null; child = child.NextSibling) { AppendChildForLoad(child.CloneNode(deep), doc); } } // DOM Level 2 // Puts all XmlText nodes in the full depth of the sub-tree // underneath this XmlNode into a "normal" form where only // markup (e.g., tags, comments, processing instructions, CDATA sections, // and entity references) separates XmlText nodes, that is, there // are no adjacent XmlText nodes. public virtual void Normalize() { XmlNode firstChildTextLikeNode = null; StringBuilder sb = new StringBuilder(); for (XmlNode crtChild = this.FirstChild; crtChild != null;) { XmlNode nextChild = crtChild.NextSibling; switch (crtChild.NodeType) { case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: { sb.Append(crtChild.Value); XmlNode winner = NormalizeWinner(firstChildTextLikeNode, crtChild); if (winner == firstChildTextLikeNode) { this.RemoveChild(crtChild); } else { if (firstChildTextLikeNode != null) this.RemoveChild(firstChildTextLikeNode); firstChildTextLikeNode = crtChild; } break; } case XmlNodeType.Element: { crtChild.Normalize(); goto default; } default: { if (firstChildTextLikeNode != null) { firstChildTextLikeNode.Value = sb.ToString(); firstChildTextLikeNode = null; } sb.Remove(0, sb.Length); break; } } crtChild = nextChild; } if (firstChildTextLikeNode != null && sb.Length > 0) firstChildTextLikeNode.Value = sb.ToString(); } private XmlNode NormalizeWinner(XmlNode firstNode, XmlNode secondNode) { //first node has the priority if (firstNode == null) return secondNode; Debug.Assert(firstNode.NodeType == XmlNodeType.Text || firstNode.NodeType == XmlNodeType.SignificantWhitespace || firstNode.NodeType == XmlNodeType.Whitespace || secondNode.NodeType == XmlNodeType.Text || secondNode.NodeType == XmlNodeType.SignificantWhitespace || secondNode.NodeType == XmlNodeType.Whitespace); if (firstNode.NodeType == XmlNodeType.Text) return firstNode; if (secondNode.NodeType == XmlNodeType.Text) return secondNode; if (firstNode.NodeType == XmlNodeType.SignificantWhitespace) return firstNode; if (secondNode.NodeType == XmlNodeType.SignificantWhitespace) return secondNode; if (firstNode.NodeType == XmlNodeType.Whitespace) return firstNode; if (secondNode.NodeType == XmlNodeType.Whitespace) return secondNode; Debug.Assert(true, "shouldn't have fall through here."); return null; } // Test if the DOM implementation implements a specific feature. public virtual bool Supports(string feature, string version) { if (String.Compare("XML", feature, StringComparison.OrdinalIgnoreCase) == 0) { if (version == null || version == "1.0" || version == "2.0") return true; } return false; } // Gets the namespace URI of this node. public virtual string NamespaceURI { get { return string.Empty; } } // Gets or sets the namespace prefix of this node. public virtual string Prefix { get { return string.Empty; } set { } } // Gets the name of the node without the namespace prefix. public abstract string LocalName { get; } // Microsoft extensions // Gets a value indicating whether the node is read-only. public virtual bool IsReadOnly { get { XmlDocument doc = OwnerDocument; return HasReadOnlyParent(this); } } internal static bool HasReadOnlyParent(XmlNode n) { while (n != null) { switch (n.NodeType) { case XmlNodeType.EntityReference: case XmlNodeType.Entity: return true; case XmlNodeType.Attribute: n = ((XmlAttribute)n).OwnerElement; break; default: n = n.ParentNode; break; } } return false; } // Provides a simple ForEach-style iteration over the // collection of nodes in this XmlNamedNodeMap. IEnumerator IEnumerable.GetEnumerator() { return new XmlChildEnumerator(this); } public IEnumerator GetEnumerator() { return new XmlChildEnumerator(this); } private void AppendChildText(StringBuilder builder) { for (XmlNode child = FirstChild; child != null; child = child.NextSibling) { if (child.FirstChild == null) { if (child.NodeType == XmlNodeType.Text || child.NodeType == XmlNodeType.CDATA || child.NodeType == XmlNodeType.Whitespace || child.NodeType == XmlNodeType.SignificantWhitespace) builder.Append(child.InnerText); } else { child.AppendChildText(builder); } } } // Gets or sets the concatenated values of the node and // all its children. public virtual string InnerText { get { XmlNode fc = FirstChild; if (fc == null) { return string.Empty; } if (fc.NextSibling == null) { XmlNodeType nodeType = fc.NodeType; switch (nodeType) { case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: return fc.Value; } } StringBuilder builder = new StringBuilder(); AppendChildText(builder); return builder.ToString(); } set { XmlNode firstChild = FirstChild; if (firstChild != null //there is one child && firstChild.NextSibling == null // and exactly one && firstChild.NodeType == XmlNodeType.Text)//which is a text node { //this branch is for perf reason and event fired when TextNode.Value is changed firstChild.Value = value; } else { RemoveAll(); AppendChild(OwnerDocument.CreateTextNode(value)); } } } // Gets the markup representing this node and all its children. public virtual string OuterXml { get { StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); XmlDOMTextWriter xw = new XmlDOMTextWriter(sw); try { WriteTo(xw); } finally { xw.Dispose(); } return sw.ToString(); } } // Gets or sets the markup representing just the children of this node. public virtual string InnerXml { get { StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); XmlDOMTextWriter xw = new XmlDOMTextWriter(sw); try { WriteContentTo(xw); } finally { xw.Dispose(); } return sw.ToString(); } set { throw new InvalidOperationException(SR.Xdom_Set_InnerXml); } } public virtual String BaseURI { get { XmlNode curNode = this.ParentNode; //save one while loop since if going to here, the nodetype of this node can't be document, entity and entityref while (curNode != null) { XmlNodeType nt = curNode.NodeType; //EntityReference's children come from the dtd where they are defined. //we need to investigate the same thing for entity's children if they are defined in an external dtd file. if (nt == XmlNodeType.EntityReference) return ((XmlEntityReference)curNode).ChildBaseURI; if (nt == XmlNodeType.Document || nt == XmlNodeType.Entity || nt == XmlNodeType.Attribute) return curNode.BaseURI; curNode = curNode.ParentNode; } return String.Empty; } } // Saves the current node to the specified XmlWriter. public abstract void WriteTo(XmlWriter w); // Saves all the children of the node to the specified XmlWriter. public abstract void WriteContentTo(XmlWriter w); // Removes all the children and/or attributes // of the current node. public virtual void RemoveAll() { XmlNode child = FirstChild; XmlNode sibling = null; while (child != null) { sibling = child.NextSibling; RemoveChild(child); child = sibling; } } internal XmlDocument Document { get { if (NodeType == XmlNodeType.Document) return (XmlDocument)this; return OwnerDocument; } } // Looks up the closest xmlns declaration for the given // prefix that is in scope for the current node and returns // the namespace URI in the declaration. public virtual string GetNamespaceOfPrefix(string prefix) { string namespaceName = GetNamespaceOfPrefixStrict(prefix); return namespaceName != null ? namespaceName : string.Empty; } internal string GetNamespaceOfPrefixStrict(string prefix) { XmlDocument doc = Document; if (doc != null) { prefix = doc.NameTable.Get(prefix); if (prefix == null) return null; XmlNode node = this; while (node != null) { if (node.NodeType == XmlNodeType.Element) { XmlElement elem = (XmlElement)node; if (elem.HasAttributes) { XmlAttributeCollection attrs = elem.Attributes; if (prefix.Length == 0) { for (int iAttr = 0; iAttr < attrs.Count; iAttr++) { XmlAttribute attr = attrs[iAttr]; if (attr.Prefix.Length == 0) { if (Ref.Equal(attr.LocalName, doc.strXmlns)) { return attr.Value; // found xmlns } } } } else { for (int iAttr = 0; iAttr < attrs.Count; iAttr++) { XmlAttribute attr = attrs[iAttr]; if (Ref.Equal(attr.Prefix, doc.strXmlns)) { if (Ref.Equal(attr.LocalName, prefix)) { return attr.Value; // found xmlns:prefix } } else if (Ref.Equal(attr.Prefix, prefix)) { return attr.NamespaceURI; // found prefix:attr } } } } if (Ref.Equal(node.Prefix, prefix)) { return node.NamespaceURI; } node = node.ParentNode; } else if (node.NodeType == XmlNodeType.Attribute) { node = ((XmlAttribute)node).OwnerElement; } else { node = node.ParentNode; } } if (Ref.Equal(doc.strXml, prefix)) { // xmlns:xml return doc.strReservedXml; } else if (Ref.Equal(doc.strXmlns, prefix)) { // xmlns:xmlns return doc.strReservedXmlns; } } return null; } // Looks up the closest xmlns declaration for the given namespace // URI that is in scope for the current node and returns // the prefix defined in that declaration. public virtual string GetPrefixOfNamespace(string namespaceURI) { string prefix = GetPrefixOfNamespaceStrict(namespaceURI); return prefix != null ? prefix : string.Empty; } internal string GetPrefixOfNamespaceStrict(string namespaceURI) { XmlDocument doc = Document; if (doc != null) { namespaceURI = doc.NameTable.Add(namespaceURI); XmlNode node = this; while (node != null) { if (node.NodeType == XmlNodeType.Element) { XmlElement elem = (XmlElement)node; if (elem.HasAttributes) { XmlAttributeCollection attrs = elem.Attributes; for (int iAttr = 0; iAttr < attrs.Count; iAttr++) { XmlAttribute attr = attrs[iAttr]; if (attr.Prefix.Length == 0) { if (Ref.Equal(attr.LocalName, doc.strXmlns)) { if (attr.Value == namespaceURI) { return string.Empty; // found xmlns="namespaceURI" } } } else if (Ref.Equal(attr.Prefix, doc.strXmlns)) { if (attr.Value == namespaceURI) { return attr.LocalName; // found xmlns:prefix="namespaceURI" } } else if (Ref.Equal(attr.NamespaceURI, namespaceURI)) { return attr.Prefix; // found prefix:attr // with prefix bound to namespaceURI } } } if (Ref.Equal(node.NamespaceURI, namespaceURI)) { return node.Prefix; } node = node.ParentNode; } else if (node.NodeType == XmlNodeType.Attribute) { node = ((XmlAttribute)node).OwnerElement; } else { node = node.ParentNode; } } if (Ref.Equal(doc.strReservedXml, namespaceURI)) { // xmlns:xml return doc.strXml; } else if (Ref.Equal(doc.strReservedXmlns, namespaceURI)) { // xmlns:xmlns return doc.strXmlns; } } return null; } // Retrieves the first child element with the specified name. public virtual XmlElement this[string name] { get { for (XmlNode n = FirstChild; n != null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.Element && n.Name == name) return (XmlElement)n; } return null; } } // Retrieves the first child element with the specified LocalName and // NamespaceURI. public virtual XmlElement this[string localname, string ns] { get { for (XmlNode n = FirstChild; n != null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.Element && n.LocalName == localname && n.NamespaceURI == ns) return (XmlElement)n; } return null; } } internal virtual void SetParent(XmlNode node) { if (node == null) { this.parentNode = OwnerDocument; } else { this.parentNode = node; } } internal virtual void SetParentForLoad(XmlNode node) { this.parentNode = node; } internal static void SplitName(string name, out string prefix, out string localName) { int colonPos = name.IndexOf(':'); // ordinal compare if (-1 == colonPos || 0 == colonPos || name.Length - 1 == colonPos) { prefix = string.Empty; localName = name; } else { prefix = name.Substring(0, colonPos); localName = name.Substring(colonPos + 1); } } internal virtual XmlNode FindChild(XmlNodeType type) { for (XmlNode child = FirstChild; child != null; child = child.NextSibling) { if (child.NodeType == type) { return child; } } return null; } internal virtual XmlNodeChangedEventArgs GetEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action) { XmlDocument doc = OwnerDocument; if (doc != null) { if (!doc.IsLoading) { if (((newParent != null && newParent.IsReadOnly) || (oldParent != null && oldParent.IsReadOnly))) throw new InvalidOperationException(SR.Xdom_Node_Modify_ReadOnly); } return doc.GetEventArgs(node, oldParent, newParent, oldValue, newValue, action); } return null; } internal virtual void BeforeEvent(XmlNodeChangedEventArgs args) { if (args != null) OwnerDocument.BeforeEvent(args); } internal virtual void AfterEvent(XmlNodeChangedEventArgs args) { if (args != null) OwnerDocument.AfterEvent(args); } internal virtual XmlSpace XmlSpace { get { XmlNode node = this; XmlElement elem = null; do { elem = node as XmlElement; if (elem != null && elem.HasAttribute("xml:space")) { switch (XmlConvertEx.TrimString(elem.GetAttribute("xml:space"))) { case "default": return XmlSpace.Default; case "preserve": return XmlSpace.Preserve; default: //should we throw exception if value is otherwise? break; } } node = node.ParentNode; } while (node != null); return XmlSpace.None; } } internal virtual String XmlLang { get { XmlNode node = this; XmlElement elem = null; do { elem = node as XmlElement; if (elem != null) { if (elem.HasAttribute("xml:lang")) return elem.GetAttribute("xml:lang"); } node = node.ParentNode; } while (node != null); return String.Empty; } } internal virtual string GetXPAttribute(string localName, string namespaceURI) { return String.Empty; } internal virtual bool IsText { get { return false; } } public virtual XmlNode PreviousText { get { return null; } } internal static void NestTextNodes(XmlNode prevNode, XmlNode nextNode) { Debug.Assert(prevNode.IsText); Debug.Assert(nextNode.IsText); nextNode.parentNode = prevNode; } internal static void UnnestTextNodes(XmlNode prevNode, XmlNode nextNode) { Debug.Assert(prevNode.IsText); Debug.Assert(nextNode.IsText); nextNode.parentNode = prevNode.ParentNode; } private object debuggerDisplayProxy { get { return new DebuggerDisplayXmlNodeProxy(this); } } } [DebuggerDisplay("{ToString()}")] internal struct DebuggerDisplayXmlNodeProxy { private XmlNode node; public DebuggerDisplayXmlNodeProxy(XmlNode node) { this.node = node; } public override string ToString() { XmlNodeType nodeType = node.NodeType; string result = nodeType.ToString(); switch (nodeType) { case XmlNodeType.Element: case XmlNodeType.EntityReference: result += ", Name=\"" + node.Name + "\""; break; case XmlNodeType.Attribute: case XmlNodeType.ProcessingInstruction: result += ", Name=\"" + node.Name + "\", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(node.Value) + "\""; break; case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.XmlDeclaration: result += ", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(node.Value) + "\""; break; case XmlNodeType.DocumentType: XmlDocumentType documentType = (XmlDocumentType)node; result += ", Name=\"" + documentType.Name + "\", SYSTEM=\"" + documentType.SystemId + "\", PUBLIC=\"" + documentType.PublicId + "\", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(documentType.InternalSubset) + "\""; break; default: break; } return result; } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Runtime.Serialization { using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Xml; using System.Runtime.CompilerServices; using System.Runtime.Diagnostics; using System.Text; using System.Security; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Runtime.Serialization.Diagnostics; public abstract class XmlObjectSerializer { public abstract void WriteStartObject(XmlDictionaryWriter writer, object graph); public abstract void WriteObjectContent(XmlDictionaryWriter writer, object graph); public abstract void WriteEndObject(XmlDictionaryWriter writer); public virtual void WriteObject(Stream stream, object graph) { CheckNull(stream, "stream"); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8, false /*ownsStream*/); WriteObject(writer, graph); writer.Flush(); } public virtual void WriteObject(XmlWriter writer, object graph) { CheckNull(writer, "writer"); WriteObject(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph); } public virtual void WriteStartObject(XmlWriter writer, object graph) { CheckNull(writer, "writer"); WriteStartObject(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph); } public virtual void WriteObjectContent(XmlWriter writer, object graph) { CheckNull(writer, "writer"); WriteObjectContent(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph); } public virtual void WriteEndObject(XmlWriter writer) { CheckNull(writer, "writer"); WriteEndObject(XmlDictionaryWriter.CreateDictionaryWriter(writer)); } public virtual void WriteObject(XmlDictionaryWriter writer, object graph) { WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object graph) { WriteObjectHandleExceptions(writer, graph, null); } internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) { try { CheckNull(writer, "writer"); if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.Trace(TraceEventType.Information, TraceCode.WriteObjectBegin, SR.GetString(SR.TraceCodeWriteObjectBegin), new StringTraceRecord("Type", GetTypeInfo(GetSerializeType(graph)))); InternalWriteObject(writer, graph, dataContractResolver); TraceUtility.Trace(TraceEventType.Information, TraceCode.WriteObjectEnd, SR.GetString(SR.TraceCodeWriteObjectEnd), new StringTraceRecord("Type", GetTypeInfo(GetSerializeType(graph)))); } else { InternalWriteObject(writer, graph, dataContractResolver); } } catch (XmlException ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorSerializing, GetSerializeType(graph), ex), ex)); } catch (FormatException ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorSerializing, GetSerializeType(graph), ex), ex)); } } internal virtual DataContractDictionary KnownDataContracts { get { return null; } } internal virtual void InternalWriteObject(XmlWriterDelegator writer, object graph) { WriteStartObject(writer.Writer, graph); WriteObjectContent(writer.Writer, graph); WriteEndObject(writer.Writer); } internal virtual void InternalWriteObject(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) { InternalWriteObject(writer, graph); } internal virtual void InternalWriteStartObject(XmlWriterDelegator writer, object graph) { Fx.Assert("XmlObjectSerializer.InternalWriteStartObject should never get called"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } internal virtual void InternalWriteObjectContent(XmlWriterDelegator writer, object graph) { Fx.Assert("XmlObjectSerializer.InternalWriteObjectContent should never get called"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } internal virtual void InternalWriteEndObject(XmlWriterDelegator writer) { Fx.Assert("XmlObjectSerializer.InternalWriteEndObject should never get called"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } internal void WriteStartObjectHandleExceptions(XmlWriterDelegator writer, object graph) { try { CheckNull(writer, "writer"); InternalWriteStartObject(writer, graph); } catch (XmlException ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorWriteStartObject, GetSerializeType(graph), ex), ex)); } catch (FormatException ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorWriteStartObject, GetSerializeType(graph), ex), ex)); } } internal void WriteObjectContentHandleExceptions(XmlWriterDelegator writer, object graph) { try { CheckNull(writer, "writer"); if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.Trace(TraceEventType.Information, TraceCode.WriteObjectContentBegin, SR.GetString(SR.TraceCodeWriteObjectContentBegin), new StringTraceRecord("Type", GetTypeInfo(GetSerializeType(graph)))); if (writer.WriteState != WriteState.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.XmlWriterMustBeInElement, writer.WriteState))); } InternalWriteObjectContent(writer, graph); TraceUtility.Trace(TraceEventType.Information, TraceCode.WriteObjectContentEnd, SR.GetString(SR.TraceCodeWriteObjectContentEnd), new StringTraceRecord("Type", GetTypeInfo(GetSerializeType(graph)))); } else { if (writer.WriteState != WriteState.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.XmlWriterMustBeInElement, writer.WriteState))); InternalWriteObjectContent(writer, graph); } } catch (XmlException ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorSerializing, GetSerializeType(graph), ex), ex)); } catch (FormatException ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorSerializing, GetSerializeType(graph), ex), ex)); } } internal void WriteEndObjectHandleExceptions(XmlWriterDelegator writer) { try { CheckNull(writer, "writer"); InternalWriteEndObject(writer); } catch (XmlException ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorWriteEndObject, null, ex), ex)); } catch (FormatException ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorWriteEndObject, null, ex), ex)); } } internal void WriteRootElement(XmlWriterDelegator writer, DataContract contract, XmlDictionaryString name, XmlDictionaryString ns, bool needsContractNsAtRoot) { if (name == null) // root name not set explicitly { if (!contract.HasRoot) return; contract.WriteRootElement(writer, contract.TopLevelElementName, contract.TopLevelElementNamespace); } else { contract.WriteRootElement(writer, name, ns); if (needsContractNsAtRoot) { writer.WriteNamespaceDecl(contract.Namespace); } } } internal bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString name, XmlDictionaryString ns, DataContract contract) { if (name == null) return false; if (contract.IsBuiltInDataContract || !contract.CanContainReferences || contract.IsISerializable) return false; string contractNs = XmlDictionaryString.GetString(contract.Namespace); if (string.IsNullOrEmpty(contractNs) || contractNs == XmlDictionaryString.GetString(ns)) return false; return true; } internal static void WriteNull(XmlWriterDelegator writer) { writer.WriteAttributeBool(Globals.XsiPrefix, DictionaryGlobals.XsiNilLocalName, DictionaryGlobals.SchemaInstanceNamespace, true); } internal static bool IsContractDeclared(DataContract contract, DataContract declaredContract) { return (object.ReferenceEquals(contract.Name, declaredContract.Name) && object.ReferenceEquals(contract.Namespace, declaredContract.Namespace)) || (contract.Name.Value == declaredContract.Name.Value && contract.Namespace.Value == declaredContract.Namespace.Value); } public virtual object ReadObject(Stream stream) { CheckNull(stream, "stream"); return ReadObject(XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max)); } public virtual object ReadObject(XmlReader reader) { CheckNull(reader, "reader"); return ReadObject(XmlDictionaryReader.CreateDictionaryReader(reader)); } public virtual object ReadObject(XmlDictionaryReader reader) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), true /*verifyObjectName*/); } public virtual object ReadObject(XmlReader reader, bool verifyObjectName) { CheckNull(reader, "reader"); return ReadObject(XmlDictionaryReader.CreateDictionaryReader(reader), verifyObjectName); } public abstract object ReadObject(XmlDictionaryReader reader, bool verifyObjectName); public virtual bool IsStartObject(XmlReader reader) { CheckNull(reader, "reader"); return IsStartObject(XmlDictionaryReader.CreateDictionaryReader(reader)); } public abstract bool IsStartObject(XmlDictionaryReader reader); internal virtual object InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName) { return ReadObject(reader.UnderlyingReader, verifyObjectName); } internal virtual object InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver dataContractResolver) { return InternalReadObject(reader, verifyObjectName); } internal virtual bool InternalIsStartObject(XmlReaderDelegator reader) { Fx.Assert("XmlObjectSerializer.InternalIsStartObject should never get called"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } internal object ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName) { return ReadObjectHandleExceptions(reader, verifyObjectName, null); } internal object ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver dataContractResolver) { try { CheckNull(reader, "reader"); if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.Trace(TraceEventType.Information, TraceCode.ReadObjectBegin, SR.GetString(SR.TraceCodeReadObjectBegin), new StringTraceRecord("Type", GetTypeInfo(GetDeserializeType()))); object retObj = InternalReadObject(reader, verifyObjectName, dataContractResolver); TraceUtility.Trace(TraceEventType.Information, TraceCode.ReadObjectEnd, SR.GetString(SR.TraceCodeReadObjectEnd), new StringTraceRecord("Type", GetTypeInfo(GetDeserializeType()))); return retObj; } else { return InternalReadObject(reader, verifyObjectName, dataContractResolver); } } catch (XmlException ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorDeserializing, GetDeserializeType(), ex), ex)); } catch (FormatException ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorDeserializing, GetDeserializeType(), ex), ex)); } } internal bool IsStartObjectHandleExceptions(XmlReaderDelegator reader) { try { CheckNull(reader, "reader"); return InternalIsStartObject(reader); } catch (XmlException ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorIsStartObject, GetDeserializeType(), ex), ex)); } catch (FormatException ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorIsStartObject, GetDeserializeType(), ex), ex)); } } internal bool IsRootXmlAny(XmlDictionaryString rootName, DataContract contract) { return (rootName == null) && !contract.HasRoot; } internal bool IsStartElement(XmlReaderDelegator reader) { return (reader.MoveToElement() || reader.IsStartElement()); } internal bool IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString name, XmlDictionaryString ns) { reader.MoveToElement(); if (name != null) // root name set explicitly { return reader.IsStartElement(name, ns); } else { if (!contract.HasRoot) return reader.IsStartElement(); if (reader.IsStartElement(contract.TopLevelElementName, contract.TopLevelElementNamespace)) return true; ClassDataContract classContract = contract as ClassDataContract; if (classContract != null) classContract = classContract.BaseContract; while (classContract != null) { if (reader.IsStartElement(classContract.TopLevelElementName, classContract.TopLevelElementNamespace)) return true; classContract = classContract.BaseContract; } if (classContract == null) { DataContract objectContract = PrimitiveDataContract.GetPrimitiveDataContract(Globals.TypeOfObject); if (reader.IsStartElement(objectContract.TopLevelElementName, objectContract.TopLevelElementNamespace)) return true; } return false; } } internal static void CheckNull(object obj, string name) { if (obj == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(name)); } internal static string TryAddLineInfo(XmlReaderDelegator reader, string errorMessage) { if (reader.HasLineInfo()) return String.Format(CultureInfo.InvariantCulture, "{0} {1}", SR.GetString(SR.ErrorInLine, reader.LineNumber, reader.LinePosition), errorMessage); return errorMessage; } internal static Exception CreateSerializationExceptionWithReaderDetails(string errorMessage, XmlReaderDelegator reader) { return XmlObjectSerializer.CreateSerializationException(TryAddLineInfo(reader, SR.GetString(SR.EncounteredWithNameNamespace, errorMessage, reader.NodeType, reader.LocalName, reader.NamespaceURI))); } static internal SerializationException CreateSerializationException(string errorMessage) { return XmlObjectSerializer.CreateSerializationException(errorMessage, null); } [MethodImpl(MethodImplOptions.NoInlining)] static internal SerializationException CreateSerializationException(string errorMessage, Exception innerException) { return new SerializationException(errorMessage, innerException); } static string GetTypeInfo(Type type) { return (type == null) ? string.Empty : DataContract.GetClrTypeFullName(type); } static string GetTypeInfoError(string errorMessage, Type type, Exception innerException) { string typeInfo = (type == null) ? string.Empty : SR.GetString(SR.ErrorTypeInfo, DataContract.GetClrTypeFullName(type)); string innerExceptionMessage = (innerException == null) ? string.Empty : innerException.Message; return SR.GetString(errorMessage, typeInfo, innerExceptionMessage); } internal virtual Type GetSerializeType(object graph) { return (graph == null) ? null : graph.GetType(); } internal virtual Type GetDeserializeType() { return null; } [Fx.Tag.SecurityNote(Critical = "Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")] [SecurityCritical] static IFormatterConverter formatterConverter; static internal IFormatterConverter FormatterConverter { [Fx.Tag.SecurityNote(Critical = "Fetches the critical formatterConverter field.", Safe = "Get-only properties only needs to be protected for write; initialized in getter if null.")] [SecuritySafeCritical] get { if (formatterConverter == null) formatterConverter = new FormatterConverter(); return formatterConverter; } } } }
using UnityEngine; using System.Collections; public class VolumeRenderer : MonoBehaviour { public Texture3D texture3D; public int n; public Light _light; public float absorption; public float lightIntensityScale; public bool selfCreateTexture3D; private Mesh m; // Use this for initialization public void Start () { CreateMesh(); if(selfCreateTexture3D){ Generate3DTexture(); } Vector4 localEyePos = transform.worldToLocalMatrix.MultiplyPoint( Camera.main.transform.position); Vector4 localLightPos = transform.worldToLocalMatrix.MultiplyPoint( _light.transform.position); renderer.material.SetVector("g_eyePos", localEyePos); renderer.material.SetVector("g_lightPos", localLightPos); renderer.material.SetFloat("g_lightIntensity", _light.intensity); renderer.material.SetFloat("g_absorption", absorption); } void LateUpdate() { Vector4 localEyePos = transform.worldToLocalMatrix.MultiplyPoint( Camera.main.transform.position); localEyePos += new Vector4(0.5f,0.5f,0.5f,0.0f); renderer.material.SetVector("g_eyePos", localEyePos); Vector4 localLightPos = transform.worldToLocalMatrix.MultiplyPoint( _light.transform.position); renderer.material.SetVector("g_lightPos", localLightPos); renderer.material.SetFloat("g_lightIntensity", _light.intensity * lightIntensityScale); renderer.material.SetFloat("g_absorption", absorption); } private Mesh CreateMesh() { m = new Mesh(); CreateCube(m); m.RecalculateBounds(); MeshFilter mf = (MeshFilter)transform.GetComponent(typeof(MeshFilter)); mf.mesh = m; return m; } void CreateCube(Mesh m) { Vector3[] vertices = new Vector3[24]; Vector2[] uv = new Vector2[24]; Color[] colors = new Color[24]; Vector3[] normals = new Vector3[24]; int[] triangles = new int[36]; int i = 0; int ti = 0; //Front vertices[i] = new Vector3(-0.5f,-0.5f,-0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(0,0,0); i++; vertices[i] = new Vector3(0.5f,-0.5f,-0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(1,0,0); i++; vertices[i] = new Vector3(0.5f,0.5f,-0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(1,1,0); i++; vertices[i] = new Vector3(-0.5f,0.5f,-0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(0,1,0); i++; triangles[ti++] = i-4; triangles[ti++] = i-2; triangles[ti++] = i-3; triangles[ti++] = i-4; triangles[ti++] = i-1; triangles[ti++] = i-2; //Back vertices[i] = new Vector3(-0.5f,-0.5f,0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(0,0,1); i++; vertices[i] = new Vector3(0.5f,-0.5f,0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(1,0,1); i++; vertices[i] = new Vector3(0.5f,0.5f,0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(1,1,1); i++; vertices[i] = new Vector3(-0.5f,0.5f,0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(0,1,1); i++; triangles[ti++] = i-4; triangles[ti++] = i-3; triangles[ti++] = i-2; triangles[ti++] = i-4; triangles[ti++] = i-2; triangles[ti++] = i-1; //Top vertices[i] = new Vector3(-0.5f,0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,1,0); i++; vertices[i] = new Vector3(0.5f,0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,1,0); i++; vertices[i] = new Vector3(0.5f,0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,1,1); i++; vertices[i] = new Vector3(-0.5f,0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,1,1); i++; triangles[ti++] = i-4; triangles[ti++] = i-2; triangles[ti++] = i-3; triangles[ti++] = i-4; triangles[ti++] = i-1; triangles[ti++] = i-2; //Bottom vertices[i] = new Vector3(-0.5f,-0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,0,0); i++; vertices[i] = new Vector3(0.5f,-0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,0,0); i++; vertices[i] = new Vector3(0.5f,-0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,0,1); i++; vertices[i] = new Vector3(-0.5f,-0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,0,1); i++; triangles[ti++] = i-4; triangles[ti++] = i-3; triangles[ti++] = i-2; triangles[ti++] = i-4; triangles[ti++] = i-2; triangles[ti++] = i-1; //Right vertices[i] = new Vector3(0.5f,-0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,0,0); i++; vertices[i] = new Vector3(0.5f,0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,1,0); i++; vertices[i] = new Vector3(0.5f,0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,1,1); i++; vertices[i] = new Vector3(0.5f,-0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,0,1); i++; triangles[ti++] = i-4; triangles[ti++] = i-3; triangles[ti++] = i-2; triangles[ti++] = i-4; triangles[ti++] = i-2; triangles[ti++] = i-1; //Left vertices[i] = new Vector3(-0.5f,-0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,0,0); i++; vertices[i] = new Vector3(-0.5f,0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,1,0); i++; vertices[i] = new Vector3(-0.5f,0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,1,1); i++; vertices[i] = new Vector3(-0.5f,-0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,0,1); i++; triangles[ti++] = i-4; triangles[ti++] = i-2; triangles[ti++] = i-3; triangles[ti++] = i-4; triangles[ti++] = i-1; triangles[ti++] = i-2; m.vertices = vertices; m.colors = colors; //Putting uv's into the normal channel to get the //Vector3 type m.uv = uv; m.normals = normals; m.triangles = triangles; } public void set3DTexture(Texture3D t){ texture3D = t; renderer.material.SetTexture("g_densityTex", texture3D); } public void Generate3DTexture() { float r = 0.3f; texture3D = new Texture3D(n,n,n,TextureFormat.ARGB32,true); int size = n * n * n; Color[] cols = new Color[size]; int idx = 0; Color c = Color.white; float frequency = 0.01f / n; float center = n / 2.0f + 0.5f; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { for(int k = 0; k < n; k++, ++idx) { float dx = center-i; float dy = center-j; float dz = center-k; float off = Mathf.Abs(Perlin.Turbulence(i*frequency, j*frequency, k*frequency, 6)); float d = Mathf.Sqrt(dx*dx+dy*dy+dz*dz)/(n); //c.r = c.g = c.b = c.a = ((d-off) < r)?1.0f:0.0f; float p = d-off; c.r = c.g = c.b = c.a = Mathf.Clamp01(r - p); cols[idx] = c; } } } //for(int i = 0; i < size; i++) // Debug.Log (newC[i]); texture3D.SetPixels(cols); texture3D.Apply(); renderer.material.SetTexture("g_densityTex", texture3D); texture3D.filterMode = FilterMode.Trilinear; texture3D.wrapMode = TextureWrapMode.Clamp; texture3D.anisoLevel = 1; //Color[] cs = texture3D.GetPixels(); //for(int i = 0; i < 10; i++) // Debug.Log (cs[i]); } }
// Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // 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.Batch.Protocol { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for ComputeNodeOperations. /// </summary> public static partial class ComputeNodeOperationsExtensions { /// <summary> /// Adds a user account to the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to create a user account. /// </param> /// <param name='user'> /// The user account to be created. /// </param> /// <param name='computeNodeAddUserOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeAddUserHeaders AddUser(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeUser user, ComputeNodeAddUserOptions computeNodeAddUserOptions = default(ComputeNodeAddUserOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IComputeNodeOperations)s).AddUserAsync(poolId, nodeId, user, computeNodeAddUserOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Adds a user account to the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to create a user account. /// </param> /// <param name='user'> /// The user account to be created. /// </param> /// <param name='computeNodeAddUserOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ComputeNodeAddUserHeaders> AddUserAsync(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeUser user, ComputeNodeAddUserOptions computeNodeAddUserOptions = default(ComputeNodeAddUserOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.AddUserWithHttpMessagesAsync(poolId, nodeId, user, computeNodeAddUserOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Deletes a user account from the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to delete a user account. /// </param> /// <param name='userName'> /// The name of the user account to delete. /// </param> /// <param name='computeNodeDeleteUserOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeDeleteUserHeaders DeleteUser(this IComputeNodeOperations operations, string poolId, string nodeId, string userName, ComputeNodeDeleteUserOptions computeNodeDeleteUserOptions = default(ComputeNodeDeleteUserOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IComputeNodeOperations)s).DeleteUserAsync(poolId, nodeId, userName, computeNodeDeleteUserOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a user account from the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to delete a user account. /// </param> /// <param name='userName'> /// The name of the user account to delete. /// </param> /// <param name='computeNodeDeleteUserOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ComputeNodeDeleteUserHeaders> DeleteUserAsync(this IComputeNodeOperations operations, string poolId, string nodeId, string userName, ComputeNodeDeleteUserOptions computeNodeDeleteUserOptions = default(ComputeNodeDeleteUserOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.DeleteUserWithHttpMessagesAsync(poolId, nodeId, userName, computeNodeDeleteUserOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Updates the password or expiration time of a user account on the specified /// compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to update a user account. /// </param> /// <param name='userName'> /// The name of the user account to update. /// </param> /// <param name='nodeUpdateUserParameter'> /// The parameters for the request. /// </param> /// <param name='computeNodeUpdateUserOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeUpdateUserHeaders UpdateUser(this IComputeNodeOperations operations, string poolId, string nodeId, string userName, NodeUpdateUserParameter nodeUpdateUserParameter, ComputeNodeUpdateUserOptions computeNodeUpdateUserOptions = default(ComputeNodeUpdateUserOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IComputeNodeOperations)s).UpdateUserAsync(poolId, nodeId, userName, nodeUpdateUserParameter, computeNodeUpdateUserOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the password or expiration time of a user account on the specified /// compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to update a user account. /// </param> /// <param name='userName'> /// The name of the user account to update. /// </param> /// <param name='nodeUpdateUserParameter'> /// The parameters for the request. /// </param> /// <param name='computeNodeUpdateUserOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ComputeNodeUpdateUserHeaders> UpdateUserAsync(this IComputeNodeOperations operations, string poolId, string nodeId, string userName, NodeUpdateUserParameter nodeUpdateUserParameter, ComputeNodeUpdateUserOptions computeNodeUpdateUserOptions = default(ComputeNodeUpdateUserOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.UpdateUserWithHttpMessagesAsync(poolId, nodeId, userName, nodeUpdateUserParameter, computeNodeUpdateUserOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Gets information about the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to get information about. /// </param> /// <param name='computeNodeGetOptions'> /// Additional parameters for the operation /// </param> public static ComputeNode Get(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeGetOptions computeNodeGetOptions = default(ComputeNodeGetOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IComputeNodeOperations)s).GetAsync(poolId, nodeId, computeNodeGetOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets information about the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to get information about. /// </param> /// <param name='computeNodeGetOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ComputeNode> GetAsync(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeGetOptions computeNodeGetOptions = default(ComputeNodeGetOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(poolId, nodeId, computeNodeGetOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Restarts the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to restart. /// </param> /// <param name='nodeRebootOption'> /// When to reboot the compute node and what to do with currently running /// tasks. The default value is requeue. Possible values include: 'requeue', /// 'terminate', 'taskcompletion', 'retaineddata' /// </param> /// <param name='computeNodeRebootOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeRebootHeaders Reboot(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeRebootOption? nodeRebootOption = default(ComputeNodeRebootOption?), ComputeNodeRebootOptions computeNodeRebootOptions = default(ComputeNodeRebootOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IComputeNodeOperations)s).RebootAsync(poolId, nodeId, nodeRebootOption, computeNodeRebootOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Restarts the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to restart. /// </param> /// <param name='nodeRebootOption'> /// When to reboot the compute node and what to do with currently running /// tasks. The default value is requeue. Possible values include: 'requeue', /// 'terminate', 'taskcompletion', 'retaineddata' /// </param> /// <param name='computeNodeRebootOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ComputeNodeRebootHeaders> RebootAsync(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeRebootOption? nodeRebootOption = default(ComputeNodeRebootOption?), ComputeNodeRebootOptions computeNodeRebootOptions = default(ComputeNodeRebootOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.RebootWithHttpMessagesAsync(poolId, nodeId, nodeRebootOption, computeNodeRebootOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Reinstalls the operating system on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to restart. /// </param> /// <param name='nodeReimageOption'> /// When to reimage the compute node and what to do with currently running /// tasks. The default value is requeue. Possible values include: 'requeue', /// 'terminate', 'taskcompletion', 'retaineddata' /// </param> /// <param name='computeNodeReimageOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeReimageHeaders Reimage(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeReimageOption? nodeReimageOption = default(ComputeNodeReimageOption?), ComputeNodeReimageOptions computeNodeReimageOptions = default(ComputeNodeReimageOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IComputeNodeOperations)s).ReimageAsync(poolId, nodeId, nodeReimageOption, computeNodeReimageOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Reinstalls the operating system on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to restart. /// </param> /// <param name='nodeReimageOption'> /// When to reimage the compute node and what to do with currently running /// tasks. The default value is requeue. Possible values include: 'requeue', /// 'terminate', 'taskcompletion', 'retaineddata' /// </param> /// <param name='computeNodeReimageOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ComputeNodeReimageHeaders> ReimageAsync(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeReimageOption? nodeReimageOption = default(ComputeNodeReimageOption?), ComputeNodeReimageOptions computeNodeReimageOptions = default(ComputeNodeReimageOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ReimageWithHttpMessagesAsync(poolId, nodeId, nodeReimageOption, computeNodeReimageOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Disables task scheduling on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node on which you want to disable task scheduling. /// </param> /// <param name='nodeDisableSchedulingOption'> /// What to do with currently running tasks when disable task scheduling on /// the compute node. The default value is requeue. Possible values include: /// 'requeue', 'terminate', 'taskcompletion' /// </param> /// <param name='computeNodeDisableSchedulingOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeDisableSchedulingHeaders DisableScheduling(this IComputeNodeOperations operations, string poolId, string nodeId, DisableComputeNodeSchedulingOption? nodeDisableSchedulingOption = default(DisableComputeNodeSchedulingOption?), ComputeNodeDisableSchedulingOptions computeNodeDisableSchedulingOptions = default(ComputeNodeDisableSchedulingOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IComputeNodeOperations)s).DisableSchedulingAsync(poolId, nodeId, nodeDisableSchedulingOption, computeNodeDisableSchedulingOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Disables task scheduling on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node on which you want to disable task scheduling. /// </param> /// <param name='nodeDisableSchedulingOption'> /// What to do with currently running tasks when disable task scheduling on /// the compute node. The default value is requeue. Possible values include: /// 'requeue', 'terminate', 'taskcompletion' /// </param> /// <param name='computeNodeDisableSchedulingOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ComputeNodeDisableSchedulingHeaders> DisableSchedulingAsync(this IComputeNodeOperations operations, string poolId, string nodeId, DisableComputeNodeSchedulingOption? nodeDisableSchedulingOption = default(DisableComputeNodeSchedulingOption?), ComputeNodeDisableSchedulingOptions computeNodeDisableSchedulingOptions = default(ComputeNodeDisableSchedulingOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.DisableSchedulingWithHttpMessagesAsync(poolId, nodeId, nodeDisableSchedulingOption, computeNodeDisableSchedulingOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Enables task scheduling on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node on which you want to enable task scheduling. /// </param> /// <param name='computeNodeEnableSchedulingOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeEnableSchedulingHeaders EnableScheduling(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeEnableSchedulingOptions computeNodeEnableSchedulingOptions = default(ComputeNodeEnableSchedulingOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IComputeNodeOperations)s).EnableSchedulingAsync(poolId, nodeId, computeNodeEnableSchedulingOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Enables task scheduling on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node on which you want to enable task scheduling. /// </param> /// <param name='computeNodeEnableSchedulingOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ComputeNodeEnableSchedulingHeaders> EnableSchedulingAsync(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeEnableSchedulingOptions computeNodeEnableSchedulingOptions = default(ComputeNodeEnableSchedulingOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.EnableSchedulingWithHttpMessagesAsync(poolId, nodeId, computeNodeEnableSchedulingOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Gets the settings required for remote login to a compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node for which to obtain the remote login settings. /// </param> /// <param name='computeNodeGetRemoteLoginSettingsOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeGetRemoteLoginSettingsResult GetRemoteLoginSettings(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeGetRemoteLoginSettingsOptions computeNodeGetRemoteLoginSettingsOptions = default(ComputeNodeGetRemoteLoginSettingsOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IComputeNodeOperations)s).GetRemoteLoginSettingsAsync(poolId, nodeId, computeNodeGetRemoteLoginSettingsOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the settings required for remote login to a compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node for which to obtain the remote login settings. /// </param> /// <param name='computeNodeGetRemoteLoginSettingsOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ComputeNodeGetRemoteLoginSettingsResult> GetRemoteLoginSettingsAsync(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeGetRemoteLoginSettingsOptions computeNodeGetRemoteLoginSettingsOptions = default(ComputeNodeGetRemoteLoginSettingsOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetRemoteLoginSettingsWithHttpMessagesAsync(poolId, nodeId, computeNodeGetRemoteLoginSettingsOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the Remote Desktop Protocol file for the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node for which you want to get the Remote Desktop /// Protocol file. /// </param> /// <param name='computeNodeGetRemoteDesktopOptions'> /// Additional parameters for the operation /// </param> public static System.IO.Stream GetRemoteDesktop(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeGetRemoteDesktopOptions computeNodeGetRemoteDesktopOptions = default(ComputeNodeGetRemoteDesktopOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IComputeNodeOperations)s).GetRemoteDesktopAsync(poolId, nodeId, computeNodeGetRemoteDesktopOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the Remote Desktop Protocol file for the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node for which you want to get the Remote Desktop /// Protocol file. /// </param> /// <param name='computeNodeGetRemoteDesktopOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.IO.Stream> GetRemoteDesktopAsync(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeGetRemoteDesktopOptions computeNodeGetRemoteDesktopOptions = default(ComputeNodeGetRemoteDesktopOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var _result = await operations.GetRemoteDesktopWithHttpMessagesAsync(poolId, nodeId, computeNodeGetRemoteDesktopOptions, null, cancellationToken).ConfigureAwait(false); _result.Request.Dispose(); return _result.Body; } /// <summary> /// Lists the compute nodes in the specified pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool from which you want to list nodes. /// </param> /// <param name='computeNodeListOptions'> /// Additional parameters for the operation /// </param> public static Microsoft.Rest.Azure.IPage<ComputeNode> List(this IComputeNodeOperations operations, string poolId, ComputeNodeListOptions computeNodeListOptions = default(ComputeNodeListOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IComputeNodeOperations)s).ListAsync(poolId, computeNodeListOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the compute nodes in the specified pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool from which you want to list nodes. /// </param> /// <param name='computeNodeListOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<ComputeNode>> ListAsync(this IComputeNodeOperations operations, string poolId, ComputeNodeListOptions computeNodeListOptions = default(ComputeNodeListOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(poolId, computeNodeListOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the compute nodes in the specified pool. /// </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='computeNodeListNextOptions'> /// Additional parameters for the operation /// </param> public static Microsoft.Rest.Azure.IPage<ComputeNode> ListNext(this IComputeNodeOperations operations, string nextPageLink, ComputeNodeListNextOptions computeNodeListNextOptions = default(ComputeNodeListNextOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IComputeNodeOperations)s).ListNextAsync(nextPageLink, computeNodeListNextOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the compute nodes in the specified pool. /// </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='computeNodeListNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<ComputeNode>> ListNextAsync(this IComputeNodeOperations operations, string nextPageLink, ComputeNodeListNextOptions computeNodeListNextOptions = default(ComputeNodeListNextOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, computeNodeListNextOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// EventResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Taskrouter.V1.Workspace { public class EventResource : Resource { private static Request BuildFetchRequest(FetchEventOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Taskrouter, "/v1/Workspaces/" + options.PathWorkspaceSid + "/Events/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Event parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Event </returns> public static EventResource Fetch(FetchEventOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Event parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Event </returns> public static async System.Threading.Tasks.Task<EventResource> FetchAsync(FetchEventOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Event to fetch </param> /// <param name="pathSid"> The SID of the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Event </returns> public static EventResource Fetch(string pathWorkspaceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchEventOptions(pathWorkspaceSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Event to fetch </param> /// <param name="pathSid"> The SID of the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Event </returns> public static async System.Threading.Tasks.Task<EventResource> FetchAsync(string pathWorkspaceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchEventOptions(pathWorkspaceSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadEventOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Taskrouter, "/v1/Workspaces/" + options.PathWorkspaceSid + "/Events", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Event parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Event </returns> public static ResourceSet<EventResource> Read(ReadEventOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<EventResource>.FromJson("events", response.Content); return new ResourceSet<EventResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Event parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Event </returns> public static async System.Threading.Tasks.Task<ResourceSet<EventResource>> ReadAsync(ReadEventOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<EventResource>.FromJson("events", response.Content); return new ResourceSet<EventResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Events to read </param> /// <param name="endDate"> Only include usage that occurred on or before this date </param> /// <param name="eventType"> The type of Events to read </param> /// <param name="minutes"> The period of events to read in minutes </param> /// <param name="reservationSid"> The SID of the Reservation with the Events to read </param> /// <param name="startDate"> Only include Events from on or after this date </param> /// <param name="taskQueueSid"> The SID of the TaskQueue with the Events to read </param> /// <param name="taskSid"> The SID of the Task with the Events to read </param> /// <param name="workerSid"> The SID of the Worker with the Events to read </param> /// <param name="workflowSid"> The SID of the Worker with the Events to read </param> /// <param name="taskChannel"> The TaskChannel with the Events to read </param> /// <param name="sid"> The unique string that identifies the resource </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Event </returns> public static ResourceSet<EventResource> Read(string pathWorkspaceSid, DateTime? endDate = null, string eventType = null, int? minutes = null, string reservationSid = null, DateTime? startDate = null, string taskQueueSid = null, string taskSid = null, string workerSid = null, string workflowSid = null, string taskChannel = null, string sid = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadEventOptions(pathWorkspaceSid){EndDate = endDate, EventType = eventType, Minutes = minutes, ReservationSid = reservationSid, StartDate = startDate, TaskQueueSid = taskQueueSid, TaskSid = taskSid, WorkerSid = workerSid, WorkflowSid = workflowSid, TaskChannel = taskChannel, Sid = sid, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Events to read </param> /// <param name="endDate"> Only include usage that occurred on or before this date </param> /// <param name="eventType"> The type of Events to read </param> /// <param name="minutes"> The period of events to read in minutes </param> /// <param name="reservationSid"> The SID of the Reservation with the Events to read </param> /// <param name="startDate"> Only include Events from on or after this date </param> /// <param name="taskQueueSid"> The SID of the TaskQueue with the Events to read </param> /// <param name="taskSid"> The SID of the Task with the Events to read </param> /// <param name="workerSid"> The SID of the Worker with the Events to read </param> /// <param name="workflowSid"> The SID of the Worker with the Events to read </param> /// <param name="taskChannel"> The TaskChannel with the Events to read </param> /// <param name="sid"> The unique string that identifies the resource </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Event </returns> public static async System.Threading.Tasks.Task<ResourceSet<EventResource>> ReadAsync(string pathWorkspaceSid, DateTime? endDate = null, string eventType = null, int? minutes = null, string reservationSid = null, DateTime? startDate = null, string taskQueueSid = null, string taskSid = null, string workerSid = null, string workflowSid = null, string taskChannel = null, string sid = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadEventOptions(pathWorkspaceSid){EndDate = endDate, EventType = eventType, Minutes = minutes, ReservationSid = reservationSid, StartDate = startDate, TaskQueueSid = taskQueueSid, TaskSid = taskSid, WorkerSid = workerSid, WorkflowSid = workflowSid, TaskChannel = taskChannel, Sid = sid, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<EventResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<EventResource>.FromJson("events", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<EventResource> NextPage(Page<EventResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Taskrouter) ); var response = client.Request(request); return Page<EventResource>.FromJson("events", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<EventResource> PreviousPage(Page<EventResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Taskrouter) ); var response = client.Request(request); return Page<EventResource>.FromJson("events", response.Content); } /// <summary> /// Converts a JSON string into a EventResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> EventResource object represented by the provided JSON </returns> public static EventResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<EventResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the resource that triggered the event /// </summary> [JsonProperty("actor_sid")] public string ActorSid { get; private set; } /// <summary> /// The type of resource that triggered the event /// </summary> [JsonProperty("actor_type")] public string ActorType { get; private set; } /// <summary> /// The absolute URL of the resource that triggered the event /// </summary> [JsonProperty("actor_url")] public Uri ActorUrl { get; private set; } /// <summary> /// A description of the event /// </summary> [JsonProperty("description")] public string Description { get; private set; } /// <summary> /// Data about the event /// </summary> [JsonProperty("event_data")] public object EventData { get; private set; } /// <summary> /// The time the event was sent /// </summary> [JsonProperty("event_date")] public DateTime? EventDate { get; private set; } /// <summary> /// The time the event was sent in milliseconds /// </summary> [JsonProperty("event_date_ms")] public long? EventDateMs { get; private set; } /// <summary> /// The identifier for the event /// </summary> [JsonProperty("event_type")] public string EventType { get; private set; } /// <summary> /// The SID of the object the event is most relevant to /// </summary> [JsonProperty("resource_sid")] public string ResourceSid { get; private set; } /// <summary> /// The type of object the event is most relevant to /// </summary> [JsonProperty("resource_type")] public string ResourceType { get; private set; } /// <summary> /// The URL of the resource the event is most relevant to /// </summary> [JsonProperty("resource_url")] public Uri ResourceUrl { get; private set; } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// Where the Event originated /// </summary> [JsonProperty("source")] public string Source { get; private set; } /// <summary> /// The IP from which the Event originated /// </summary> [JsonProperty("source_ip_address")] public string SourceIpAddress { get; private set; } /// <summary> /// The absolute URL of the Event resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The SID of the Workspace that contains the Event /// </summary> [JsonProperty("workspace_sid")] public string WorkspaceSid { get; private set; } private EventResource() { } } }
// 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 JetBrains.dotMemoryUnit; using Avalonia.Collections; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Diagnostics; using Avalonia.Layout; using Avalonia.Rendering; using Avalonia.Styling; using Avalonia.UnitTests; using Avalonia.VisualTree; using Moq; using Xunit; using Xunit.Abstractions; namespace Avalonia.LeakTests { [DotMemoryUnit(FailIfRunWithoutSupport = false)] public class ControlTests { public ControlTests(ITestOutputHelper atr) { DotMemoryUnitTestOutput.SetOutputMethod(atr.WriteLine); } [Fact] public void Canvas_Is_Freed() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { Func<Window> run = () => { var window = new Window { Content = new Canvas() }; // Do a layout and make sure that Canvas gets added to visual tree. LayoutManager.Instance.ExecuteInitialLayoutPass(window); Assert.IsType<Canvas>(window.Presenter.Child); // Clear the content and ensure the Canvas is removed. window.Content = null; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); PurgeMoqReferences(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount)); } } [Fact] public void Named_Canvas_Is_Freed() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { Func<Window> run = () => { var window = new Window { Content = new Canvas { Name = "foo" } }; // Do a layout and make sure that Canvas gets added to visual tree. LayoutManager.Instance.ExecuteInitialLayoutPass(window); Assert.IsType<Canvas>(window.Find<Canvas>("foo")); Assert.IsType<Canvas>(window.Presenter.Child); // Clear the content and ensure the Canvas is removed. window.Content = null; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); PurgeMoqReferences(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount)); } } [Fact] public void ScrollViewer_With_Content_Is_Freed() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { Func<Window> run = () => { var window = new Window { Content = new ScrollViewer { Content = new Canvas() } }; // Do a layout and make sure that ScrollViewer gets added to visual tree and its // template applied. LayoutManager.Instance.ExecuteInitialLayoutPass(window); Assert.IsType<ScrollViewer>(window.Presenter.Child); Assert.IsType<Canvas>(((ScrollViewer)window.Presenter.Child).Presenter.Child); // Clear the content and ensure the ScrollViewer is removed. window.Content = null; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); PurgeMoqReferences(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBox>()).ObjectsCount)); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount)); } } [Fact] public void TextBox_Is_Freed() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { Func<Window> run = () => { var window = new Window { Content = new TextBox() }; // Do a layout and make sure that TextBox gets added to visual tree and its // template applied. LayoutManager.Instance.ExecuteInitialLayoutPass(window); Assert.IsType<TextBox>(window.Presenter.Child); Assert.NotEqual(0, window.Presenter.Child.GetVisualChildren().Count()); // Clear the content and ensure the TextBox is removed. window.Content = null; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); PurgeMoqReferences(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBox>()).ObjectsCount)); } } [Fact] public void TextBox_With_Xaml_Binding_Is_Freed() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { Func<Window> run = () => { var window = new Window { DataContext = new Node { Name = "foo" }, Content = new TextBox() }; var binding = new Avalonia.Markup.Xaml.Data.Binding { Path = "Name" }; var textBox = (TextBox)window.Content; textBox.Bind(TextBox.TextProperty, binding); // Do a layout and make sure that TextBox gets added to visual tree and its // Text property set. LayoutManager.Instance.ExecuteInitialLayoutPass(window); Assert.IsType<TextBox>(window.Presenter.Child); Assert.Equal("foo", ((TextBox)window.Presenter.Child).Text); // Clear the content and DataContext and ensure the TextBox is removed. window.Content = null; window.DataContext = null; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); PurgeMoqReferences(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBox>()).ObjectsCount)); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Node>()).ObjectsCount)); } } [Fact] public void TextBox_Class_Listeners_Are_Freed() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { TextBox textBox; var window = new Window { Content = textBox = new TextBox() }; // Do a layout and make sure that TextBox gets added to visual tree and its // template applied. LayoutManager.Instance.ExecuteInitialLayoutPass(window); Assert.Same(textBox, window.Presenter.Child); // Get the border from the TextBox template. var border = textBox.GetTemplateChildren().FirstOrDefault(x => x.Name == "border"); // The TextBox should have subscriptions to its Classes collection from the // default theme. Assert.NotEmpty(((INotifyCollectionChangedDebug)textBox.Classes).GetCollectionChangedSubscribers()); // Clear the content and ensure the TextBox is removed. window.Content = null; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); // Check that the TextBox has no subscriptions to its Classes collection. Assert.Null(((INotifyCollectionChangedDebug)textBox.Classes).GetCollectionChangedSubscribers()); } } [Fact] public void TreeView_Is_Freed() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { Func<Window> run = () => { var nodes = new[] { new Node { Children = new[] { new Node() }, } }; TreeView target; var window = new Window { Content = target = new TreeView { DataTemplates = new DataTemplates { new FuncTreeDataTemplate<Node>( x => new TextBlock { Text = x.Name }, x => x.Children) }, Items = nodes } }; // Do a layout and make sure that TreeViewItems get realized. LayoutManager.Instance.ExecuteInitialLayoutPass(window); Assert.Equal(1, target.ItemContainerGenerator.Containers.Count()); // Clear the content and ensure the TreeView is removed. window.Content = null; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); PurgeMoqReferences(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TreeView>()).ObjectsCount)); } } private static void PurgeMoqReferences() { // Moq holds onto references in its mock of IRenderer in case we want to check if a method has been called; // clear these. var renderer = Mock.Get(AvaloniaLocator.Current.GetService<IRenderer>()); renderer.ResetCalls(); } private class Node { public string Name { get; set; } public IEnumerable<Node> Children { get; set; } } } }
// created on 12/18/2004 at 16:28 using System; using System.Threading; using System.Diagnostics; namespace Moscrif.IDE.Execution { public delegate void ProcessEventHandler(object sender, string message); public class ProcessWrapper : Process, IProcessAsyncOperation { private Thread captureOutputThread; private Thread captureErrorThread; ManualResetEvent endEventOut = new ManualResetEvent (false); ManualResetEvent endEventErr = new ManualResetEvent (false); bool done; object lockObj = new object (); public ProcessWrapper () { } public new void Start () { CheckDisposed (); //base.PriorityClass = ProcessPriorityClass.Normal; //base. base.Start (); captureOutputThread = new Thread (new ThreadStart(CaptureOutput)); captureOutputThread.Name = "Process output reader"; captureOutputThread.IsBackground = true; captureOutputThread.Start (); if (ErrorStreamChanged != null) { captureErrorThread = new Thread (new ThreadStart(CaptureError)); captureErrorThread.Name = "Process error reader"; captureErrorThread.IsBackground = true; captureErrorThread.Start (); } else { endEventErr.Set (); } } public void WaitForOutput (int milliseconds) { CheckDisposed (); WaitForExit (milliseconds); WaitHandle.WaitAll (new WaitHandle[] {endEventOut}); } public void WaitForOutput () { WaitForOutput (-1); } private void CaptureOutput () { try { if (OutputStreamChanged != null) { char[] buffer = new char [1024]; int nr; while ((nr = StandardOutput.Read (buffer, 0, buffer.Length)) > 0) { if (OutputStreamChanged != null) OutputStreamChanged (this, new string (buffer, 0, nr)); } } } catch (ThreadAbortException) { // There is no need to keep propagating the abort exception Thread.ResetAbort (); } finally { // WORKAROUND for "Bug 410743 - wapi leak in System.Diagnostic.Process" // Process leaks when an exit event is registered if (endEventErr != null) WaitHandle.WaitAll (new WaitHandle[] {endEventErr} ); OnExited (this, EventArgs.Empty); //call this AFTER the exit event, or the ProcessWrapper may get disposed and abort this thread if (endEventOut != null) endEventOut.Set (); } } private void CaptureError () { try { char[] buffer = new char [1024]; int nr; while ((nr = StandardError.Read (buffer, 0, buffer.Length)) > 0) { if (ErrorStreamChanged != null) ErrorStreamChanged (this, new string (buffer, 0, nr)); } } finally { if (endEventErr != null) endEventErr.Set (); } } protected override void Dispose (bool disposing) { lock (lockObj) { if (endEventOut == null) return; } if (!done) ((IAsyncOperation)this).Cancel (); captureOutputThread = captureErrorThread = null; endEventOut.Close (); endEventErr.Close (); endEventOut = endEventErr = null; base.Dispose (disposing); } void CheckDisposed () { if (endEventOut == null) throw new ObjectDisposedException ("ProcessWrapper"); } int IProcessAsyncOperation.ExitCode { get { return ExitCode; } } int IProcessAsyncOperation.ProcessId { get { return Id; } } void IAsyncOperation.Cancel () { try { if (!done) { try { Kill (); } catch { // Ignore } } } catch {//(Exception ex) { // LoggingService.LogError (ex.ToString ()); } } void IAsyncOperation.WaitForCompleted () { WaitForOutput (); } void OnExited (object sender, EventArgs args) { try { if (!HasExited) WaitForExit (); } catch { // Ignore } finally { lock (lockObj) { done = true; try { if (completedEvent != null) completedEvent (this); } catch { // Ignore } } } } event OperationHandler IAsyncOperation.Completed { add { bool raiseNow = false; lock (lockObj) { if (done) raiseNow = true; else completedEvent += value; } if (raiseNow) value (this); } remove { lock (lockObj) { completedEvent -= value; } } } bool IAsyncOperation.Success { get { return done ? ExitCode == 0 : false; } } bool IAsyncOperation.SuccessWithWarnings { get { return false; } } bool IAsyncOperation.IsCompleted { get { return done; } } event OperationHandler completedEvent; public event ProcessEventHandler OutputStreamChanged; public event ProcessEventHandler ErrorStreamChanged; } }
#define WITH_ZLIB #define WITH_BZIP // // MpqHuffman.cs // // Authors: // Foole (fooleau@gmail.com) // // (C) 2006 Foole (fooleau@gmail.com) // Based on code from StormLib by Ladislav Zezula // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; #if WITH_ZLIB using ICSharpCode.SharpZipLib.Zip.Compression.Streams; #endif #if WITH_BZIP using ICSharpCode.SharpZipLib.BZip2; #endif namespace Foole.Mpq { /// <summary> /// A Stream based class for reading a file from an MPQ file /// </summary> public class MpqStream : Stream { private Stream _stream; private int _blockSize; private MpqEntry _entry; private uint[] _blockPositions; private long _position; private byte[] _currentData; private int _currentBlockIndex = -1; internal MpqStream(MpqArchive archive, MpqEntry entry) { _entry = entry; _stream = archive.BaseStream; _blockSize = archive.BlockSize; if (_entry.IsCompressed && !_entry.IsSingleUnit) LoadBlockPositions(); } // Compressed files start with an array of offsets to make seeking possible private void LoadBlockPositions() { int blockposcount = (int)((_entry.FileSize + _blockSize - 1) / _blockSize) + 1; // Files with metadata have an extra block containing block checksums if ((_entry.Flags & MpqFileFlags.FileHasMetadata) != 0) blockposcount++; _blockPositions = new uint[blockposcount]; lock(_stream) { _stream.Seek(_entry.FilePos, SeekOrigin.Begin); BinaryReader br = new BinaryReader(_stream); for(int i = 0; i < blockposcount; i++) _blockPositions[i] = br.ReadUInt32(); } uint blockpossize = (uint) blockposcount * 4; /* if(_blockPositions[0] != blockpossize) _entry.Flags |= MpqFileFlags.Encrypted; */ if (_entry.IsEncrypted) { if (_entry.EncryptionSeed == 0) // This should only happen when the file name is not known { _entry.EncryptionSeed = MpqArchive.DetectFileSeed(_blockPositions[0], _blockPositions[1], blockpossize) + 1; if (_entry.EncryptionSeed == 1) throw new MpqParserException("Unable to determine encyption seed"); } MpqArchive.DecryptBlock(_blockPositions, _entry.EncryptionSeed - 1); if (_blockPositions[0] != blockpossize) throw new MpqParserException("Decryption failed"); if (_blockPositions[1] > _blockSize + blockpossize) throw new MpqParserException("Decryption failed"); } } private byte[] LoadBlock(int blockIndex, int expectedLength) { uint offset; int toread; uint encryptionseed; if (_entry.IsCompressed) { offset = _blockPositions[blockIndex]; toread = (int)(_blockPositions[blockIndex + 1] - offset); } else { offset = (uint)(blockIndex * _blockSize); toread = expectedLength; } offset += _entry.FilePos; byte[] data = new byte[toread]; lock (_stream) { _stream.Seek(offset, SeekOrigin.Begin); int read = _stream.Read(data, 0, toread); if (read != toread) throw new MpqParserException("Insufficient data or invalid data length"); } if (_entry.IsEncrypted && _entry.FileSize > 3) { if (_entry.EncryptionSeed == 0) throw new MpqParserException("Unable to determine encryption key"); encryptionseed = (uint)(blockIndex + _entry.EncryptionSeed); MpqArchive.DecryptBlock(data, encryptionseed); } if (_entry.IsCompressed && (toread != expectedLength)) { if ((_entry.Flags & MpqFileFlags.CompressedMulti) != 0) data = DecompressMulti(data, expectedLength); else data = PKDecompress(new MemoryStream(data), expectedLength); } return data; } #region Stream overrides public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return false; } } public override long Length { get { return _entry.FileSize; } } public override long Position { get { return _position; } set { Seek(value, SeekOrigin.Begin); } } public override void Flush() { // NOP } public override long Seek(long offset, SeekOrigin origin) { long target; switch (origin) { case SeekOrigin.Begin: target = offset; break; case SeekOrigin.Current: target = Position + offset; break; case SeekOrigin.End: target = Length + offset; break; default: throw new ArgumentException("Origin", "Invalid SeekOrigin"); } if (target < 0) throw new ArgumentOutOfRangeException("Attmpted to Seek before the beginning of the stream"); if (target >= Length) throw new ArgumentOutOfRangeException("Attmpted to Seek beyond the end of the stream"); _position = target; return _position; } public override void SetLength(long value) { throw new NotSupportedException("SetLength is not supported"); } public override int Read(byte[] buffer, int offset, int count) { if (_entry.IsSingleUnit) return ReadInternalSingleUnit(buffer, offset, count); int toread = count; int readtotal = 0; while (toread > 0) { int read = ReadInternal(buffer, offset, toread); if (read == 0) break; readtotal += read; offset += read; toread -= read; } return readtotal; } // SingleUnit entries can be compressed but are never encrypted private int ReadInternalSingleUnit(byte[] buffer, int offset, int count) { if (_position >= Length) return 0; if (_currentData == null) LoadSingleUnit(); int bytestocopy = Math.Min((int)(_currentData.Length - _position), count); Array.Copy(_currentData, _position, buffer, offset, bytestocopy); _position += bytestocopy; return bytestocopy; } private void LoadSingleUnit() { // Read the entire file into memory byte[] filedata = new byte[_entry.CompressedSize]; lock (_stream) { _stream.Seek(_entry.FilePos, SeekOrigin.Begin); int read = _stream.Read(filedata, 0, filedata.Length); if (read != filedata.Length) throw new MpqParserException("Insufficient data or invalid data length"); } if (_entry.CompressedSize == _entry.FileSize) _currentData = filedata; else _currentData = DecompressMulti(filedata, (int)_entry.FileSize); } private int ReadInternal(byte[] buffer, int offset, int count) { // OW: avoid reading past the contents of the file if (_position >= Length) return 0; BufferData(); int localposition = (int)(_position % _blockSize); int bytestocopy = Math.Min(_currentData.Length - localposition, count); if (bytestocopy <= 0) return 0; Array.Copy(_currentData, localposition, buffer, offset, bytestocopy); _position += bytestocopy; return bytestocopy; } public override int ReadByte() { if (_position >= Length) return -1; if (_entry.IsSingleUnit) return ReadByteSingleUnit(); BufferData(); int localposition = (int)(_position % _blockSize); _position++; return _currentData[localposition]; } private int ReadByteSingleUnit() { if (_currentData == null) LoadSingleUnit(); return _currentData[_position++]; } private void BufferData() { int requiredblock = (int)(_position / _blockSize); if (requiredblock != _currentBlockIndex) { int expectedlength = (int)Math.Min(Length - (requiredblock * _blockSize), _blockSize); _currentData = LoadBlock(requiredblock, expectedlength); _currentBlockIndex = requiredblock; } } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException("Writing is not supported"); } #endregion Strem overrides /* Compression types in order: * 10 = BZip2 * 8 = PKLib * 2 = ZLib * 1 = Huffman * 80 = IMA ADPCM Stereo * 40 = IMA ADPCM Mono */ private static byte[] DecompressMulti(byte[] input, int outputLength) { Stream sinput = new MemoryStream(input); byte comptype = (byte)sinput.ReadByte(); // WC3 onward mosly use Zlib // Starcraft 1 mostly uses PKLib, plus types 41 and 81 for audio files switch (comptype) { case 1: // Huffman return MpqHuffman.Decompress(sinput).ToArray(); case 2: // ZLib/Deflate #if WITH_ZLIB return ZlibDecompress(sinput, outputLength); #endif case 8: // PKLib/Impode return PKDecompress(sinput, outputLength); case 0x10: // BZip2 #if WITH_BZIP return BZip2Decompress(sinput, outputLength); #endif case 0x80: // IMA ADPCM Stereo return MpqWavCompression.Decompress(sinput, 2); case 0x40: // IMA ADPCM Mono return MpqWavCompression.Decompress(sinput, 1); case 0x12: // TODO: LZMA throw new MpqParserException("LZMA compression is not yet supported"); // Combos case 0x22: // TODO: sparse then zlib throw new MpqParserException("Sparse compression + Deflate compression is not yet supported"); case 0x30: // TODO: sparse then bzip2 throw new MpqParserException("Sparse compression + BZip2 compression is not yet supported"); case 0x41: sinput = MpqHuffman.Decompress(sinput); return MpqWavCompression.Decompress(sinput, 1); case 0x48: { byte[] result = PKDecompress(sinput, outputLength); return MpqWavCompression.Decompress(new MemoryStream(result), 1); } case 0x81: sinput = MpqHuffman.Decompress(sinput); return MpqWavCompression.Decompress(sinput, 2); case 0x88: { byte[] result = PKDecompress(sinput, outputLength); return MpqWavCompression.Decompress(new MemoryStream(result), 2); } default: throw new MpqParserException("Compression is not yet supported: 0x" + comptype.ToString("X")); } } #if WITH_BZIP private static byte[] BZip2Decompress(Stream data, int expectedLength) { using (var output = new MemoryStream(expectedLength)) { BZip2.Decompress(data, output, false); return output.ToArray(); } } #endif private static byte[] PKDecompress(Stream data, int expectedLength) { PKLibDecompress pk = new PKLibDecompress(data); return pk.Explode(expectedLength); } #if WITH_ZLIB private static byte[] ZlibDecompress(Stream data, int expectedLength) { // This assumes that Zlib won't be used in combination with another compression type byte[] Output = new byte[expectedLength]; Stream s = new InflaterInputStream(data); int Offset = 0; while (expectedLength > 0) { int size = s.Read(Output, Offset, expectedLength); if (size == 0) break; Offset += size; expectedLength -= size; } return Output; } #endif } }
using System; using System.Linq; using System.Runtime.InteropServices; using Torque6.Engine.SimObjects; using Torque6.Engine.SimObjects.Scene; using Torque6.Engine.Namespaces; using Torque6.Utility; namespace Torque6.Engine.SimObjects.GuiControls { public unsafe class GuiControlArrayControl : GuiControl { public GuiControlArrayControl() { ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.GuiControlArrayControlCreateInstance()); } public GuiControlArrayControl(uint pId) : base(pId) { } public GuiControlArrayControl(string pName) : base(pName) { } public GuiControlArrayControl(IntPtr pObjPtr) : base(pObjPtr) { } public GuiControlArrayControl(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr) { } public GuiControlArrayControl(SimObject pObj) : base(pObj) { } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _GuiControlArrayControlGetColCount(IntPtr ctrl); private static _GuiControlArrayControlGetColCount _GuiControlArrayControlGetColCountFunc; internal static int GuiControlArrayControlGetColCount(IntPtr ctrl) { if (_GuiControlArrayControlGetColCountFunc == null) { _GuiControlArrayControlGetColCountFunc = (_GuiControlArrayControlGetColCount)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiControlArrayControlGetColCount"), typeof(_GuiControlArrayControlGetColCount)); } return _GuiControlArrayControlGetColCountFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiControlArrayControlSetColCount(IntPtr ctrl, int cols); private static _GuiControlArrayControlSetColCount _GuiControlArrayControlSetColCountFunc; internal static void GuiControlArrayControlSetColCount(IntPtr ctrl, int cols) { if (_GuiControlArrayControlSetColCountFunc == null) { _GuiControlArrayControlSetColCountFunc = (_GuiControlArrayControlSetColCount)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiControlArrayControlSetColCount"), typeof(_GuiControlArrayControlSetColCount)); } _GuiControlArrayControlSetColCountFunc(ctrl, cols); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _GuiControlArrayControlGetRowSize(IntPtr ctrl); private static _GuiControlArrayControlGetRowSize _GuiControlArrayControlGetRowSizeFunc; internal static int GuiControlArrayControlGetRowSize(IntPtr ctrl) { if (_GuiControlArrayControlGetRowSizeFunc == null) { _GuiControlArrayControlGetRowSizeFunc = (_GuiControlArrayControlGetRowSize)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiControlArrayControlGetRowSize"), typeof(_GuiControlArrayControlGetRowSize)); } return _GuiControlArrayControlGetRowSizeFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiControlArrayControlSetRowSize(IntPtr ctrl, int size); private static _GuiControlArrayControlSetRowSize _GuiControlArrayControlSetRowSizeFunc; internal static void GuiControlArrayControlSetRowSize(IntPtr ctrl, int size) { if (_GuiControlArrayControlSetRowSizeFunc == null) { _GuiControlArrayControlSetRowSizeFunc = (_GuiControlArrayControlSetRowSize)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiControlArrayControlSetRowSize"), typeof(_GuiControlArrayControlSetRowSize)); } _GuiControlArrayControlSetRowSizeFunc(ctrl, size); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _GuiControlArrayControlGetRowSpacing(IntPtr ctrl); private static _GuiControlArrayControlGetRowSpacing _GuiControlArrayControlGetRowSpacingFunc; internal static int GuiControlArrayControlGetRowSpacing(IntPtr ctrl) { if (_GuiControlArrayControlGetRowSpacingFunc == null) { _GuiControlArrayControlGetRowSpacingFunc = (_GuiControlArrayControlGetRowSpacing)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiControlArrayControlGetRowSpacing"), typeof(_GuiControlArrayControlGetRowSpacing)); } return _GuiControlArrayControlGetRowSpacingFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiControlArrayControlSetRowSpacing(IntPtr ctrl, int spacing); private static _GuiControlArrayControlSetRowSpacing _GuiControlArrayControlSetRowSpacingFunc; internal static void GuiControlArrayControlSetRowSpacing(IntPtr ctrl, int spacing) { if (_GuiControlArrayControlSetRowSpacingFunc == null) { _GuiControlArrayControlSetRowSpacingFunc = (_GuiControlArrayControlSetRowSpacing)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiControlArrayControlSetRowSpacing"), typeof(_GuiControlArrayControlSetRowSpacing)); } _GuiControlArrayControlSetRowSpacingFunc(ctrl, spacing); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _GuiControlArrayControlGetColSpacing(IntPtr ctrl); private static _GuiControlArrayControlGetColSpacing _GuiControlArrayControlGetColSpacingFunc; internal static int GuiControlArrayControlGetColSpacing(IntPtr ctrl) { if (_GuiControlArrayControlGetColSpacingFunc == null) { _GuiControlArrayControlGetColSpacingFunc = (_GuiControlArrayControlGetColSpacing)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiControlArrayControlGetColSpacing"), typeof(_GuiControlArrayControlGetColSpacing)); } return _GuiControlArrayControlGetColSpacingFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiControlArrayControlSetColSpacing(IntPtr ctrl, int spacing); private static _GuiControlArrayControlSetColSpacing _GuiControlArrayControlSetColSpacingFunc; internal static void GuiControlArrayControlSetColSpacing(IntPtr ctrl, int spacing) { if (_GuiControlArrayControlSetColSpacingFunc == null) { _GuiControlArrayControlSetColSpacingFunc = (_GuiControlArrayControlSetColSpacing)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiControlArrayControlSetColSpacing"), typeof(_GuiControlArrayControlSetColSpacing)); } _GuiControlArrayControlSetColSpacingFunc(ctrl, spacing); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _GuiControlArrayControlCreateInstance(); private static _GuiControlArrayControlCreateInstance _GuiControlArrayControlCreateInstanceFunc; internal static IntPtr GuiControlArrayControlCreateInstance() { if (_GuiControlArrayControlCreateInstanceFunc == null) { _GuiControlArrayControlCreateInstanceFunc = (_GuiControlArrayControlCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiControlArrayControlCreateInstance"), typeof(_GuiControlArrayControlCreateInstance)); } return _GuiControlArrayControlCreateInstanceFunc(); } } #endregion #region Properties public int ColCount { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiControlArrayControlGetColCount(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiControlArrayControlSetColCount(ObjectPtr->ObjPtr, value); } } public int RowSize { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiControlArrayControlGetRowSize(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiControlArrayControlSetRowSize(ObjectPtr->ObjPtr, value); } } public int RowSpacing { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiControlArrayControlGetRowSpacing(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiControlArrayControlSetRowSpacing(ObjectPtr->ObjPtr, value); } } public int ColSpacing { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiControlArrayControlGetColSpacing(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiControlArrayControlSetColSpacing(ObjectPtr->ObjPtr, value); } } #endregion #region Methods #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; namespace Codentia.Common.Helper { /// <summary> /// Class for assisting with XML functionality /// </summary> public static class XMLHelper { //// <summary> //// Get a NodeList From an XmlDoc for a specified xPath //// </summary> //// <param name="xDoc">Xml Document</param> //// <param name="xPath">XPath Query</param> //// <returns>XmlNodeList</returns> //// public static XmlNodeList GetNodeListFromXmlDoc(XmlDocument xDoc, string xPath) //// { //// XmlNodeList xNodes = null; //// if (xDoc != null) //// { //// try //// { //// xNodes = xDoc.SelectNodes(xPath); //// } //// catch (Exception ex) //// { //// ////log here //// throw new Exception("Invalid xPath", ex); //// } //// } //// return xNodes; //// } //// <summary> //// Get a single Node From an XmlDoc for a specified xPath //// </summary> //// <param name="xDoc">Xml Document</param> //// <param name="xPath">XPath Query</param> //// <returns>XmlNode</returns> //// public static XmlNode GetNodeFromXmlDoc(XmlDocument xDoc, string xPath) //// { //// XmlNode xNode = null; //// if (xDoc != null) //// { //// try //// { //// xNode = xDoc.SelectSingleNode(xPath); //// } //// catch (Exception ex) //// { //// ////log here //// throw new Exception("Invalid xPath", ex); //// } //// } //// return xNode; //// } //// <summary> //// Get inner Xml for the XPath query with the xmlString //// </summary> //// <param name="xmlString">Xml String</param> //// <param name="xPath">XPath Query</param> //// <returns>string</returns> //// public static string GetInnerXmlFromXmlString(string xmlString, string xPath) ////{ //// XmlDocument xDoc= GetXmlDoc(xmlString); //// XmlNodeList xnl = XMLHelper.GetNodeListFromXmlDoc(xDoc, xPath); //// string innerX = string.Empty; //// if (xnl != null) //// { //// if (xnl.Count > 0) //// { //// innerX = xnl[0].InnerXml; //// } //// } //// return innerX; //// } //// <summary> //// Get the root node string for a given xml //// Note it must be in the format of a root node //// </summary> //// <param name="xmlString">Xml String</param> //// <returns>string</returns> ////public static string GetRootNodeFromXmlString(string xmlString) ////{ //// XmlDocument xDoc = GetXmlDoc(xmlString); //// return xDoc.FirstChild.Name; ////} //// <summary> //// Get a NodeList From a Node for a specified xPath //// </summary> //// <param name="node">Xml Node</param> //// <param name="xPath">XPath Query</param> //// <returns>XmlNodeList</returns> //// public static XmlNodeList GetNodeListFromNode(XmlNode node, string xPath) //// { //// XmlNodeList xNodes = null; //// if (node != null) //// { //// try //// { //// xNodes = node.SelectNodes(xPath); //// } //// catch (Exception ex) //// { //// //// log here //// throw new Exception("Invalid xPath", ex); //// } //// } //// return xNodes; ////} /// <summary> /// Get an Xml Doc for a specified xmlString /// </summary> /// <param name="xmlString">String representing an Xml Document</param> /// <param name="stringName">string name (for exception message)</param> /// <returns>XmlDocument after conversion</returns> public static XmlDocument GetXmlDoc(string xmlString, string stringName) { ParameterCheckHelper.CheckIsValidString(xmlString, stringName, false); XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.LoadXml(xmlString); } catch (Exception ex) { // log here throw new ArgumentException(string.Format("{0} is not valid", stringName), ex); } return xmlDoc; } /// <summary> /// Creates an Xml document with a specified root node /// </summary> /// <param name="rootNodeName">Name of the root node.</param> /// <returns>XmlDocument after creation</returns> public static XmlDocument CreateDocument(string rootNodeName) { ParameterCheckHelper.CheckIsValidString("rootNodeName", rootNodeName, false); XmlDocument xmlDoc = new XmlDocument(); string rootNodeXml = string.Format("<{0}></{0}>", rootNodeName); xmlDoc.LoadXml(rootNodeXml); return xmlDoc; } /// <summary> /// Return a comma delimited list as an xml doc with root as root node and each element with elementname /// </summary> /// <param name="csvList">Comma delimited list</param> /// <param name="elementName">element name to give each value</param> /// <returns>XmlDocument after conversion</returns> public static XmlDocument ConvertCSVStringToXmlDoc(string csvList, string elementName) { ParameterCheckHelper.CheckIsValidString(csvList, "csvList", false); ParameterCheckHelper.CheckIsValidString(elementName, "elementName", false); XmlDocument xml = new XmlDocument(); xml.LoadXml("<root></root>"); XmlElement root = xml.DocumentElement; string[] arr = csvList.Split(','); for (int i = 0; i < arr.Length; i++) { XmlNode node = xml.CreateNode("element", elementName, string.Empty); node.InnerText = arr[i]; root.AppendChild(node); } return xml; } /// <summary> /// Check an Xml string contains /// </summary> /// <param name="node">an xml node with child nodes to check</param> /// <param name="stringName">string name (for exception message)</param> /// <param name="attributesToCheck">string array of attributes to check</param> public static void CheckAttributesInXmlNodeChildren(XmlNode node, string stringName, string[] attributesToCheck) { if (node.ChildNodes.Count == 0) { throw new ArgumentException("node does not have any child nodes"); } for (int i = 0; i < attributesToCheck.Length; i++) { ParameterCheckHelper.CheckIsValidString(attributesToCheck[i], string.Format("attribute {0}", i), false); } for (int i = 0; i < node.ChildNodes.Count; i++) { XmlNode currentNode = node.ChildNodes[i]; for (int j = 0; j < attributesToCheck.Length; j++) { try { string value = currentNode.Attributes[attributesToCheck[j]].Value; } catch (Exception ex) { throw new ArgumentException("Required attribute(s) are missing from node", ex); } } } } /// <summary> /// Convert A Collection of data to Xml (Dictionary int string version) /// </summary> /// <param name="rootNode">Root Node Name</param> /// <param name="data">actual data </param> /// <param name="nodeNames">int -1, 0, 2 -- -1=element node, 0,1 =position of the node in the data parameter) string=nodeName</param> /// <param name="nodeTypes">int -1, 0, 2 -- -1=element node, 0,1= position of the node in the data parameter) XmlNodeType=Attribute or Element (no other types allowed)</param> /// <returns>XmlDocument after conversion</returns> public static XmlDocument ConvertCollectionToXml(string rootNode, Dictionary<int, string> data, Dictionary<int, string> nodeNames, Dictionary<int, XmlNodeType> nodeTypes) { ParameterCheckHelper.CheckIsValidString(rootNode, "rootNode", false); ParameterCheckHelper.CheckICollectionIsNotNullOrEmpty(data, "data"); ParameterCheckHelper.CheckICollectionCount(3, nodeNames, "nodeNames"); ParameterCheckHelper.CheckICollectionCount(2, nodeTypes, "nodeTypes"); // check nodeNames for (int i = -1; i <= 1; i++) { try { string nodeName = nodeNames[i]; } catch { throw new ArgumentException("nodeNames can only contain -1, 0 or 1 as the keys"); } } // check nodeTypes for (int i = 0; i <= 1; i++) { XmlNodeType nodeType; try { nodeType = nodeTypes[i]; } catch { throw new ArgumentException("nodeTypes can only contain 0 or 1 as the keys"); } if (nodeType != XmlNodeType.Element && nodeType != XmlNodeType.Attribute) { throw new ArgumentException(string.Format("nodeType {0} is not allowed - only Element or Attribute", nodeType.ToString())); } } // add -1 Element nodeTypes.Add(-1, XmlNodeType.Element); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(string.Format("<{0}></{0}>", rootNode)); XmlElement root = xmlDoc.DocumentElement; string mainElementName = nodeNames[-1]; IEnumerator<int> ie = data.Keys.GetEnumerator(); while (ie.MoveNext()) { XmlNode node = CreateElementNode(xmlDoc, mainElementName); for (int j = 0; j <= 1; j++) { string nodeValue = data[ie.Current]; if (j == 0) { nodeValue = Convert.ToString(ie.Current); } else { nodeValue = StringHelper.EncodeForSavingToSql(data[ie.Current]); } string nodeChildName = nodeNames[j]; switch (nodeTypes[j]) { case XmlNodeType.Element: AppendElementChildNode(xmlDoc, node, nodeChildName, nodeValue); break; case XmlNodeType.Attribute: AppendAttributeNode(xmlDoc, node, nodeChildName, nodeValue); break; } root.AppendChild(node); } } return xmlDoc; } /// <summary> /// Convert A Collection of data to Xml (List int version) /// </summary> /// <param name="rootNode">Root Node Name</param> /// <param name="data">actual data </param> /// <param name="elementName">element name</param> /// <param name="attributeName">attribute name</param> /// <returns>XmlDocument after conversion</returns> public static XmlDocument ConvertCollectionToXml(string rootNode, List<int> data, string elementName, string attributeName) { ParameterCheckHelper.CheckIsValidString(rootNode, "rootNode", false); ParameterCheckHelper.CheckICollectionIsNotNullOrEmpty(data, "data"); ParameterCheckHelper.CheckIsValidString(elementName, "elementName", false); ParameterCheckHelper.CheckIsValidString(attributeName, "attributeName", false); Dictionary<int, string> names = CreateNamesDictionary(elementName, attributeName); List<string> stringList = new List<string>(); IEnumerator ie = data.GetEnumerator(); while (ie.MoveNext()) { stringList.Add(Convert.ToString(ie.Current)); } return ConvertListToXml(rootNode, stringList, names); } /// <summary> /// Convert A Collection of data to Xml (List string version) /// </summary> /// <param name="rootNode">Root Node Name</param> /// <param name="data">actual data </param> /// <param name="elementName">element name</param> /// <param name="attributeName">attribute name</param> /// <returns>XmlDocument after conversion</returns> public static XmlDocument ConvertCollectionToXml(string rootNode, List<string> data, string elementName, string attributeName) { ParameterCheckHelper.CheckIsValidString(rootNode, "rootNode", false); ParameterCheckHelper.CheckICollectionIsNotNullOrEmpty(data, "data"); ParameterCheckHelper.CheckIsValidString(elementName, "elementName", false); ParameterCheckHelper.CheckIsValidString(attributeName, "attributeName", false); Dictionary<int, string> names = CreateNamesDictionary(elementName, attributeName); return ConvertListToXml(rootNode, data, names); } /// <summary> /// Convert A Collection of data to Xml (string[] version) /// </summary> /// <param name="rootNode">Root Node Name</param> /// <param name="data">actual data </param> /// <param name="elementName">element name</param> /// <param name="attributeName">attribute name</param> /// <returns>XmlDocument after conversion</returns> public static XmlDocument ConvertCollectionToXml(string rootNode, string[] data, string elementName, string attributeName) { ParameterCheckHelper.CheckIsValidString(rootNode, "rootNode", false); ParameterCheckHelper.CheckICollectionIsNotNullOrEmpty(data, "data"); ParameterCheckHelper.CheckIsValidString(elementName, "elementName", false); ParameterCheckHelper.CheckIsValidString(attributeName, "attributeName", false); Dictionary<int, string> names = CreateNamesDictionary(elementName, attributeName); List<string> stringList = new List<string>(); for (int i = 0; i < data.Length; i++) { stringList.Add(data[i]); } return ConvertListToXml(rootNode, stringList, names); } /// <summary> /// Convert A Collection of data to Xml (int[] version) /// </summary> /// <param name="rootNode">Root Node Name</param> /// <param name="data">actual data </param> /// <param name="elementName">element name</param> /// <param name="attributeName">attribute name</param> /// <returns>XmlDocument after conversion</returns> public static XmlDocument ConvertCollectionToXml(string rootNode, int[] data, string elementName, string attributeName) { ParameterCheckHelper.CheckIsValidString(rootNode, "rootNode", false); ParameterCheckHelper.CheckICollectionIsNotNullOrEmpty(data, "data"); ParameterCheckHelper.CheckIsValidString(elementName, "elementName", false); ParameterCheckHelper.CheckIsValidString(attributeName, "attributeName", false); Dictionary<int, string> names = CreateNamesDictionary(elementName, attributeName); List<string> stringList = new List<string>(); for (int i = 0; i < data.Length; i++) { stringList.Add(Convert.ToString(data[i])); } return ConvertListToXml(rootNode, stringList, names); } /// <summary> /// Create Element Node /// </summary> /// <param name="xmlDoc">Xml Document to create node in</param> /// <param name="elementName">Name of Element</param> /// <returns>An XmlNode</returns> public static XmlNode CreateElementNode(XmlDocument xmlDoc, string elementName) { ParameterCheckHelper.CheckIsValidString(elementName, "elementName", false); XmlNode node = xmlDoc.CreateNode("element", elementName, string.Empty); return node; } /// <summary> /// Add an element node with a value /// </summary> /// <param name="xmlDoc">Xml Document to create node in</param> /// <param name="parentNode">Parent Node</param> /// <param name="elementName">Name of element</param> /// <param name="elementValue">Value of element</param> public static void AppendElementChildNode(XmlDocument xmlDoc, XmlNode parentNode, string elementName, string elementValue) { ParameterCheckHelper.CheckIsValidString(elementName, "elementName", false); XmlNode nodeChild = xmlDoc.CreateElement(elementName); nodeChild.InnerXml = elementValue; parentNode.AppendChild(nodeChild); } /// <summary> /// Add an attribute node with a value /// </summary> /// <param name="xmlDoc">Xml Document to create node in</param> /// <param name="parentNode">Parent Node</param> /// <param name="attributeName">Name of attribute</param> /// <param name="attributeValue">Value of attribute</param> public static void AppendAttributeNode(XmlDocument xmlDoc, XmlNode parentNode, string attributeName, string attributeValue) { ParameterCheckHelper.CheckIsValidString(attributeName, "attributeName", false); XmlAttribute xa = (XmlAttribute)xmlDoc.CreateNode("attribute", attributeName, string.Empty); xa.Value = attributeValue; parentNode.Attributes.Append(xa); } /// <summary> /// Gets the XML text writer. /// </summary> /// <param name="openingTag">The opening tag.</param> /// <returns>XmlTextWriter for writing</returns> public static XmlTextWriter GetXmlTextWriter(string openingTag) { MemoryStream outputStream = new MemoryStream(); XmlTextWriter xmlOut = new XmlTextWriter(outputStream, Encoding.Default); xmlOut.WriteStartDocument(); xmlOut.WriteStartElement(openingTag); return xmlOut; } /// <summary> /// Gets the XML document. /// </summary> /// <param name="writer">The writer.</param> /// <returns>XmlDocument from XmlTextWriter</returns> public static XmlDocument GetXmlDocument(XmlTextWriter writer) { XmlDocument result = new XmlDocument(); writer.WriteEndDocument(); writer.Flush(); writer.BaseStream.Seek(0, SeekOrigin.Begin); result.Load(writer.BaseStream); writer.BaseStream.Close(); writer.BaseStream.Dispose(); writer.Close(); return result; } /// <summary> /// Convert A List of string data to Xml /// </summary> /// <param name="rootNode">Root Node Name</param> /// <param name="data">actual data </param> /// <param name="nodeNames">int -1, 0 -- -1=element node, 0 =position of the node in the data parameter) string=nodeName</param> /// <returns>An XmlDocument</returns> private static XmlDocument ConvertListToXml(string rootNode, List<string> data, Dictionary<int, string> nodeNames) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(string.Format("<{0}></{0}>", rootNode)); XmlElement root = xmlDoc.DocumentElement; IEnumerator<string> ie = data.GetEnumerator(); while (ie.MoveNext()) { string nodeValue = Convert.ToString(ie.Current); XmlNode node = CreateElementNode(xmlDoc, nodeNames[-1]); string nodeChildName = nodeNames[0]; AppendAttributeNode(xmlDoc, node, nodeChildName, nodeValue); root.AppendChild(node); } return xmlDoc; } private static Dictionary<int, string> CreateNamesDictionary(string elementName, string attributeName) { Dictionary<int, string> names = new Dictionary<int, string>(); names.Add(-1, elementName); names.Add(0, attributeName); return names; } } }
// 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.Contracts; using Microsoft.Cci.Extensions; using Microsoft.Cci.Extensions.CSharp; using Microsoft.Cci.Filters; using Microsoft.Cci.Writers.Syntax; namespace Microsoft.Cci.Writers.CSharp { public partial class CSDeclarationWriter : ICciDeclarationWriter { private readonly ISyntaxWriter _writer; private readonly ICciFilter _filter; private bool _forCompilation; private bool _forCompilationIncludeGlobalprefix; private string _platformNotSupportedExceptionMessage; private bool _includeFakeAttributes; private bool _alwaysIncludeBase; public CSDeclarationWriter(ISyntaxWriter writer) : this(writer, new PublicOnlyCciFilter()) { } public CSDeclarationWriter(ISyntaxWriter writer, ICciFilter filter) : this(writer, filter, true) { } public CSDeclarationWriter(ISyntaxWriter writer, ICciFilter filter, bool forCompilation) { Contract.Requires(writer != null); _writer = writer; _filter = filter; _forCompilation = forCompilation; _forCompilationIncludeGlobalprefix = false; _platformNotSupportedExceptionMessage = null; _includeFakeAttributes = false; _alwaysIncludeBase = false; } public CSDeclarationWriter(ISyntaxWriter writer, ICciFilter filter, bool forCompilation, bool includePseudoCustomAttributes = false) : this(writer, filter, forCompilation) { _includeFakeAttributes = includePseudoCustomAttributes; } public bool ForCompilation { get { return _forCompilation; } set { _forCompilation = value; } } public bool ForCompilationIncludeGlobalPrefix { get { return _forCompilationIncludeGlobalprefix; } set { _forCompilationIncludeGlobalprefix = value; } } public string PlatformNotSupportedExceptionMessage { get { return _platformNotSupportedExceptionMessage; } set { _platformNotSupportedExceptionMessage = value; } } public bool AlwaysIncludeBase { get { return _alwaysIncludeBase; } set { _alwaysIncludeBase = value; } } public ISyntaxWriter SyntaxtWriter { get { return _writer; } } public ICciFilter Filter { get { return _filter; } } public void WriteDeclaration(IDefinition definition) { if (definition == null) return; IAssembly assembly = definition as IAssembly; if (assembly != null) { WriteAssemblyDeclaration(assembly); return; } INamespaceDefinition ns = definition as INamespaceDefinition; if (ns != null) { WriteNamespaceDeclaration(ns); return; } ITypeDefinition type = definition as ITypeDefinition; if (type != null) { WriteTypeDeclaration(type); return; } ITypeDefinitionMember member = definition as ITypeDefinitionMember; if (member != null) { WriteMemberDeclaration(member); return; } DummyInternalConstructor ctor = definition as DummyInternalConstructor; if (ctor != null) { WritePrivateConstructor(ctor.ContainingType); return; } INamedEntity named = definition as INamedEntity; if (named != null) { WriteIdentifier(named.Name); return; } _writer.Write("Unknown definition type {0}", definition.ToString()); } public void WriteAttribute(ICustomAttribute attribute) { WriteSymbol("["); WriteAttribute(attribute, null); WriteSymbol("]"); } public void WriteAssemblyDeclaration(IAssembly assembly) { WriteAttributes(assembly.Attributes, prefix: "assembly"); WriteAttributes(assembly.SecurityAttributes, prefix: "assembly"); } public void WriteMemberDeclaration(ITypeDefinitionMember member) { IMethodDefinition method = member as IMethodDefinition; if (method != null) { WriteMethodDefinition(method); return; } IPropertyDefinition property = member as IPropertyDefinition; if (property != null) { WritePropertyDefinition(property); return; } IEventDefinition evnt = member as IEventDefinition; if (evnt != null) { WriteEventDefinition(evnt); return; } IFieldDefinition field = member as IFieldDefinition; if (field != null) { WriteFieldDefinition(field); return; } _writer.Write("Unknown member definitions type {0}", member.ToString()); } private void WriteVisibility(TypeMemberVisibility visibility) { switch (visibility) { case TypeMemberVisibility.Public: WriteKeyword("public"); break; case TypeMemberVisibility.Private: WriteKeyword("private"); break; case TypeMemberVisibility.Assembly: WriteKeyword("internal"); break; case TypeMemberVisibility.Family: WriteKeyword("protected"); break; case TypeMemberVisibility.FamilyOrAssembly: WriteKeyword("protected"); WriteKeyword("internal"); break; case TypeMemberVisibility.FamilyAndAssembly: WriteKeyword("internal"); WriteKeyword("protected"); break; // Is this right? default: WriteKeyword("<Unknown-Visibility>"); break; } } private void WriteCustomModifiers(IEnumerable<ICustomModifier> modifiers) { foreach (ICustomModifier modifier in modifiers) { if (modifier.Modifier.FullName() == "System.Runtime.CompilerServices.IsVolatile") WriteKeyword("volatile"); } } // Writer Helpers these are the only methods that should directly acess _writer private void WriteKeyword(string keyword, bool noSpace = false) { _writer.WriteKeyword(keyword); if (!noSpace) WriteSpace(); } private void WriteSymbol(string symbol, bool addSpace = false) { _writer.WriteSymbol(symbol); if (addSpace) WriteSpace(); } private void Write(string literal) { _writer.Write(literal); } private void WriteTypeName(ITypeReference type, bool noSpace = false, bool isDynamic = false, bool useTypeKeywords = true, bool omitGenericTypeList = false) { if (isDynamic) { WriteKeyword("dynamic", noSpace: noSpace); return; } NameFormattingOptions namingOptions = NameFormattingOptions.TypeParameters; if (useTypeKeywords) namingOptions |= NameFormattingOptions.UseTypeKeywords; if (_forCompilationIncludeGlobalprefix) namingOptions |= NameFormattingOptions.UseGlobalPrefix; if (!_forCompilation) namingOptions |= NameFormattingOptions.OmitContainingNamespace; if (omitGenericTypeList) namingOptions |= NameFormattingOptions.EmptyTypeParameterList; string name = TypeHelper.GetTypeName(type, namingOptions); if (CSharpCciExtensions.IsKeyword(name)) _writer.WriteKeyword(name); else _writer.WriteTypeName(name); if (!noSpace) WriteSpace(); } public void WriteIdentifier(string id) { WriteIdentifier(id, true); } public void WriteIdentifier(string id, bool escape) { // Escape keywords if (escape && CSharpCciExtensions.IsKeyword(id)) id = "@" + id; _writer.WriteIdentifier(id); } private void WriteIdentifier(IName name) { WriteIdentifier(name.Value); } private void WriteSpace() { _writer.Write(" "); } private void WriteList<T>(IEnumerable<T> list, Action<T> writeItem) { _writer.WriteList(list, writeItem); } } }
using Lucene.Net.Documents; using System; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using FixedBitSet = Lucene.Net.Util.FixedBitSet; using InPlaceMergeSorter = Lucene.Net.Util.InPlaceMergeSorter; using NumericDocValuesUpdate = Lucene.Net.Index.DocValuesUpdate.NumericDocValuesUpdate; using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s; using PagedGrowableWriter = Lucene.Net.Util.Packed.PagedGrowableWriter; using PagedMutable = Lucene.Net.Util.Packed.PagedMutable; /// <summary> /// A <see cref="DocValuesFieldUpdates"/> which holds updates of documents, of a single /// <see cref="NumericDocValuesField"/>. /// <para/> /// @lucene.experimental /// </summary> internal class NumericDocValuesFieldUpdates : DocValuesFieldUpdates { new internal sealed class Iterator : DocValuesFieldUpdates.Iterator { private readonly int size; private readonly PagedGrowableWriter values; private readonly FixedBitSet docsWithField; private readonly PagedMutable docs; private long idx = 0; // long so we don't overflow if size == Integer.MAX_VALUE private int doc = -1; private long? value = null; internal Iterator(int size, PagedGrowableWriter values, FixedBitSet docsWithField, PagedMutable docs) { this.size = size; this.values = values; this.docsWithField = docsWithField; this.docs = docs; } public override object Value => value; public override int NextDoc() { if (idx >= size) { value = null; return doc = DocIdSetIterator.NO_MORE_DOCS; } doc = (int)docs.Get(idx); ++idx; while (idx < size && docs.Get(idx) == doc) { ++idx; } if (!docsWithField.Get((int)(idx - 1))) { value = null; } else { // idx points to the "next" element value = values.Get(idx - 1); } return doc; } public override int Doc => doc; public override void Reset() { doc = -1; value = null; idx = 0; } } private FixedBitSet docsWithField; private PagedMutable docs; private PagedGrowableWriter values; private int size; public NumericDocValuesFieldUpdates(string field, int maxDoc) : base(field, DocValuesFieldUpdatesType.NUMERIC) { docsWithField = new FixedBitSet(64); docs = new PagedMutable(1, 1024, PackedInt32s.BitsRequired(maxDoc - 1), PackedInt32s.COMPACT); values = new PagedGrowableWriter(1, 1024, 1, PackedInt32s.FAST); size = 0; } public override void Add(int doc, object value) { // TODO: if the Sorter interface changes to take long indexes, we can remove that limitation if (size == int.MaxValue) { throw new InvalidOperationException("cannot support more than System.Int32.MaxValue doc/value entries"); } long? val = (long?)value; if (val == null) { val = NumericDocValuesUpdate.MISSING; } // grow the structures to have room for more elements if (docs.Count == size) { docs = docs.Grow(size + 1); values = values.Grow(size + 1); docsWithField = FixedBitSet.EnsureCapacity(docsWithField, (int)docs.Count); } if (val != NumericDocValuesUpdate.MISSING) { // only mark the document as having a value in that field if the value wasn't set to null (MISSING) docsWithField.Set(size); } docs.Set(size, doc); values.Set(size, (long)val); ++size; } public override DocValuesFieldUpdates.Iterator GetIterator() { PagedMutable docs = this.docs; PagedGrowableWriter values = this.values; FixedBitSet docsWithField = this.docsWithField; new InPlaceMergeSorterAnonymousInnerClassHelper(this, docs, values, docsWithField).Sort(0, size); return new Iterator(size, values, docsWithField, docs); } private class InPlaceMergeSorterAnonymousInnerClassHelper : InPlaceMergeSorter { private readonly NumericDocValuesFieldUpdates outerInstance; private PagedMutable docs; private PagedGrowableWriter values; private FixedBitSet docsWithField; public InPlaceMergeSorterAnonymousInnerClassHelper(NumericDocValuesFieldUpdates outerInstance, PagedMutable docs, PagedGrowableWriter values, FixedBitSet docsWithField) { this.outerInstance = outerInstance; this.docs = docs; this.values = values; this.docsWithField = docsWithField; } protected override void Swap(int i, int j) { long tmpDoc = docs.Get(j); docs.Set(j, docs.Get(i)); docs.Set(i, tmpDoc); long tmpVal = values.Get(j); values.Set(j, values.Get(i)); values.Set(i, tmpVal); bool tmpBool = docsWithField.Get(j); if (docsWithField.Get(i)) { docsWithField.Set(j); } else { docsWithField.Clear(j); } if (tmpBool) { docsWithField.Set(i); } else { docsWithField.Clear(i); } } protected override int Compare(int i, int j) { int x = (int)docs.Get(i); int y = (int)docs.Get(j); return (x < y) ? -1 : ((x == y) ? 0 : 1); } } [MethodImpl(MethodImplOptions.NoInlining)] public override void Merge(DocValuesFieldUpdates other) { Debug.Assert(other is NumericDocValuesFieldUpdates); NumericDocValuesFieldUpdates otherUpdates = (NumericDocValuesFieldUpdates)other; if (size + otherUpdates.size > int.MaxValue) { throw new InvalidOperationException("cannot support more than System.Int32.MaxValue doc/value entries; size=" + size + " other.size=" + otherUpdates.size); } docs = docs.Grow(size + otherUpdates.size); values = values.Grow(size + otherUpdates.size); docsWithField = FixedBitSet.EnsureCapacity(docsWithField, (int)docs.Count); for (int i = 0; i < otherUpdates.size; i++) { int doc = (int)otherUpdates.docs.Get(i); if (otherUpdates.docsWithField.Get(i)) { docsWithField.Set(size); } docs.Set(size, doc); values.Set(size, otherUpdates.values.Get(i)); ++size; } } public override bool Any() { return size > 0; } } }
using System; using System.IO; using System.Collections.Generic; using System.Reflection; using NLua; using Oxide.Core; using Oxide.Core.Plugins; using Oxide.Core.Plugins.Watchers; namespace Oxide.Ext.Lua.Plugins { /// <summary> /// Represents a Lua plugin /// </summary> public class LuaPlugin : Plugin { /// <summary> /// Gets the Lua environment /// </summary> private NLua.Lua LuaEnvironment { get; set; } /// <summary> /// Gets this plugin's Lua table /// </summary> private LuaTable Table { get; set; } /// <summary> /// Gets the object associated with this plugin /// </summary> public override object Object { get { return Table; } } // All functions in this plugin private IDictionary<string, LuaFunction> functions; // The plugin change watcher private FSWatcher watcher; /// <summary> /// Initializes a new instance of the LuaPlugin class /// </summary> /// <param name="filename"></param> internal LuaPlugin(string filename, NLua.Lua lua, FSWatcher watcher) { // Store filename Filename = filename; LuaEnvironment = lua; this.watcher = watcher; } #region Config /// <summary> /// Populates the config with default settings /// </summary> protected override void LoadDefaultConfig() { LuaEnvironment.NewTable("tmp"); LuaTable tmp = LuaEnvironment["tmp"] as LuaTable; Table["Config"] = tmp; LuaEnvironment["tmp"] = null; CallHook("LoadDefaultConfig", null); Utility.SetConfigFromTable(Config, tmp); } /// <summary> /// Loads the config file for this plugin /// </summary> protected override void LoadConfig() { base.LoadConfig(); if (Table != null) { Table["Config"] = Utility.TableFromConfig(Config, LuaEnvironment); } } /// <summary> /// Saves the config file for this plugin /// </summary> protected override void SaveConfig() { if (Config == null) return; if (Table == null) return; LuaTable configtable = Table["Config"] as LuaTable; if (configtable != null) { Utility.SetConfigFromTable(Config, configtable); } base.SaveConfig(); } #endregion /// <summary> /// Loads this plugin /// </summary> public void Load() { // Load the plugin into a table string source = File.ReadAllText(Filename); LuaFunction pluginfunc = LuaEnvironment.LoadString(source, Path.GetFileName(Filename)); if (pluginfunc == null) throw new Exception("LoadString returned null for some reason"); LuaEnvironment.NewTable("PLUGIN"); Table = LuaEnvironment["PLUGIN"] as LuaTable; Name = Path.GetFileNameWithoutExtension(Filename); Table["Name"] = Name; pluginfunc.Call(); // Read plugin attributes if (Table["Title"] == null || !(Table["Title"] is string)) throw new Exception("Plugin is missing title"); if (Table["Author"] == null || !(Table["Author"] is string)) throw new Exception("Plugin is missing author"); if (Table["Version"] == null || !(Table["Version"] is VersionNumber)) throw new Exception("Plugin is missing version"); Title = (string)Table["Title"]; Author = (string)Table["Author"]; Version = (VersionNumber)Table["Version"]; if (Table["Description"] is string) Description = (string)Table["Description"]; if (Table["ResourceId"] is int) ResourceId = (int)Table["ResourceId"]; if (Table["HasConfig"] is bool) HasConfig = (bool)Table["HasConfig"]; // Set attributes Table["Object"] = this; Table["Plugin"] = this; // Get all functions and hook them functions = new Dictionary<string, LuaFunction>(); foreach (var keyobj in Table.Keys) { string key = keyobj as string; if (key != null) { object value = Table[key]; LuaFunction func = value as LuaFunction; if (func != null) { functions.Add(key, func); } } } if (!HasConfig) HasConfig = functions.ContainsKey("LoadDefaultConfig"); // Bind any base methods (we do it here because we don't want them to be hooked) BindBaseMethods(); // Clean up LuaEnvironment["PLUGIN"] = null; } /// <summary> /// Binds base methods to the PLUGIN table /// </summary> private void BindBaseMethods() { BindBaseMethod("lua_SaveConfig", "SaveConfig"); } /// <summary> /// Binds the specified base method to the PLUGIN table /// </summary> /// <param name="methodname"></param> /// <param name="luaname"></param> private void BindBaseMethod(string methodname, string luaname) { MethodInfo method = GetType().GetMethod(methodname, BindingFlags.Static | BindingFlags.NonPublic); LuaEnvironment.RegisterFunction(string.Format("PLUGIN.{0}", luaname), method); } #region Base Methods /// <summary> /// Saves the config file for the specified plugin /// </summary> /// <param name="plugintable"></param> private static void lua_SaveConfig(LuaTable plugintable) { LuaPlugin plugin = plugintable["Object"] as LuaPlugin; if (plugin == null) return; plugin.SaveConfig(); } #endregion /// <summary> /// Called when this plugin has been added to the specified manager /// </summary> /// <param name="manager"></param> public override void HandleAddedToManager(PluginManager manager) { // Call base base.HandleAddedToManager(manager); // Subscribe all our hooks foreach (string key in functions.Keys) Subscribe(key); // Add us to the watcher watcher.AddMapping(Name); // Let the plugin know that it's loading CallFunction("Init", null); } /// <summary> /// Called when this plugin has been removed from the specified manager /// </summary> /// <param name="manager"></param> public override void HandleRemovedFromManager(PluginManager manager) { // Let plugin know that it's unloading CallFunction("Unload", null); // Remove us from the watcher watcher.RemoveMapping(Name); // Call base base.HandleRemovedFromManager(manager); } /// <summary> /// Called when it's time to call a hook /// </summary> /// <param name="hookname"></param> /// <param name="args"></param> /// <returns></returns> protected override object OnCallHook(string hookname, object[] args) { // Call it return CallFunction(hookname, args); } #region Lua CallFunction Hack // An empty object array private static readonly object[] emptyargs; // The method used to call a lua function private static MethodInfo LuaCallFunctionMethod; static LuaPlugin() { // Initialize emptyargs = new object[0]; // Load the method Type[] sig = new Type[] { typeof(object), typeof(object[]), typeof(Type[]) }; LuaCallFunctionMethod = typeof(NLua.Lua).GetMethod("CallFunction", BindingFlags.NonPublic | BindingFlags.Instance, null, sig, null); if (LuaCallFunctionMethod == null) throw new Exception("Lua CallFunction hack failed!"); } /// <summary> /// Calls a Lua function with the specified arguments /// </summary> /// <param name="func"></param> /// <param name="args"></param> /// <returns></returns> private object CallLuaFunction(LuaFunction func, object[] args) { object[] invokeargs = new object[3] { func, args, null }; try { object[] returnvalues = LuaCallFunctionMethod.Invoke(LuaEnvironment, invokeargs) as object[]; if (returnvalues == null || returnvalues.Length == 0) return null; else return returnvalues[0]; } catch (TargetInvocationException ex) { throw ex.InnerException; } } #endregion /// <summary> /// Calls a lua function by the given name and returns the output /// </summary> /// <param name="name"></param> /// <param name="args"></param> /// <returns></returns> private object CallFunction(string name, object[] args) { LuaFunction func; if (!functions.TryGetValue(name, out func)) return null; object[] realargs; if (args == null) { realargs = new object[] { Table }; } else { realargs = new object[args.Length + 1]; realargs[0] = Table; Array.Copy(args, 0, realargs, 1, args.Length); } return CallLuaFunction(func, realargs); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.CodeDom.Compiler; using System.Collections.Generic; using Microsoft.CSharp; using NUnit.Framework; using OpenSim.Region.ScriptEngine.Shared.CodeTools; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using OpenSim.Tests.Common; namespace OpenSim.Region.ScriptEngine.Shared.CodeTools.Tests { /// <summary> /// Tests the LSL compiler. Among other things, test that error messages /// generated by the C# compiler can be mapped to prper lines/columns in /// the LSL source. /// </summary> [TestFixture] public class CompilerTest : OpenSimTestCase { private string m_testDir; private CSharpCodeProvider m_CSCodeProvider; private CompilerParameters m_compilerParameters; private CompilerResults m_compilerResults; private ResolveEventHandler m_resolveEventHandler; /// <summary> /// Creates a temporary directory where build artifacts are stored. /// </summary> [TestFixtureSetUp] public void Init() { m_testDir = Path.Combine(Path.GetTempPath(), "opensim_compilerTest_" + Path.GetRandomFileName()); if (!Directory.Exists(m_testDir)) { // Create the temporary directory for housing build artifacts. Directory.CreateDirectory(m_testDir); } } [SetUp] public void SetUp() { // Create a CSCodeProvider and CompilerParameters. m_CSCodeProvider = new CSharpCodeProvider(); m_compilerParameters = new CompilerParameters(); string rootPath = System.AppDomain.CurrentDomain.BaseDirectory; m_resolveEventHandler = new ResolveEventHandler(AssemblyResolver.OnAssemblyResolve); System.AppDomain.CurrentDomain.AssemblyResolve += m_resolveEventHandler; m_compilerParameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.dll")); m_compilerParameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll")); m_compilerParameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenMetaverseTypes.dll")); m_compilerParameters.GenerateExecutable = false; } /// <summary> /// Removes the temporary build directory and any build artifacts /// inside it. /// </summary> [TearDown] public void CleanUp() { System.AppDomain.CurrentDomain.AssemblyResolve -= m_resolveEventHandler; if (Directory.Exists(m_testDir)) { // Blow away the temporary directory with artifacts. Directory.Delete(m_testDir, true); } } private CompilerResults CompileScript( string input, out Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> positionMap) { m_compilerParameters.OutputAssembly = Path.Combine(m_testDir, Path.GetRandomFileName() + ".dll"); CSCodeGenerator cg = new CSCodeGenerator(); string output = cg.Convert(input); output = Compiler.CreateCSCompilerScript(output, "script1", typeof(ScriptBaseClass).FullName, null); // System.Console.WriteLine(output); positionMap = cg.PositionMap; CompilerResults compilerResults = m_CSCodeProvider.CompileAssemblyFromSource(m_compilerParameters, output); // foreach (KeyValuePair<int, int> key in positionMap.Keys) // { // KeyValuePair<int, int> val = positionMap[key]; // // System.Console.WriteLine("{0},{1} => {2},{3}", key.Key, key.Value, val.Key, val.Value); // } // // foreach (CompilerError compErr in m_compilerResults.Errors) // { // System.Console.WriteLine("Error: {0},{1} => {2}", compErr.Line, compErr.Column, compErr); // } return compilerResults; } /// <summary> /// Test that line number errors are resolved as expected when preceding code contains a jump. /// </summary> [Test] public void TestJumpAndSyntaxError() { TestHelpers.InMethod(); Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> positionMap; CompilerResults compilerResults = CompileScript( @"default { state_entry() { jump l; @l; i = 1; } }", out positionMap); Assert.AreEqual( new KeyValuePair<int, int>(7, 9), positionMap[new KeyValuePair<int, int>(compilerResults.Errors[0].Line, compilerResults.Errors[0].Column)]); } /// <summary> /// Test the C# compiler error message can be mapped to the correct /// line/column in the LSL source when an undeclared variable is used. /// </summary> [Test] public void TestUseUndeclaredVariable() { TestHelpers.InMethod(); Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> positionMap; CompilerResults compilerResults = CompileScript( @"default { state_entry() { integer y = x + 3; } }", out positionMap); Assert.AreEqual( new KeyValuePair<int, int>(5, 21), positionMap[new KeyValuePair<int, int>(compilerResults.Errors[0].Line, compilerResults.Errors[0].Column)]); } /// <summary> /// Test that a string can be cast to string and another string /// concatenated. /// </summary> [Test] public void TestCastAndConcatString() { TestHelpers.InMethod(); Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> positionMap; CompilerResults compilerResults = CompileScript( @"string s = "" a string""; default { state_entry() { key gAvatarKey = llDetectedKey(0); string tmp = (string) gAvatarKey + s; llSay(0, tmp); } }", out positionMap); Assert.AreEqual(0, compilerResults.Errors.Count); } } }
// 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; using System.ServiceModel.Channels; using System.ServiceModel.Diagnostics; using System.ServiceModel.Dispatcher; using System.Threading; using System.Threading.Tasks; namespace System.ServiceModel { public sealed class InstanceContext : CommunicationObject, IExtensibleObject<InstanceContext> { private InstanceBehavior _behavior; private ConcurrencyInstanceContextFacet _concurrency; private ServiceChannelManager _channels; private ExtensionCollection<InstanceContext> _extensions; private object _serviceInstanceLock = new object(); private SynchronizationContext _synchronizationContext; private object _userObject; private bool _wellKnown; private SynchronizedCollection<IChannel> _wmiChannels; private bool _isUserCreated; public InstanceContext(object implementation) : this(implementation, true) { } internal InstanceContext(object implementation, bool isUserCreated) : this(implementation, true, isUserCreated) { } internal InstanceContext(object implementation, bool wellKnown, bool isUserCreated) { if (implementation != null) { _userObject = implementation; _wellKnown = wellKnown; } _channels = new ServiceChannelManager(this); _isUserCreated = isUserCreated; } internal InstanceBehavior Behavior { get { return _behavior; } set { if (_behavior == null) { _behavior = value; } } } internal ConcurrencyInstanceContextFacet Concurrency { get { if (_concurrency == null) { lock (ThisLock) { if (_concurrency == null) { _concurrency = new ConcurrencyInstanceContextFacet(); } } } return _concurrency; } } protected override TimeSpan DefaultCloseTimeout { get { return ServiceDefaults.CloseTimeout; } } protected override TimeSpan DefaultOpenTimeout { get { return ServiceDefaults.OpenTimeout; } } public IExtensionCollection<InstanceContext> Extensions { get { ThrowIfClosed(); lock (ThisLock) { if (_extensions == null) { _extensions = new ExtensionCollection<InstanceContext>(this, ThisLock); } return _extensions; } } } public ICollection<IChannel> IncomingChannels { get { ThrowIfClosed(); return _channels.IncomingChannels; } } public ICollection<IChannel> OutgoingChannels { get { ThrowIfClosed(); return _channels.OutgoingChannels; } } public SynchronizationContext SynchronizationContext { get { return _synchronizationContext; } set { ThrowIfClosedOrOpened(); _synchronizationContext = value; } } new internal object ThisLock { get { return base.ThisLock; } } internal object UserObject { get { return _userObject; } } internal ICollection<IChannel> WmiChannels { get { if (_wmiChannels == null) { lock (ThisLock) { if (_wmiChannels == null) { _wmiChannels = new SynchronizedCollection<IChannel>(); } } } return _wmiChannels; } } protected override void OnAbort() { _channels.Abort(); } internal void BindRpc(ref MessageRpc rpc) { ThrowIfClosed(); _channels.IncrementActivityCount(); rpc.SuccessfullyBoundInstance = true; } internal void FaultInternal() { Fault(); } public object GetServiceInstance(Message message) { lock (_serviceInstanceLock) { ThrowIfClosedOrNotOpen(); object current = _userObject; if (current != null) { return current; } if (_behavior == null) { Exception error = new InvalidOperationException(SR.SFxInstanceNotInitialized); if (message != null) { throw TraceUtility.ThrowHelperError(error, message); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error); } } object newUserObject; if (message != null) { newUserObject = _behavior.GetInstance(this, message); } else { newUserObject = _behavior.GetInstance(this); } if (newUserObject != null) { SetUserObject(newUserObject); } return newUserObject; } } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new CloseAsyncResult(timeout, callback, state, this); } protected override void OnEndClose(IAsyncResult result) { CloseAsyncResult.End(result); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new CompletedAsyncResult(callback, state); } protected override void OnEndOpen(IAsyncResult result) { CompletedAsyncResult.End(result); } protected override void OnClose(TimeSpan timeout) { _channels.Close(timeout); } protected override void OnOpen(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); } protected override void OnOpened() { base.OnOpened(); } protected override void OnOpening() { base.OnOpening(); } protected internal override Task OnCloseAsync(TimeSpan timeout) { OnClose(timeout); return TaskHelpers.CompletedTask(); } protected internal override Task OnOpenAsync(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); return TaskHelpers.CompletedTask(); } private void SetUserObject(object newUserObject) { if (_behavior != null && !_wellKnown) { object oldUserObject = Interlocked.Exchange(ref _userObject, newUserObject); } } internal void UnbindRpc(ref MessageRpc rpc) { if (rpc.InstanceContext == this && rpc.SuccessfullyBoundInstance) { _channels.DecrementActivityCount(); } } internal class CloseAsyncResult : AsyncResult { private InstanceContext _instanceContext; private TimeoutHelper _timeoutHelper; public CloseAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, InstanceContext instanceContext) : base(callback, state) { _timeoutHelper = new TimeoutHelper(timeout); _instanceContext = instanceContext; IAsyncResult result = _instanceContext._channels.BeginClose(_timeoutHelper.RemainingTime(), PrepareAsyncCompletion(new AsyncCompletion(CloseChannelsCallback)), this); if (result.CompletedSynchronously && CloseChannelsCallback(result)) { base.Complete(true); } } public static void End(IAsyncResult result) { AsyncResult.End<CloseAsyncResult>(result); } private bool CloseChannelsCallback(IAsyncResult result) { Fx.Assert(object.ReferenceEquals(this, result.AsyncState), "AsyncState should be this"); _instanceContext._channels.EndClose(result); return true; } } } }
using System.Diagnostics; namespace Community.CsharpSqlite { using u8 = System.Byte; public partial class Sqlite3 { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** An tokenizer for SQL ** ** This file contains C code that implements the sqlite3_complete() API. ** This code used to be part of the tokenizer.c source file. But by ** separating it out, the code will be automatically omitted from ** static links that do not use it. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#include "sqliteInt.h" #if !SQLITE_OMIT_COMPLETE /* ** This is defined in tokenize.c. We just have to import the definition. */ #if !SQLITE_AMALGAMATION #if SQLITE_ASCII //#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) static bool IdChar( u8 C ) { return ( sqlite3CtypeMap[(char)C] & 0x46 ) != 0; } #endif //#if SQLITE_EBCDIC //extern const char sqlite3IsEbcdicIdChar[]; //#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) //#endif #endif // * SQLITE_AMALGAMATION */ /* ** Token types used by the sqlite3_complete() routine. See the header ** comments on that procedure for additional information. */ const int tkSEMI = 0; const int tkWS = 1; const int tkOTHER = 2; #if !SQLITE_OMIT_TRIGGER const int tkEXPLAIN = 3; const int tkCREATE = 4; const int tkTEMP = 5; const int tkTRIGGER = 6; const int tkEND = 7; #endif /* ** Return TRUE if the given SQL string ends in a semicolon. ** ** Special handling is require for CREATE TRIGGER statements. ** Whenever the CREATE TRIGGER keywords are seen, the statement ** must end with ";END;". ** ** This implementation uses a state machine with 8 states: ** ** (0) INVALID We have not yet seen a non-whitespace character. ** ** (1) START At the beginning or end of an SQL statement. This routine ** returns 1 if it ends in the START state and 0 if it ends ** in any other state. ** ** (2) NORMAL We are in the middle of statement which ends with a single ** semicolon. ** ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of ** a statement. ** ** (4) CREATE The keyword CREATE has been seen at the beginning of a ** statement, possibly preceeded by EXPLAIN and/or followed by ** TEMP or TEMPORARY ** ** (5) TRIGGER We are in the middle of a trigger definition that must be ** ended by a semicolon, the keyword END, and another semicolon. ** ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at ** the end of a trigger definition. ** ** (7) END We've seen the ";END" of the ";END;" that occurs at the end ** of a trigger difinition. ** ** Transitions between states above are determined by tokens extracted ** from the input. The following tokens are significant: ** ** (0) tkSEMI A semicolon. ** (1) tkWS Whitespace. ** (2) tkOTHER Any other SQL token. ** (3) tkEXPLAIN The "explain" keyword. ** (4) tkCREATE The "create" keyword. ** (5) tkTEMP The "temp" or "temporary" keyword. ** (6) tkTRIGGER The "trigger" keyword. ** (7) tkEND The "end" keyword. ** ** Whitespace never causes a state transition and is always ignored. ** This means that a SQL string of all whitespace is invalid. ** ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed ** to recognize the end of a trigger can be omitted. All we have to do ** is look for a semicolon that is not part of an string or comment. */ static public int sqlite3_complete( string zSql ) { int state = 0; /* Current state, using numbers defined in header comment */ int token; /* Value of the next token */ #if !SQLITE_OMIT_TRIGGER /* A complex statement machine used to detect the end of a CREATE TRIGGER ** statement. This is the normal case. */ u8[][] trans = new u8[][] { /* Token: */ /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */ /* 0 INVALID: */ new u8[]{ 1, 0, 2, 3, 4, 2, 2, 2, }, /* 1 START: */ new u8[]{ 1, 1, 2, 3, 4, 2, 2, 2, }, /* 2 NORMAL: */ new u8[]{ 1, 2, 2, 2, 2, 2, 2, 2, }, /* 3 EXPLAIN: */ new u8[]{ 1, 3, 3, 2, 4, 2, 2, 2, }, /* 4 CREATE: */ new u8[]{ 1, 4, 2, 2, 2, 4, 5, 2, }, /* 5 TRIGGER: */ new u8[]{ 6, 5, 5, 5, 5, 5, 5, 5, }, /* 6 SEMI: */ new u8[]{ 6, 6, 5, 5, 5, 5, 5, 7, }, /* 7 END: */ new u8[]{ 1, 7, 5, 5, 5, 5, 5, 5, }, }; #else /* If triggers are not supported by this compile then the statement machine ** used to detect the end of a statement is much simplier */ u8[][] trans = new u8[][] { /* Token: */ /* State: ** SEMI WS OTHER */ /* 0 INVALID: */new u8[] { 1, 0, 2, }, /* 1 START: */new u8[] { 1, 1, 2, }, /* 2 NORMAL: */new u8[] { 1, 2, 2, }, }; #endif // * SQLITE_OMIT_TRIGGER */ int zIdx = 0; while ( zIdx < zSql.Length ) { switch ( zSql[zIdx] ) { case ';': { /* A semicolon */ token = tkSEMI; break; } case ' ': case '\r': case '\t': case '\n': case '\f': { /* White space is ignored */ token = tkWS; break; } case '/': { /* C-style comments */ if ( zSql[zIdx + 1] != '*' ) { token = tkOTHER; break; } zIdx += 2; while ( zIdx < zSql.Length && zSql[zIdx] != '*' || zIdx < zSql.Length - 1 && zSql[zIdx + 1] != '/' ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; zIdx++; token = tkWS; break; } case '-': { /* SQL-style comments from "--" to end of line */ if ( zSql[zIdx + 1] != '-' ) { token = tkOTHER; break; } while ( zIdx < zSql.Length && zSql[zIdx] != '\n' ) { zIdx++; } if ( zIdx == zSql.Length ) return state == 1 ? 1 : 0;//if( *zSql==0 ) return state==1; token = tkWS; break; } case '[': { /* Microsoft-style identifiers in [...] */ zIdx++; while ( zIdx < zSql.Length && zSql[zIdx] != ']' ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; token = tkOTHER; break; } case '`': /* Grave-accent quoted symbols used by MySQL */ case '"': /* single- and double-quoted strings */ case '\'': { int c = zSql[zIdx]; zIdx++; while ( zIdx < zSql.Length && zSql[zIdx] != c ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; token = tkOTHER; break; } default: { //#if SQLITE_EBCDIC // unsigned char c; //#endif if ( IdChar( (u8)zSql[zIdx] ) ) { /* Keywords and unquoted identifiers */ int nId; for ( nId = 1; ( zIdx + nId ) < zSql.Length && IdChar( (u8)zSql[zIdx + nId] ); nId++ ) { } #if SQLITE_OMIT_TRIGGER token = tkOTHER; #else switch ( zSql[zIdx] ) { case 'c': case 'C': { if ( nId == 6 && sqlite3StrNICmp( zSql, zIdx, "create", 6 ) == 0 ) { token = tkCREATE; } else { token = tkOTHER; } break; } case 't': case 'T': { if ( nId == 7 && sqlite3StrNICmp( zSql, zIdx, "trigger", 7 ) == 0 ) { token = tkTRIGGER; } else if ( nId == 4 && sqlite3StrNICmp( zSql, zIdx, "temp", 4 ) == 0 ) { token = tkTEMP; } else if ( nId == 9 && sqlite3StrNICmp( zSql, zIdx, "temporary", 9 ) == 0 ) { token = tkTEMP; } else { token = tkOTHER; } break; } case 'e': case 'E': { if ( nId == 3 && sqlite3StrNICmp( zSql, zIdx, "end", 3 ) == 0 ) { token = tkEND; } else #if ! SQLITE_OMIT_EXPLAIN if ( nId == 7 && sqlite3StrNICmp( zSql, zIdx, "explain", 7 ) == 0 ) { token = tkEXPLAIN; } else #endif { token = tkOTHER; } break; } default: { token = tkOTHER; break; } } #endif // * SQLITE_OMIT_TRIGGER */ zIdx += nId - 1; } else { /* Operators and special symbols */ token = tkOTHER; } break; } } state = trans[state][token]; zIdx++; } return ( state == 1 ) ? 1 : 0;//return state==1; } #if ! SQLITE_OMIT_UTF16 /* ** This routine is the same as the sqlite3_complete() routine described ** above, except that the parameter is required to be UTF-16 encoded, not ** UTF-8. */ int sqlite3_complete16(const void *zSql){ sqlite3_value pVal; char const *zSql8; int rc = SQLITE_NOMEM; #if !SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if( rc !=0) return rc; #endif pVal = sqlite3ValueNew(0); sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); if( zSql8 ){ rc = sqlite3_complete(zSql8); }else{ rc = SQLITE_NOMEM; } sqlite3ValueFree(pVal); return sqlite3ApiExit(0, rc); } #endif // * SQLITE_OMIT_UTF16 */ #endif // * SQLITE_OMIT_COMPLETE */ } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Azure.Core.Pipeline; using Azure.Identity; using NUnit.Framework; using System; using System.Threading; using System.Threading.Tasks; using System.Net.Http; namespace Azure.Security.KeyVault.Secrets.Samples { /// <summary> /// Samples that are used in the associated README.md file. /// </summary> public partial class Snippets { #pragma warning disable IDE1006 // Naming Styles private SecretClient client; #pragma warning restore IDE1006 // Naming Styles [OneTimeSetUp] public void CreateClient() { // Environment variable with the Key Vault endpoint. string vaultUrl = TestEnvironment.KeyVaultUrl; #region Snippet:CreateSecretClient // Create a new secret client using the default credential from Azure.Identity using environment variables previously set, // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID. var client = new SecretClient(vaultUri: new Uri(vaultUrl), credential: new DefaultAzureCredential()); // Create a new secret using the secret client. KeyVaultSecret secret = client.SetSecret("secret-name", "secret-value"); // Retrieve a secret using the secret client. secret = client.GetSecret("secret-name"); #endregion this.client = client; } [Test] public void CreateSecret() { #region Snippet:CreateSecret KeyVaultSecret secret = client.SetSecret("secret-name", "secret-value"); Console.WriteLine(secret.Name); Console.WriteLine(secret.Value); Console.WriteLine(secret.Properties.Version); Console.WriteLine(secret.Properties.Enabled); #endregion } [Test] public async Task CreateSecretAsync() { #region Snippet:CreateSecretAsync KeyVaultSecret secret = await client.SetSecretAsync("secret-name", "secret-value"); Console.WriteLine(secret.Name); Console.WriteLine(secret.Value); #endregion } [Test] public void RetrieveSecret() { // Make sure a secret exists. This will create a new version if "secret-name" already exists. client.SetSecret("secret-name", "secret-value"); #region Snippet:RetrieveSecret KeyVaultSecret secret = client.GetSecret("secret-name"); Console.WriteLine(secret.Name); Console.WriteLine(secret.Value); #endregion } [Test] public void UpdateSecret() { // Make sure a secret exists. This will create a new version if "secret-name" already exists. client.SetSecret("secret-name", "secret-value"); #region Snippet:UpdateSecret KeyVaultSecret secret = client.GetSecret("secret-name"); // Clients may specify the content type of a secret to assist in interpreting the secret data when its retrieved. secret.Properties.ContentType = "text/plain"; // You can specify additional application-specific metadata in the form of tags. secret.Properties.Tags["foo"] = "updated tag"; SecretProperties updatedSecretProperties = client.UpdateSecretProperties(secret.Properties); Console.WriteLine(updatedSecretProperties.Name); Console.WriteLine(updatedSecretProperties.Version); Console.WriteLine(updatedSecretProperties.ContentType); #endregion } [Test] public void ListSecrets() { #region Snippet:ListSecrets Pageable<SecretProperties> allSecrets = client.GetPropertiesOfSecrets(); foreach (SecretProperties secretProperties in allSecrets) { Console.WriteLine(secretProperties.Name); } #endregion } [Test] public async Task ListSecretsAsync() { #region Snippet:ListSecretsAsync AsyncPageable<SecretProperties> allSecrets = client.GetPropertiesOfSecretsAsync(); await foreach (SecretProperties secretProperties in allSecrets) { Console.WriteLine(secretProperties.Name); } #endregion } [Test] public void NotFound() { #region Snippet:SecretNotFound try { KeyVaultSecret secret = client.GetSecret("some_secret"); } catch (RequestFailedException ex) { Console.WriteLine(ex.ToString()); } #endregion } [Ignore("The secret is deleted and purged on tear down of this text fixture.")] public void DeleteSecret() { #region Snippet:DeleteSecret DeleteSecretOperation operation = client.StartDeleteSecret("secret-name"); DeletedSecret secret = operation.Value; Console.WriteLine(secret.Name); Console.WriteLine(secret.Value); #endregion } [OneTimeTearDown] public async Task DeleteAndPurgeSecretAsync() { #region Snippet:DeleteAndPurgeSecretAsync DeleteSecretOperation operation = await client.StartDeleteSecretAsync("secret-name"); // You only need to wait for completion if you want to purge or recover the secret. await operation.WaitForCompletionAsync(); DeletedSecret secret = operation.Value; await client.PurgeDeletedSecretAsync(secret.Name); #endregion } [Ignore("The secret is deleted and purged on tear down of this text fixture.")] public void DeleteAndPurgeSecret() { #region Snippet:DeleteAndPurgeSecret DeleteSecretOperation operation = client.StartDeleteSecret("secret-name"); // You only need to wait for completion if you want to purge or recover the secret. // You should call `UpdateStatus` in another thread or after doing additional work like pumping messages. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } DeletedSecret secret = operation.Value; client.PurgeDeletedSecret(secret.Name); #endregion } [Ignore("Used only for the migration guide")] private async Task MigrationGuide() { #region Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_Create SecretClient client = new SecretClient( new Uri("https://myvault.vault.azure.net"), new DefaultAzureCredential()); #endregion Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_Create #region Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_CreateWithOptions using (HttpClient httpClient = new HttpClient()) { SecretClientOptions options = new SecretClientOptions { Transport = new HttpClientTransport(httpClient) }; #if SNIPPET SecretClient client = new SecretClient( #else SecretClient _ = new SecretClient( #endif new Uri("https://myvault.vault.azure.net"), new DefaultAzureCredential(), options); } #endregion Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_CreateWithOptions { #region Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_SetSecret KeyVaultSecret secret = await client.SetSecretAsync("secret-name", "secret-value"); #endregion Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_SetSecret } { #region Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_GetSecret // Get the latest secret value. KeyVaultSecret secret = await client.GetSecretAsync("secret-name"); // Get a specific secret value. KeyVaultSecret secretVersion = await client.GetSecretAsync("secret-name", "e43af03a7cbc47d4a4e9f11540186048"); #endregion Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_GetSecret } { #region Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_ListSecrets // List all secrets asynchronously. await foreach (SecretProperties item in client.GetPropertiesOfSecretsAsync()) { KeyVaultSecret secret = await client.GetSecretAsync(item.Name); } // List all secrets synchronously. foreach (SecretProperties item in client.GetPropertiesOfSecrets()) { KeyVaultSecret secret = client.GetSecret(item.Name); } #endregion Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_ListSecrets } { #region Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_DeleteSecret // Delete the secret. DeleteSecretOperation deleteOperation = await client.StartDeleteSecretAsync("secret-name"); // Purge or recover the deleted secret if soft delete is enabled. if (deleteOperation.Value.RecoveryId != null) { // Deleting a secret does not happen immediately. Wait for the secret to be deleted. DeletedSecret deletedSecret = await deleteOperation.WaitForCompletionAsync(); // Purge the deleted secret. await client.PurgeDeletedSecretAsync(deletedSecret.Name); // You can also recover the deleted secret using StartRecoverDeletedSecretAsync, // which returns RecoverDeletedSecretOperation you can await like DeleteSecretOperation above. } #endregion Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_DeleteSecret } } } }
using System.Collections.Generic; using System.Text.Encodings.Web; using System.Text.Json; using GraphQL.SystemTextJson; using Shouldly; using Xunit; namespace GraphQL.Tests.Serialization.SystemTextJson { public class InputsConverterTests { private readonly JsonSerializerOptions _options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true, Converters = { new InputsConverter(), new JsonConverterBigInteger(), } }; private readonly JsonSerializerOptions _optionsWriter = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true, Converters = { new JsonConverterBigInteger(), } }; [Fact] public void Deserialize_And_Serialize_Introspection() { string json = "IntrospectionResult".ReadJsonResult(); var data = JsonSerializer.Deserialize<Inputs>(json, _options); string roundtrip = JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); roundtrip.ShouldBeCrossPlatJson(json); } [Fact] public void Deserialize_SimpleValues() { string json = @" { ""int"": 123, ""double"": 123.456, ""string"": ""string"", ""bool"": true } "; var actual = JsonSerializer.Deserialize<Inputs>(json, _options); actual["int"].ShouldBe(123); actual["double"].ShouldBe(123.456); actual["string"].ShouldBe("string"); actual["bool"].ShouldBe(true); } [Fact] public void Deserialize_Simple_Null() { string json = @" { ""string"": null } "; var actual = JsonSerializer.Deserialize<Inputs>(json, _options); actual["string"].ShouldBeNull(); } [Fact] public void Deserialize_Array() { string json = @" { ""values"": [1, 2, 3] } "; var actual = JsonSerializer.Deserialize<Inputs>(json, _options); actual["values"].ShouldNotBeNull(); } [Fact] public void Deserialize_Array_in_Array() { string json = @" { ""values"": [[1,2,3]] } "; var actual = JsonSerializer.Deserialize<Inputs>(json, _options); actual["values"].ShouldNotBeNull(); object values = actual["values"]; values.ShouldBeAssignableTo<IEnumerable<object>>(); } [Fact] public void Deserialize_ComplexValue() { string json = @" { ""complex"": { ""int"": 123, ""double"": 123.456, ""string"": ""string"", ""bool"": true } } "; var actual = JsonSerializer.Deserialize<Inputs>(json, _options); var complex = actual["complex"].ShouldBeAssignableTo<IDictionary<string, object>>(); complex["int"].ShouldBe(123); complex["double"].ShouldBe(123.456); complex["string"].ShouldBe("string"); complex["bool"].ShouldBe(true); } [Fact] public void Deserialize_MixedValue() { string json = @" { ""int"": 123, ""complex"": { ""int"": 123, ""double"": 123.456, ""string"": ""string"", ""bool"": true }, ""bool"": true } "; var actual = JsonSerializer.Deserialize<Inputs>(json, _options); actual["int"].ShouldBe(123); actual["bool"].ShouldBe(true); var complex = actual["complex"].ShouldBeAssignableTo<IDictionary<string, object>>(); complex["int"].ShouldBe(123); complex["double"].ShouldBe(123.456); complex["string"].ShouldBe("string"); complex["bool"].ShouldBe(true); } [Fact] public void Deserialize_Nested_SimpleValues() { string json = @" { ""value1"": ""string"", ""dictionary"": { ""int"": 123, ""double"": 123.456, ""string"": ""string"", ""bool"": true }, ""value2"": 123 } "; var actual = JsonSerializer.Deserialize<Nested>(json, _options); actual.Value1.ShouldBe("string"); actual.Value2.ShouldBe(123); } [Fact] public void Serialize_SimpleValues() { var source = new Nested { Value2 = 123, Value1 = null }; string json = JsonSerializer.Serialize(source, _options); json.ShouldBeCrossPlatJson( @"{ ""value1"": null, ""dictionary"": null, ""value2"": 123 }".Trim()); } [Fact] public void Serialize_Nested_SimpleValues() { var source = new Nested { Dictionary = new Dictionary<string, object> { ["int"] = 123, ["string"] = "string" }.ToInputs(), Value2 = 123, Value1 = "string" }; string json = JsonSerializer.Serialize(source, _options); json.ShouldBeCrossPlatJson( @"{ ""value1"": ""string"", ""dictionary"": { ""int"": 123, ""string"": ""string"" }, ""value2"": 123 }".Trim()); } [Fact] public void Serialize_Nested_Simple_Null() { var source = new Nested { Dictionary = new Dictionary<string, object> { ["string"] = null }.ToInputs(), Value2 = 123, Value1 = "string" }; string json = JsonSerializer.Serialize(source, _options); json.ShouldBeCrossPlatJson( @"{ ""value1"": ""string"", ""dictionary"": { ""string"": null }, ""value2"": 123 }".Trim()); } [Fact] public void Serialize_Nested_ComplexValues() { var source = new Nested { Dictionary = new Dictionary<string, object> { ["int"] = 123, ["string"] = "string", ["complex"] = new Dictionary<string, object> { ["double"] = 1.123d } }.ToInputs(), Value2 = 123, Value1 = "string" }; string json = JsonSerializer.Serialize(source, _options); json.ShouldBeCrossPlatJson( @"{ ""value1"": ""string"", ""dictionary"": { ""int"": 123, ""string"": ""string"", ""complex"": { ""double"": 1.123 } }, ""value2"": 123 }".Trim()); } private class Nested { public string Value1 { get; set; } public Inputs Dictionary { get; set; } public int Value2 { get; set; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace System.Net.Sockets { public partial class SafeSocketHandle { private ThreadPoolBoundHandle _iocpBoundHandle; private bool _skipCompletionPortOnSuccess; private readonly object _iocpBindingLock = new object(); internal void SetExposed() { /* nop */ } internal ThreadPoolBoundHandle IOCPBoundHandle { get { return _iocpBoundHandle; } } internal ThreadPoolBoundHandle GetThreadPoolBoundHandle() => !_released ? _iocpBoundHandle : null; // Binds the Socket Win32 Handle to the ThreadPool's CompletionPort. internal ThreadPoolBoundHandle GetOrAllocateThreadPoolBoundHandle(bool trySkipCompletionPortOnSuccess) { if (_released) { ThrowSocketDisposedException(); } if (_iocpBoundHandle != null) { return _iocpBoundHandle; } lock (_iocpBindingLock) { ThreadPoolBoundHandle boundHandle = _iocpBoundHandle; if (boundHandle == null) { // Bind the socket native _handle to the ThreadPool. if (NetEventSource.IsEnabled) NetEventSource.Info(this, "calling ThreadPool.BindHandle()"); try { // The handle (this) may have been already released: // E.g.: The socket has been disposed in the main thread. A completion callback may // attempt starting another operation. boundHandle = ThreadPoolBoundHandle.BindHandle(this); } catch (Exception exception) when (!ExceptionCheck.IsFatal(exception)) { bool closed = IsClosed; CloseAsIs(abortive: false); if (closed) { // If the handle was closed just before the call to BindHandle, // we could end up getting an ArgumentException, which we should // instead propagate as an ObjectDisposedException. ThrowSocketDisposedException(exception); } throw; } // Try to disable completions for synchronous success, if requested if (trySkipCompletionPortOnSuccess && CompletionPortHelper.SkipCompletionPortOnSuccess(boundHandle.Handle)) { _skipCompletionPortOnSuccess = true; } // Don't set this until after we've configured the handle above (if we did) Volatile.Write(ref _iocpBoundHandle, boundHandle); } return boundHandle; } } internal bool SkipCompletionPortOnSuccess { get { Debug.Assert(_iocpBoundHandle != null); return _skipCompletionPortOnSuccess; } } internal static SafeSocketHandle CreateWSASocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { return CreateSocket(InnerSafeCloseSocket.CreateWSASocket(addressFamily, socketType, protocolType)); } internal static SafeSocketHandle Accept( SafeSocketHandle socketHandle, byte[] socketAddress, ref int socketAddressSize) { return CreateSocket(InnerSafeCloseSocket.Accept(socketHandle, socketAddress, ref socketAddressSize)); } private bool DoReleaseHandle() { // Keep m_IocpBoundHandle around after disposing it to allow freeing NativeOverlapped. // ThreadPoolBoundHandle allows FreeNativeOverlapped even after it has been disposed. if (_iocpBoundHandle != null) { _iocpBoundHandle.Dispose(); } // On Unix, we use the return value of DoReleaseHandle to cause an abortive close. // On Windows, this is handled in TryUnblockSocket. return false; } private static void ThrowSocketDisposedException(Exception innerException = null) => throw new ObjectDisposedException(typeof(Socket).FullName, innerException); internal sealed partial class InnerSafeCloseSocket : SafeHandleMinusOneIsInvalid { private SocketError InnerReleaseHandle() { SocketError errorCode; // If _abortive was set to false in Close, it's safe to block here, which means // we can honor the linger options set on the socket. It also means closesocket() might return WSAEWOULDBLOCK, in which // case we need to do some recovery. if (!_abortive) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, Following 'blockable' branch"); errorCode = Interop.Winsock.closesocket(handle); #if DEBUG _closeSocketHandle = handle; _closeSocketResult = errorCode; #endif if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, closesocket()#1:{errorCode}"); // If it's not WSAEWOULDBLOCK, there's no more recourse - we either succeeded or failed. if (errorCode != SocketError.WouldBlock) { return errorCode; } // The socket must be non-blocking with a linger timeout set. // We have to set the socket to blocking. int nonBlockCmd = 0; errorCode = Interop.Winsock.ioctlsocket( handle, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref nonBlockCmd); if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, ioctlsocket()#1:{errorCode}"); // If that succeeded, try again. if (errorCode == SocketError.Success) { errorCode = Interop.Winsock.closesocket(handle); #if DEBUG _closeSocketHandle = handle; _closeSocketResult = errorCode; #endif if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, closesocket#2():{errorCode}"); // If it's not WSAEWOULDBLOCK, there's no more recourse - we either succeeded or failed. if (errorCode != SocketError.WouldBlock) { return errorCode; } } // It failed. Fall through to the regular abortive close. } // By default or if non abortive path failed, set linger timeout to zero to get an abortive close (RST). Interop.Winsock.Linger lingerStruct; lingerStruct.OnOff = 1; lingerStruct.Time = 0; errorCode = Interop.Winsock.setsockopt( handle, SocketOptionLevel.Socket, SocketOptionName.Linger, ref lingerStruct, 4); #if DEBUG _closeSocketLinger = errorCode; #endif if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, setsockopt():{errorCode}"); if (errorCode != SocketError.Success && errorCode != SocketError.InvalidArgument && errorCode != SocketError.ProtocolOption) { // Too dangerous to try closesocket() - it might block! return errorCode; } errorCode = Interop.Winsock.closesocket(handle); #if DEBUG _closeSocketHandle = handle; _closeSocketResult = errorCode; #endif if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, closesocket#3():{(errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode)}"); return errorCode; } internal static InnerSafeCloseSocket CreateWSASocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { InnerSafeCloseSocket result = Interop.Winsock.WSASocketW(addressFamily, socketType, protocolType, IntPtr.Zero, 0, Interop.Winsock.SocketConstructorFlags.WSA_FLAG_OVERLAPPED | Interop.Winsock.SocketConstructorFlags.WSA_FLAG_NO_HANDLE_INHERIT); if (result.IsInvalid) { result.SetHandleAsInvalid(); } return result; } internal static InnerSafeCloseSocket Accept(SafeSocketHandle socketHandle, byte[] socketAddress, ref int socketAddressSize) { InnerSafeCloseSocket result = Interop.Winsock.accept(socketHandle, socketAddress, ref socketAddressSize); if (result.IsInvalid) { result.SetHandleAsInvalid(); } return result; } /// <returns>Returns whether operations were canceled.</returns> internal unsafe bool TryUnblockSocket(bool abortive, bool hasShutdownSend) { // Try to cancel all pending IO. return Interop.Kernel32.CancelIoEx(this, 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 0.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyDictionary { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Dictionary operations. /// </summary> public partial interface IDictionary { /// <summary> /// Get null dictionary value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get empty dictionary value {} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutEmptyWithHttpMessagesAsync(IDictionary<string, string> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get Dictionary with null value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetNullValueWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get Dictionary with null key /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetNullKeyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get Dictionary with key as empty string /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetEmptyStringKeyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get invalid Dictionary value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": true, "1": false, "2": false, /// "3": true } /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, bool?>>> GetBooleanTfftWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {"0": true, "1": false, "2": false, /// "3": true } /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBooleanTfftWithHttpMessagesAsync(IDictionary<string, bool?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": true, "1": null, "2": false } /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, bool?>>> GetBooleanInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value '{"0": true, "1": "boolean", "2": /// false}' /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, bool?>>> GetBooleanInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetIntegerValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutIntegerValidWithHttpMessagesAsync(IDictionary<string, int?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": null, "2": 0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetIntInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": "integer", "2": 0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetIntInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, long?>>> GetLongValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutLongValidWithHttpMessagesAsync(IDictionary<string, long?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get long dictionary value {"0": 1, "1": null, "2": 0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, long?>>> GetLongInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get long dictionary value {"0": 1, "1": "integer", "2": 0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, long?>>> GetLongInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetFloatValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutFloatValidWithHttpMessagesAsync(IDictionary<string, double?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0.0, "1": null, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetFloatInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": 1.0, "1": "number", "2": 0.0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetFloatInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetDoubleValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDoubleValidWithHttpMessagesAsync(IDictionary<string, double?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0.0, "1": null, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetDoubleInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": 1.0, "1": "number", "2": 0.0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetDoubleInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetStringValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutStringValidWithHttpMessagesAsync(IDictionary<string, string> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string dictionary value {"0": "foo", "1": null, "2": "foo2"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetStringWithNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string dictionary value {"0": "foo", "1": 123, "2": "foo2"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetStringWithInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": "2000-12-01", "1": /// "1980-01-02", "2": "1492-10-12"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": "2000-12-01", "1": "1980-01-02", "2": /// "1492-10-12"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDateValidWithHttpMessagesAsync(IDictionary<string, DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2012-01-01", "1": null, "2": /// "1776-07-04"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2011-03-22", "1": "date"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateInvalidCharsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date-time dictionary value {"0": "2000-12-01t00:00:01z", "1": /// "1980-01-02T00:11:35+01:00", "2": "1492-10-12T10:15:01-08:00"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateTimeValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": "2000-12-01t00:00:01z", "1": /// "1980-01-02T00:11:35+01:00", "2": "1492-10-12T10:15:01-08:00"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDateTimeValidWithHttpMessagesAsync(IDictionary<string, DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2000-12-01t00:00:01z", "1": null} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateTimeInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2000-12-01t00:00:01z", "1": /// "date-time"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateTimeInvalidCharsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get byte dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 /// 03), "2": hex (25, 29, 43)} with each item encoded in base64 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, byte[]>>> GetByteValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put the dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 /// 03), "2": hex (25, 29, 43)} with each elementencoded in base 64 /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutByteValidWithHttpMessagesAsync(IDictionary<string, byte[]> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get byte dictionary value {"0": hex(FF FF FF FA), "1": null} with /// the first item base64 encoded /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, byte[]>>> GetByteInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type null value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get empty dictionary of complex type {} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type with null item {"0": {"integer": 1, /// "string": "2"}, "1": null, "2": {"integer": 5, "string": "6"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type with empty item {"0": {"integer": /// 1, "string": "2"}, "1:" {}, "2": {"integer": 5, "string": "6"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type with {"0": {"integer": 1, "string": /// "2"}, "1": {"integer": 3, "string": "4"}, "2": {"integer": 5, /// "string": "6"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put an dictionary of complex type with values {"0": {"integer": 1, /// "string": "2"}, "1": {"integer": 3, "string": "4"}, "2": /// {"integer": 5, "string": "6"}} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutComplexValidWithHttpMessagesAsync(IDictionary<string, Widget> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get a null array /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an empty dictionary {} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionary of array of strings {"0": ["1", "2", "3"], "1": /// null, "2": ["7", "8", "9"]} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of array of strings [{"0": ["1", "2", "3"], "1": [], /// "2": ["7", "8", "9"]} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of array of strings {"0": ["1", "2", "3"], "1": ["4", /// "5", "6"], "2": ["7", "8", "9"]} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put An array of array of strings {"0": ["1", "2", "3"], "1": ["4", /// "5", "6"], "2": ["7", "8", "9"]} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutArrayValidWithHttpMessagesAsync(IDictionary<string, IList<string>> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries with value null /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": /// null, "2": {"7": "seven", "8": "eight", "9": "nine"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": {}, /// "2": {"7": "seven", "8": "eight", "9": "nine"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": /// {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven", "8": /// "eight", "9": "nine"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": /// {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven", "8": /// "eight", "9": "nine"}} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDictionaryValidWithHttpMessagesAsync(IDictionary<string, IDictionary<string, string>> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/* * 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 Net.Pkcs11Interop.Common; namespace Net.Pkcs11Interop.HighLevelAPI.MechanismParams { /// <summary> /// Resulting key handles and initialization vectors after performing a DeriveKey method with the CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE or with the CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE mechanism /// </summary> public class CkWtlsKeyMatOut : IDisposable { /// <summary> /// Flag indicating whether instance has been disposed /// </summary> private bool _disposed = false; /// <summary> /// Platform specific CkWtlsKeyMatOut /// </summary> private HighLevelAPI40.MechanismParams.CkWtlsKeyMatOut _params40 = null; /// <summary> /// Platform specific CkWtlsKeyMatOut /// </summary> private HighLevelAPI41.MechanismParams.CkWtlsKeyMatOut _params41 = null; /// <summary> /// Platform specific CkWtlsKeyMatOut /// </summary> private HighLevelAPI80.MechanismParams.CkWtlsKeyMatOut _params80 = null; /// <summary> /// Platform specific CkWtlsKeyMatOut /// </summary> private HighLevelAPI81.MechanismParams.CkWtlsKeyMatOut _params81 = null; /// <summary> /// Key handle for the resulting MAC secret key /// </summary> public ObjectHandle MacSecret { get { if (this._disposed) throw new ObjectDisposedException(this.GetType().FullName); if (Platform.UnmanagedLongSize == 4) return (Platform.StructPackingSize == 0) ? new ObjectHandle(_params40.MacSecret) : new ObjectHandle(_params41.MacSecret); else return (Platform.StructPackingSize == 0) ? new ObjectHandle(_params80.MacSecret) : new ObjectHandle(_params81.MacSecret); } } /// <summary> /// Key handle for the resulting Secret key /// </summary> public ObjectHandle Key { get { if (this._disposed) throw new ObjectDisposedException(this.GetType().FullName); if (Platform.UnmanagedLongSize == 4) return (Platform.StructPackingSize == 0) ? new ObjectHandle(_params40.Key) : new ObjectHandle(_params41.Key); else return (Platform.StructPackingSize == 0) ? new ObjectHandle(_params80.Key) : new ObjectHandle(_params81.Key); } } /// <summary> /// Initialization vector (IV) /// </summary> public byte[] IV { get { if (this._disposed) throw new ObjectDisposedException(this.GetType().FullName); if (Platform.UnmanagedLongSize == 4) return (Platform.StructPackingSize == 0) ? _params40.IV : _params41.IV; else return (Platform.StructPackingSize == 0) ? _params80.IV : _params81.IV; } } /// <summary> /// Initializes a new instance of the CkWtlsKeyMatOut class. /// </summary> /// <param name='ckWtlsKeyMatOut'>Platform specific CkWtlsKeyMatOut</param> internal CkWtlsKeyMatOut(HighLevelAPI40.MechanismParams.CkWtlsKeyMatOut ckWtlsKeyMatOut) { if (ckWtlsKeyMatOut == null) throw new ArgumentNullException("ckWtlsKeyMatOut"); _params40 = ckWtlsKeyMatOut; } /// <summary> /// Initializes a new instance of the CkWtlsKeyMatOut class. /// </summary> /// <param name='ckWtlsKeyMatOut'>Platform specific CkWtlsKeyMatOut</param> internal CkWtlsKeyMatOut(HighLevelAPI41.MechanismParams.CkWtlsKeyMatOut ckWtlsKeyMatOut) { if (ckWtlsKeyMatOut == null) throw new ArgumentNullException("ckWtlsKeyMatOut"); _params41 = ckWtlsKeyMatOut; } /// <summary> /// Initializes a new instance of the CkWtlsKeyMatOut class. /// </summary> /// <param name='ckWtlsKeyMatOut'>Platform specific CkWtlsKeyMatOut</param> internal CkWtlsKeyMatOut(HighLevelAPI80.MechanismParams.CkWtlsKeyMatOut ckWtlsKeyMatOut) { if (ckWtlsKeyMatOut == null) throw new ArgumentNullException("ckWtlsKeyMatOut"); _params80 = ckWtlsKeyMatOut; } /// <summary> /// Initializes a new instance of the CkWtlsKeyMatOut class. /// </summary> /// <param name='ckWtlsKeyMatOut'>Platform specific CkWtlsKeyMatOut</param> internal CkWtlsKeyMatOut(HighLevelAPI81.MechanismParams.CkWtlsKeyMatOut ckWtlsKeyMatOut) { if (ckWtlsKeyMatOut == null) throw new ArgumentNullException("ckWtlsKeyMatOut"); _params81 = ckWtlsKeyMatOut; } #region IDisposable /// <summary> /// Disposes object /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Disposes object /// </summary> /// <param name="disposing">Flag indicating whether managed resources should be disposed</param> protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { // Dispose managed objects if (_params40 != null) { _params40.Dispose(); _params40 = null; } if (_params41 != null) { _params41.Dispose(); _params41 = null; } if (_params80 != null) { _params80.Dispose(); _params80 = null; } if (_params81 != null) { _params81.Dispose(); _params81 = null; } } // Dispose unmanaged objects _disposed = true; } } /// <summary> /// Class destructor that disposes object if caller forgot to do so /// </summary> ~CkWtlsKeyMatOut() { Dispose(false); } #endregion } }
using System; using Skewworks.NETMF; using Skewworks.NETMF.Controls; using Skewworks.NETMF.Resources; namespace TestSandbox.CommonControls { public class LabelsForm { public static LabelsForm Instance { get; private set; } public static void Show() { if (Instance == null) { Instance = new LabelsForm(); } Instance.DoShow(); } private readonly Form _form; private void DoShow() { Core.ActiveContainer = _form; } private LabelsForm() { _form = new Form("LabelsForm"); _form.AddMenuStrip( MenuHelper.CreateMenuItem("Nav", MenuHelper.CreateMenuItem("Home", (sender, point) => Program.ShowMainForm())), MenuHelper.CreateMenuItem("Test", MenuHelper.CreateMenuItem("Fonts", TestFonts), MenuHelper.CreateMenuItem("Size", TestSize), MenuHelper.CreateMenuItem("Alignment", TestAlignment), MenuHelper.CreateMenuItem("Padding", TestPadding) )); } private Panel GetNewRootPanel() { var c = _form.GetChildByName("Root"); if (c != null) { _form.RemoveChild(c); c.Dispose(); } var p = new Panel("Root", 0, 28, _form.Width, _form.Height - 28); _form.AddChild(p); return p; } private void TestFonts(object sender, point point) { var panel = GetNewRootPanel(); panel.BackColor = 0; int x = 1; var l = new Label("L1", "Droid8", Fonts.Droid8, x, 1, false); panel.AddChild(l); l = new Label("L2", "Droid9", Fonts.Droid9, x, l.Y + l.Height + 1, false); panel.AddChild(l); l = new Label("L3", "Droid11", Fonts.Droid11, x, l.Y + l.Height + 1, false); panel.AddChild(l); l = new Label("L4", "Droid12", Fonts.Droid12, x, l.Y + l.Height + 1, false); panel.AddChild(l); l = new Label("L5", "Droid16", Fonts.Droid12, x, l.Y + l.Height + 1, false); panel.AddChild(l); x = l.X + l.Width + 2; l = new Label("I1", "Italic8", Fonts.Droid8Italic, x, 1, false); panel.AddChild(l); l = new Label("I2", "Italic9", Fonts.Droid9Italic, x, l.Y + l.Height + 1, false); panel.AddChild(l); l = new Label("I3", "Italic11", Fonts.Droid11Italic, x, l.Y + l.Height + 1, false); panel.AddChild(l); l = new Label("I4", "Italic12", Fonts.Droid12Italic, x, l.Y + l.Height + 1, false); panel.AddChild(l); l = new Label("I5", "Italic16", Fonts.Droid16Italic, x, l.Y + l.Height + 1, false); panel.AddChild(l); x = l.X + l.Width + 2; l = new Label("B1", "Bold8", Fonts.Droid8Bold, x, 1, false); panel.AddChild(l); l = new Label("B2", "Bold9", Fonts.Droid9Bold, x, l.Y + l.Height + 1, false); panel.AddChild(l); l = new Label("B3", "Bold11", Fonts.Droid11Bold, x, l.Y + l.Height + 1, false); panel.AddChild(l); l = new Label("B4", "Bold12", Fonts.Droid12Bold, x, l.Y + l.Height + 1, false); panel.AddChild(l); l = new Label("B5", "Bold16", Fonts.Droid16Bold, x, l.Y + l.Height + 1, false); panel.AddChild(l); x = l.X + l.Width + 2; l = new Label("BI1", "BoldItalic 8", Fonts.Droid8BoldItalic, x, 1, false); panel.AddChild(l); l = new Label("BI2", "BoldItalic 9", Fonts.Droid9BoldItalic, x, l.Y + l.Height + 1, false); panel.AddChild(l); l = new Label("BI3", "BoldItalic 11", Fonts.Droid11BoldItalic, x, l.Y + l.Height + 1, false); panel.AddChild(l); l = new Label("BI4", "BoldItalic 12", Fonts.Droid12BoldItalic, x, l.Y + l.Height + 1, false); panel.AddChild(l); l = new Label("BI5", "BoldItalic 16", Fonts.Droid16BoldItalic, x, l.Y + l.Height + 1, false); panel.AddChild(l); int y = l.Y + l.Height + 5; x = 1; l = new Label("L1", "Red", Fonts.Droid11, x, y, Colors.Red, false); panel.AddChild(l); l = new Label("L1", "Green", Fonts.Droid11, x, l.Y + l.Height + 1, Colors.Green, false); panel.AddChild(l); l = new Label("L1", "Blue", Fonts.Droid11, x, l.Y + l.Height + 1, Colors.Blue, false); panel.AddChild(l); l = new Label("L1", "Red", Fonts.Droid11, x, l.Y + l.Height + 1, Colors.Red, false); l.BackColor = Colors.DarkGray; panel.AddChild(l); l = new Label("L1", "Green", Fonts.Droid11, x, l.Y + l.Height + 1, Colors.Green, false); l.BackColor = Colors.Yellow; panel.AddChild(l); l = new Label("L1", "Blue", Fonts.Droid11, x, l.Y + l.Height + 1, Colors.Blue, false); l.BackColor = Colors.Brown; panel.AddChild(l); x = l.X + l.Width + 30; l = new Label("BI5", "Back", Fonts.Droid16, x, y, false); panel.AddChild(l); l = new Label("BI5", "Transparent", Fonts.Droid8, x + 1, y + 2, Colors.Red); panel.AddChild(l); } private Label[] _labels; private int _n; private void TestSize(object sender, point point) { var panel = GetNewRootPanel(); panel.BackColor = 0; var l = new Label("L1", "Auto size", Fonts.Droid9, 1, 1, false); panel.AddChild(l); l = new Label("L2", "Fixed size large", Fonts.Droid9, 1, 30, 200, 30, false); panel.AddChild(l); l = new Label("L3", "Fixed size small", Fonts.Droid9, 1, 65, 20, 10, false); panel.AddChild(l); l = new Label("L4", "Fixed width", Fonts.Droid9, 1, 95, 200, Colors.Black, false); panel.AddChild(l); _labels = new Label[2]; var btn = new Button("Font", "F", Fonts.Droid11, 210, 5); btn.Tap += TestSizeFont; panel.AddChild(btn); btn = new Button("Text", "T", Fonts.Droid11, 245, 5); btn.Tap += TestSizeText; panel.AddChild(btn); btn = new Button("Color", "C", Fonts.Droid11, 280, 5); btn.Tap += TestSizeColor; panel.AddChild(btn); btn = new Button("BackColor", "B", Fonts.Droid11, 315, 5); btn.Tap += TestSizeBackColor; panel.AddChild(btn); _labels[0] = new Label("Ls0", "Fixed size", Fonts.Droid9, 210, 35, 200, 30, false); panel.AddChild(_labels[0]); _labels[1] = new Label("Ls0", "Auto size", Fonts.Droid9, 210, 80, false); panel.AddChild(_labels[1]); } private void TestSizeFont(object sender, point point) { for (int n = 0; n < _labels.Length; ++n) { if (_labels[n].Font == Fonts.Droid9) { _labels[n].Font = Fonts.Droid12; } else { _labels[n].Font = Fonts.Droid9; } } } private void TestSizeText(object sender, point point) { if (_labels != null && _labels.Length >= 2) { if (_labels[0].Text == "Fixed size") { _labels[0].Text = "A somewhat longer text\n2n line"; _labels[1].Text = "A somewhat longer text\n2n line"; } else { _labels[0].Text = "Fixed size"; _labels[1].Text = "Auto size"; } } } private void TestSizeColor(object sender, point point) { if (_labels != null && _labels.Length >= 2) { if (_labels[0].Color == Core.SystemColors.FontColor) { _labels[0].Color = Colors.Green; _labels[1].Color = Colors.Blue; } else { _labels[0].Color = Core.SystemColors.FontColor; _labels[1].Color = Core.SystemColors.FontColor; } } } private void TestSizeBackColor(object sender, point point) { if (_labels != null && _labels.Length >= 2) { if (_labels[0].BackColor == Core.SystemColors.ContainerBackground) { _labels[0].BackColor = Colors.Orange; _labels[1].BackColor = Colors.Orange; } else { _labels[0].BackColor = Core.SystemColors.ContainerBackground; _labels[1].BackColor = Core.SystemColors.ContainerBackground; } } } private void TestAlignment(object sender, point point) { var panel = GetNewRootPanel(); panel.BackColor = 0; var btn = new Button("HL", "L", Fonts.Droid11, 10, 10); btn.Tag = HorizontalAlignment.Left; btn.Tap += TestAlignmentHorizontal; panel.AddChild(btn); btn = new Button("HC", "C", Fonts.Droid11, 150, 10); btn.Tag = HorizontalAlignment.Center; btn.Tap += TestAlignmentHorizontal; panel.AddChild(btn); btn = new Button("HR", "R", Fonts.Droid11, 280, 10); btn.Tag = HorizontalAlignment.Right; btn.Tap += TestAlignmentHorizontal; panel.AddChild(btn); btn = new Button("VT", "T", Fonts.Droid11, 315, 50); btn.Tag = VerticalAlignment.Top; btn.Tap += TestAlignmentVertical; panel.AddChild(btn); btn = new Button("VC", "C", Fonts.Droid11, 315, 85); btn.Tag = VerticalAlignment.Center; btn.Tap += TestAlignmentVertical; panel.AddChild(btn); btn = new Button("VB", "B", Fonts.Droid11, 315, 120); btn.Tag = VerticalAlignment.Bottom; btn.Tap += TestAlignmentVertical; panel.AddChild(btn); _labels = new Label[2]; _labels[0] = new Label("L1", "Auto size\nL2", Fonts.Droid11, 10, 50, false); panel.AddChild(_labels[0]); _labels[1] = new Label("L2", "Fixed size\nL2", Fonts.Droid11, 10, 90, 300, 60, false); panel.AddChild(_labels[1]); } private void TestAlignmentHorizontal(object sender, point point) { _labels[0].TextAlignment = (HorizontalAlignment)((Button) sender).Tag; _labels[1].TextAlignment = (HorizontalAlignment)((Button)sender).Tag; } private void TestAlignmentVertical(object sender, point point) { _labels[0].VerticalAlignment = (VerticalAlignment)((Button)sender).Tag; _labels[1].VerticalAlignment = (VerticalAlignment)((Button)sender).Tag; } private void TestPadding(object sender, point point) { var panel = GetNewRootPanel(); panel.BackColor = 0; var btn = new Button("Padding", "Padding", Fonts.Droid11, 10, 10); btn.Tag = HorizontalAlignment.Left; btn.Tap += TestPaddingSwitch; panel.AddChild(btn); _labels = new Label[2]; _n = 0; _labels[0] = new Label("L1", "Auto size\nL2", Fonts.Droid11, 10, 50, false); _labels[0].Padding = new Thickness(5); panel.AddChild(_labels[0]); _labels[1] = new Label("L2", "5", Fonts.Droid11, 10, 120, 300, 60, false); _labels[1].Padding = new Thickness(5); panel.AddChild(_labels[1]); } private void TestPaddingSwitch(object sender, point point) { switch (_n) { case 0: _labels[0].Padding = new Thickness(10, 3); _labels[1].Padding = new Thickness(10, 3); _labels[1].Text = "10, 3"; break; case 1: _labels[0].Padding = new Thickness(5, 10, 15, 20); _labels[1].Padding = new Thickness(5, 10, 15, 20); _labels[1].Text = "5, 10, 15, 20"; break; case 2: _labels[0].Padding = new Thickness(0); _labels[1].Padding = new Thickness(0); _labels[1].Text = "0"; break; case 3: _labels[0].Padding = new Thickness(10); _labels[1].Padding = new Thickness(10); _labels[1].Text = "10"; break; case 4: _labels[0].Padding = new Thickness(5); _labels[1].Padding = new Thickness(5); _labels[1].Text = "5"; break; } if (++_n > 4) { _n = 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 Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class CompilationContext { private static readonly SymbolDisplayFormat s_fullNameFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); internal readonly CSharpCompilation Compilation; internal readonly Binder NamespaceBinder; // Internal for test purposes. private readonly MetadataDecoder _metadataDecoder; private readonly MethodSymbol _currentFrame; private readonly ImmutableArray<LocalSymbol> _locals; private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables; private readonly ImmutableHashSet<string> _hoistedParameterNames; private readonly ImmutableArray<LocalSymbol> _localsForBinding; private readonly CSharpSyntaxNode _syntax; private readonly bool _methodNotType; /// <summary> /// Create a context to compile expressions within a method scope. /// </summary> internal CompilationContext( CSharpCompilation compilation, MetadataDecoder metadataDecoder, MethodSymbol currentFrame, ImmutableArray<LocalSymbol> locals, InScopeHoistedLocals inScopeHoistedLocals, MethodDebugInfo methodDebugInfo, CSharpSyntaxNode syntax) { Debug.Assert(string.IsNullOrEmpty(methodDebugInfo.DefaultNamespaceName)); Debug.Assert((syntax == null) || (syntax is ExpressionSyntax) || (syntax is LocalDeclarationStatementSyntax)); // TODO: syntax.SyntaxTree should probably be added to the compilation, // but it isn't rooted by a CompilationUnitSyntax so it doesn't work (yet). _currentFrame = currentFrame; _syntax = syntax; _methodNotType = !locals.IsDefault; // NOTE: Since this is done within CompilationContext, it will not be cached. // CONSIDER: The values should be the same everywhere in the module, so they // could be cached. // (Catch: what happens in a type context without a method def?) this.Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords); _metadataDecoder = metadataDecoder; // Each expression compile should use a unique compilation // to ensure expression-specific synthesized members can be // added (anonymous types, for instance). Debug.Assert(this.Compilation != compilation); this.NamespaceBinder = CreateBinderChain( this.Compilation, (PEModuleSymbol)currentFrame.ContainingModule, currentFrame.ContainingNamespace, methodDebugInfo.ImportRecordGroups, _metadataDecoder); if (_methodNotType) { _locals = locals; ImmutableArray<string> displayClassVariableNamesInOrder; GetDisplayClassVariables( currentFrame, _locals, inScopeHoistedLocals, out displayClassVariableNamesInOrder, out _displayClassVariables, out _hoistedParameterNames); Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count); _localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables); } else { _locals = ImmutableArray<LocalSymbol>.Empty; _displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; _localsForBinding = ImmutableArray<LocalSymbol>.Empty; } // Assert that the cheap check for "this" is equivalent to the expensive check for "this". Debug.Assert( _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()) == _displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This)); } internal CommonPEModuleBuilder CompileExpression( string typeName, string methodName, ImmutableArray<Alias> aliases, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics, out ResultProperties resultProperties) { var properties = default(ResultProperties); var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( this.Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, typeName, methodName, this, (method, diags) => { var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()); var binder = ExtendBinderChain( _syntax, aliases, method, this.NamespaceBinder, hasDisplayClassThis, _methodNotType); var statementSyntax = _syntax as StatementSyntax; return (statementSyntax == null) ? BindExpression(binder, (ExpressionSyntax)_syntax, diags, out properties) : BindStatement(binder, statementSyntax, diags, out properties); }); var module = CreateModuleBuilder( this.Compilation, synthesizedType.Methods, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), synthesizedType: synthesizedType, testData: testData, diagnostics: diagnostics); Debug.Assert(module != null); this.Compilation.Compile( module, win32Resources: null, xmlDocStream: null, emittingPdb: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: CancellationToken.None); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } // Should be no name mangling since the caller provided explicit names. Debug.Assert(synthesizedType.MetadataName == typeName); Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName); resultProperties = properties; return module; } internal CommonPEModuleBuilder CompileAssignment( string typeName, string methodName, ImmutableArray<Alias> aliases, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics, out ResultProperties resultProperties) { var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, typeName, methodName, this, (method, diags) => { var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()); var binder = ExtendBinderChain( _syntax, aliases, method, this.NamespaceBinder, hasDisplayClassThis, methodNotType: true); return BindAssignment(binder, (ExpressionSyntax)_syntax, diags); }); var module = CreateModuleBuilder( this.Compilation, synthesizedType.Methods, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), synthesizedType: synthesizedType, testData: testData, diagnostics: diagnostics); Debug.Assert(module != null); this.Compilation.Compile( module, win32Resources: null, xmlDocStream: null, emittingPdb: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: CancellationToken.None); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } // Should be no name mangling since the caller provided explicit names. Debug.Assert(synthesizedType.MetadataName == typeName); Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName); resultProperties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect); return module; } private static string GetNextMethodName(ArrayBuilder<MethodSymbol> builder) { return string.Format("<>m{0}", builder.Count); } /// <summary> /// Generate a class containing methods that represent /// the set of arguments and locals at the current scope. /// </summary> internal CommonPEModuleBuilder CompileGetLocals( string typeName, ArrayBuilder<LocalAndMethod> localBuilder, bool argumentsOnly, ImmutableArray<Alias> aliases, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics) { var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object); var allTypeParameters = _currentFrame.GetAllTypeParameters(); var additionalTypes = ArrayBuilder<NamedTypeSymbol>.GetInstance(); EENamedTypeSymbol typeVariablesType = null; if (!argumentsOnly && (allTypeParameters.Length > 0)) { // Generate a generic type with matching type parameters. // A null instance of the type will be used to represent the // "Type variables" local. typeVariablesType = new EENamedTypeSymbol( this.Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, ExpressionCompilerConstants.TypeVariablesClassName, (m, t) => ImmutableArray.Create<MethodSymbol>(new EEConstructorSymbol(t)), allTypeParameters, (t1, t2) => allTypeParameters.SelectAsArray((tp, i, t) => (TypeParameterSymbol)new SimpleTypeParameterSymbol(t, i, tp.Name), t2)); additionalTypes.Add(typeVariablesType); } var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, typeName, (m, container) => { var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance(); if (!argumentsOnly) { // Pseudo-variables: $exception, $ReturnValue, etc. if (aliases.Length > 0) { var sourceAssembly = Compilation.SourceAssembly; var typeNameDecoder = new EETypeNameDecoder(Compilation, (PEModuleSymbol)_currentFrame.ContainingModule); foreach (var alias in aliases) { var local = PlaceholderLocalSymbol.Create( typeNameDecoder, _currentFrame, sourceAssembly, alias); var methodName = GetNextMethodName(methodBuilder); var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); var aliasMethod = this.CreateMethod(container, methodName, syntax, (method, diags) => { var expression = new BoundLocal(syntax, local, constantValueOpt: null, type: local.Type); return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; }); var flags = local.IsWritable ? DkmClrCompilationResultFlags.None : DkmClrCompilationResultFlags.ReadOnlyResult; localBuilder.Add(MakeLocalAndMethod(local, aliasMethod, flags)); methodBuilder.Add(aliasMethod); } } // "this" for non-static methods that are not display class methods or // display class methods where the display class contains "<>4__this". if (!m.IsStatic && (!IsDisplayClassType(m.ContainingType) || _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()))) { var methodName = GetNextMethodName(methodBuilder); var method = this.GetThisMethod(container, methodName); localBuilder.Add(new CSharpLocalAndMethod("this", "this", method, DkmClrCompilationResultFlags.None)); // Note: writable in dev11. methodBuilder.Add(method); } } // Hoisted method parameters (represented as locals in the EE). if (!_hoistedParameterNames.IsEmpty) { int localIndex = 0; foreach (var local in _localsForBinding) { // Since we are showing hoisted method parameters first, the parameters may appear out of order // in the Locals window if only some of the parameters are hoisted. This is consistent with the // behavior of the old EE. if (_hoistedParameterNames.Contains(local.Name)) { AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local)); } localIndex++; } } // Method parameters (except those that have been hoisted). int parameterIndex = m.IsStatic ? 0 : 1; foreach (var parameter in m.Parameters) { var parameterName = parameter.Name; if (!_hoistedParameterNames.Contains(parameterName) && GeneratedNames.GetKind(parameterName) == GeneratedNameKind.None) { AppendParameterAndMethod(localBuilder, methodBuilder, parameter, container, parameterIndex); } parameterIndex++; } if (!argumentsOnly) { // Locals. int localIndex = 0; foreach (var local in _localsForBinding) { if (!_hoistedParameterNames.Contains(local.Name)) { AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local)); } localIndex++; } // "Type variables". if ((object)typeVariablesType != null) { var methodName = GetNextMethodName(methodBuilder); var returnType = typeVariablesType.Construct(allTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>()); var method = this.GetTypeVariablesMethod(container, methodName, returnType); localBuilder.Add(new CSharpLocalAndMethod( ExpressionCompilerConstants.TypeVariablesLocalName, ExpressionCompilerConstants.TypeVariablesLocalName, method, DkmClrCompilationResultFlags.ReadOnlyResult)); methodBuilder.Add(method); } } return methodBuilder.ToImmutableAndFree(); }); additionalTypes.Add(synthesizedType); var module = CreateModuleBuilder( this.Compilation, synthesizedType.Methods, additionalTypes: additionalTypes.ToImmutableAndFree(), synthesizedType: synthesizedType, testData: testData, diagnostics: diagnostics); Debug.Assert(module != null); this.Compilation.Compile( module, win32Resources: null, xmlDocStream: null, emittingPdb: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: CancellationToken.None); return diagnostics.HasAnyErrors() ? null : module; } private void AppendLocalAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, LocalSymbol local, EENamedTypeSymbol container, int localIndex, DkmClrCompilationResultFlags resultFlags) { var methodName = GetNextMethodName(methodBuilder); var method = this.GetLocalMethod(container, methodName, local.Name, localIndex); localBuilder.Add(MakeLocalAndMethod(local, method, resultFlags)); methodBuilder.Add(method); } private void AppendParameterAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, ParameterSymbol parameter, EENamedTypeSymbol container, int parameterIndex) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. var name = SyntaxHelpers.EscapeKeywordIdentifiers(parameter.Name); var methodName = GetNextMethodName(methodBuilder); var method = this.GetParameterMethod(container, methodName, name, parameterIndex); localBuilder.Add(new CSharpLocalAndMethod(name, name, method, DkmClrCompilationResultFlags.None)); methodBuilder.Add(method); } private static LocalAndMethod MakeLocalAndMethod(LocalSymbol local, MethodSymbol method, DkmClrCompilationResultFlags flags) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. var escapedName = SyntaxHelpers.EscapeKeywordIdentifiers(local.Name); var displayName = (local as PlaceholderLocalSymbol)?.DisplayName ?? escapedName; return new CSharpLocalAndMethod(escapedName, displayName, method, flags); } private static EEAssemblyBuilder CreateModuleBuilder( CSharpCompilation compilation, ImmutableArray<MethodSymbol> methods, ImmutableArray<NamedTypeSymbol> additionalTypes, EENamedTypeSymbol synthesizedType, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics) { // Each assembly must have a unique name. var emitOptions = new EmitOptions(outputNameOverride: ExpressionCompilerUtilities.GenerateUniqueName()); var dynamicOperationContextType = GetNonDisplayClassContainer(synthesizedType.SubstitutedSourceType); string runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics); var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion); return new EEAssemblyBuilder(compilation.SourceAssembly, emitOptions, methods, serializationProperties, additionalTypes, dynamicOperationContextType, testData); } internal EEMethodSymbol CreateMethod( EENamedTypeSymbol container, string methodName, CSharpSyntaxNode syntax, GenerateMethodBody generateMethodBody) { return new EEMethodSymbol( container, methodName, syntax.Location, _currentFrame, _locals, _localsForBinding, _displayClassVariables, generateMethodBody); } private EEMethodSymbol GetLocalMethod(EENamedTypeSymbol container, string methodName, string localName, int localIndex) { var syntax = SyntaxFactory.IdentifierName(localName); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var local = method.LocalsForBinding[localIndex]; var expression = new BoundLocal(syntax, local, constantValueOpt: local.GetConstantValue(null, null, diagnostics), type: local.Type); return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetParameterMethod(EENamedTypeSymbol container, string methodName, string parameterName, int parameterIndex) { var syntax = SyntaxFactory.IdentifierName(parameterName); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var parameter = method.Parameters[parameterIndex]; var expression = new BoundParameter(syntax, parameter); return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetThisMethod(EENamedTypeSymbol container, string methodName) { var syntax = SyntaxFactory.ThisExpression(); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var expression = new BoundThisReference(syntax, GetNonDisplayClassContainer(container.SubstitutedSourceType)); return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetTypeVariablesMethod(EENamedTypeSymbol container, string methodName, NamedTypeSymbol typeVariablesType) { var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var type = method.TypeMap.SubstituteNamedType(typeVariablesType); var expression = new BoundObjectCreationExpression(syntax, type.InstanceConstructors[0]); var statement = new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; return statement; }); } private static BoundStatement BindExpression(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics, out ResultProperties resultProperties) { var flags = DkmClrCompilationResultFlags.None; // In addition to C# expressions, the native EE also supports // type names which are bound to a representation of the type // (but not System.Type) that the user can expand to see the // base type. Instead, we only allow valid C# expressions. var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } if (MayHaveSideEffectsVisitor.MayHaveSideEffects(expression)) { flags |= DkmClrCompilationResultFlags.PotentialSideEffect; } var expressionType = expression.Type; if ((object)expressionType == null) { expression = binder.CreateReturnConversion( syntax, diagnostics, expression, binder.Compilation.GetSpecialType(SpecialType.System_Object)); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } } else if (expressionType.SpecialType == SpecialType.System_Void) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; Debug.Assert(expression.ConstantValue == null); resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant: false); return new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true }; } else if (expressionType.SpecialType == SpecialType.System_Boolean) { flags |= DkmClrCompilationResultFlags.BoolResult; } if (!IsAssignableExpression(binder, expression)) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; } resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValue != null); return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; } private static BoundStatement BindStatement(Binder binder, StatementSyntax syntax, DiagnosticBag diagnostics, out ResultProperties properties) { properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); return binder.BindStatement(syntax, diagnostics); } private static bool IsAssignableExpression(Binder binder, BoundExpression expression) { // NOTE: Surprisingly, binder.CheckValueKind will return true (!) for readonly fields // in contexts where they cannot be assigned - it simply reports a diagnostic. // Presumably, this is done to avoid producing a confusing error message about the // field not being an lvalue. var diagnostics = DiagnosticBag.GetInstance(); var result = binder.CheckValueKind(expression, Binder.BindValueKind.Assignment, diagnostics) && !diagnostics.HasAnyErrors(); diagnostics.Free(); return result; } private static BoundStatement BindAssignment(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics) { var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue); if (diagnostics.HasAnyErrors()) { return null; } return new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true }; } private static Binder CreateBinderChain( CSharpCompilation compilation, PEModuleSymbol module, NamespaceSymbol @namespace, ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups, MetadataDecoder metadataDecoder) { var stack = ArrayBuilder<string>.GetInstance(); while ((object)@namespace != null) { stack.Push(@namespace.Name); @namespace = @namespace.ContainingNamespace; } var binder = (new BuckStopsHereBinder(compilation)).WithAdditionalFlags( BinderFlags.SuppressObsoleteChecks | BinderFlags.IgnoreAccessibility | BinderFlags.UnsafeRegion | BinderFlags.UncheckedRegion | BinderFlags.AllowManagedAddressOf | BinderFlags.AllowAwaitInUnsafeContext | BinderFlags.IgnoreCorLibraryDuplicatedTypes); var hasImports = !importRecordGroups.IsDefaultOrEmpty; var numImportStringGroups = hasImports ? importRecordGroups.Length : 0; var currentStringGroup = numImportStringGroups - 1; // PERF: We used to call compilation.GetCompilationNamespace on every iteration, // but that involved walking up to the global namespace, which we have to do // anyway. Instead, we'll inline the functionality into our own walk of the // namespace chain. @namespace = compilation.GlobalNamespace; while (stack.Count > 0) { var namespaceName = stack.Pop(); if (namespaceName.Length > 0) { // We're re-getting the namespace, rather than using the one containing // the current frame method, because we want the merged namespace. @namespace = @namespace.GetNestedNamespace(namespaceName); Debug.Assert((object)@namespace != null, $"We worked backwards from symbols to names, but no symbol exists for name '{namespaceName}'"); } else { Debug.Assert((object)@namespace == (object)compilation.GlobalNamespace); } Imports imports = null; if (hasImports) { if (currentStringGroup < 0) { Debug.WriteLine($"No import string group for namespace '{@namespace}'"); break; } var importsBinder = new InContainerBinder(@namespace, binder); imports = BuildImports(compilation, module, importRecordGroups[currentStringGroup], importsBinder, metadataDecoder); currentStringGroup--; } binder = new InContainerBinder(@namespace, binder, imports); } stack.Free(); if (currentStringGroup >= 0) { // CONSIDER: We could lump these into the outermost namespace. It's probably not worthwhile since // the usings are already for the wrong method. Debug.WriteLine($"Found {currentStringGroup + 1} import string groups without corresponding namespaces"); } return binder; } private static CSharpCompilation GetCompilationWithExternAliases(CSharpCompilation compilation, ImmutableArray<ExternAliasRecord> externAliasRecords) { if (externAliasRecords.IsDefaultOrEmpty) { return compilation.Clone(); } var updatedReferences = ArrayBuilder<MetadataReference>.GetInstance(); var assembliesAndModulesBuilder = ArrayBuilder<Symbol>.GetInstance(); foreach (var reference in compilation.References) { updatedReferences.Add(reference); assembliesAndModulesBuilder.Add(compilation.GetAssemblyOrModuleSymbol(reference)); } Debug.Assert(assembliesAndModulesBuilder.Count == updatedReferences.Count); var assembliesAndModules = assembliesAndModulesBuilder.ToImmutableAndFree(); foreach (var externAliasRecord in externAliasRecords) { int index = externAliasRecord.GetIndexOfTargetAssembly(assembliesAndModules, compilation.Options.AssemblyIdentityComparer); if (index < 0) { Debug.WriteLine($"Unable to find corresponding assembly reference for extern alias '{externAliasRecord}'"); continue; } var externAlias = externAliasRecord.Alias; var assemblyReference = updatedReferences[index]; var oldAliases = assemblyReference.Properties.Aliases; var newAliases = oldAliases.IsEmpty ? ImmutableArray.Create(MetadataReferenceProperties.GlobalAlias, externAlias) : oldAliases.Concat(ImmutableArray.Create(externAlias)); // NOTE: Dev12 didn't emit custom debug info about "global", so we don't have // a good way to distinguish between a module aliased with both (e.g.) "X" and // "global" and a module aliased with only "X". As in Dev12, we assume that // "global" is a valid alias to remain at least as permissive as source. // NOTE: In the event that this introduces ambiguities between two assemblies // (e.g. because one was "global" in source and the other was "X"), it should be // possible to disambiguate as long as each assembly has a distinct extern alias, // not necessarily used in source. Debug.Assert(newAliases.Contains(MetadataReferenceProperties.GlobalAlias)); // Replace the value in the map with the updated reference. updatedReferences[index] = assemblyReference.WithAliases(newAliases); } compilation = compilation.WithReferences(updatedReferences); updatedReferences.Free(); return compilation; } private static Binder ExtendBinderChain( CSharpSyntaxNode syntax, ImmutableArray<Alias> aliases, EEMethodSymbol method, Binder binder, bool hasDisplayClassThis, bool methodNotType) { var substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassThis); var substitutedSourceType = substitutedSourceMethod.ContainingType; var stack = ArrayBuilder<NamedTypeSymbol>.GetInstance(); for (var type = substitutedSourceType; (object)type != null; type = type.ContainingType) { stack.Add(type); } while (stack.Count > 0) { substitutedSourceType = stack.Pop(); binder = new InContainerBinder(substitutedSourceType, binder); if (substitutedSourceType.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceType.TypeArguments, binder); } } stack.Free(); if (substitutedSourceMethod.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceMethod.TypeArguments, binder); } if (methodNotType) { // Method locals and parameters shadow pseudo-variables. var typeNameDecoder = new EETypeNameDecoder(binder.Compilation, (PEModuleSymbol)substitutedSourceMethod.ContainingModule); binder = new PlaceholderLocalBinder( syntax, aliases, method, typeNameDecoder, binder); } binder = new EEMethodBinder(method, substitutedSourceMethod, binder); if (methodNotType) { binder = new SimpleLocalScopeBinder(method.LocalsForBinding, binder); } return binder; } private static Imports BuildImports(CSharpCompilation compilation, PEModuleSymbol module, ImmutableArray<ImportRecord> importRecords, InContainerBinder binder, MetadataDecoder metadataDecoder) { // We make a first pass to extract all of the extern aliases because other imports may depend on them. var externsBuilder = ArrayBuilder<AliasAndExternAliasDirective>.GetInstance(); foreach (var importRecord in importRecords) { if (importRecord.TargetKind != ImportTargetKind.Assembly) { continue; } var alias = importRecord.Alias; IdentifierNameSyntax aliasNameSyntax; if (!TryParseIdentifierNameSyntax(alias, out aliasNameSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{alias}'"); continue; } var externAliasSyntax = SyntaxFactory.ExternAliasDirective(aliasNameSyntax.Identifier); var aliasSymbol = new AliasSymbol(binder, externAliasSyntax); // Binder is only used to access compilation. externsBuilder.Add(new AliasAndExternAliasDirective(aliasSymbol, externAliasDirective: null)); // We have one, but we pass null for consistency. } var externs = externsBuilder.ToImmutableAndFree(); if (externs.Any()) { // NB: This binder (and corresponding Imports) is only used to bind the other imports. // We'll merge the externs into a final Imports object and return that to be used in // the actual binder chain. binder = new InContainerBinder( binder.Container, binder, Imports.FromCustomDebugInfo(binder.Compilation, new Dictionary<string, AliasAndUsingDirective>(), ImmutableArray<NamespaceOrTypeAndUsingDirective>.Empty, externs)); } var usingAliases = new Dictionary<string, AliasAndUsingDirective>(); var usingsBuilder = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance(); foreach (var importRecord in importRecords) { switch (importRecord.TargetKind) { case ImportTargetKind.Type: { var portableImportRecord = importRecord as PortableImportRecord; TypeSymbol typeSymbol = portableImportRecord != null ? portableImportRecord.GetTargetType(metadataDecoder) : metadataDecoder.GetTypeSymbolForSerializedType(importRecord.TargetString); Debug.Assert((object)typeSymbol != null); if (typeSymbol.IsErrorType()) { // Type is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } else if (importRecord.Alias == null && !typeSymbol.IsStatic) { // Only static types can be directly imported. continue; } if (!TryAddImport(importRecord.Alias, typeSymbol, usingsBuilder, usingAliases, binder, importRecord)) { continue; } break; } case ImportTargetKind.Namespace: { var namespaceName = importRecord.TargetString; NameSyntax targetSyntax; if (!SyntaxHelpers.TryParseDottedName(namespaceName, out targetSyntax)) { // DevDiv #999086: Some previous version of VS apparently generated type aliases as "UA{alias} T{alias-qualified type name}". // Neither Roslyn nor Dev12 parses such imports. However, Roslyn discards them, rather than interpreting them as "UA{alias}" // (which will rarely work and never be correct). Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid target '{importRecord.TargetString}'"); continue; } NamespaceSymbol namespaceSymbol; var portableImportRecord = importRecord as PortableImportRecord; if (portableImportRecord != null) { var targetAssembly = portableImportRecord.GetTargetAssembly<ModuleSymbol, AssemblySymbol>(module, module.Module); if ((object)targetAssembly == null) { namespaceSymbol = BindNamespace(namespaceName, compilation.GlobalNamespace); } else if (targetAssembly.IsMissing) { Debug.WriteLine($"Import record '{importRecord}' has invalid assembly reference '{targetAssembly.Identity}'"); continue; } else { namespaceSymbol = BindNamespace(namespaceName, targetAssembly.GlobalNamespace); } } else { var globalNamespace = compilation.GlobalNamespace; var externAlias = ((NativeImportRecord)importRecord).ExternAlias; if (externAlias != null) { IdentifierNameSyntax externAliasSyntax = null; if (!TryParseIdentifierNameSyntax(externAlias, out externAliasSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{externAlias}'"); continue; } var unusedDiagnostics = DiagnosticBag.GetInstance(); var aliasSymbol = (AliasSymbol)binder.BindNamespaceAliasSymbol(externAliasSyntax, unusedDiagnostics); unusedDiagnostics.Free(); if ((object)aliasSymbol == null) { Debug.WriteLine($"Import record '{importRecord}' requires unknown extern alias '{externAlias}'"); continue; } globalNamespace = (NamespaceSymbol)aliasSymbol.Target; } namespaceSymbol = BindNamespace(namespaceName, globalNamespace); } if ((object)namespaceSymbol == null) { // Namespace is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } if (!TryAddImport(importRecord.Alias, namespaceSymbol, usingsBuilder, usingAliases, binder, importRecord)) { continue; } break; } case ImportTargetKind.Assembly: { // Handled in first pass (above). break; } default: { throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind); } } } return Imports.FromCustomDebugInfo(binder.Compilation, usingAliases, usingsBuilder.ToImmutableAndFree(), externs); } private static NamespaceSymbol BindNamespace(string namespaceName, NamespaceSymbol globalNamespace) { var namespaceSymbol = globalNamespace; foreach (var name in namespaceName.Split('.')) { var members = namespaceSymbol.GetMembers(name); namespaceSymbol = members.Length == 1 ? members[0] as NamespaceSymbol : null; if ((object)namespaceSymbol == null) { break; } } return namespaceSymbol; } private static bool TryAddImport( string alias, NamespaceOrTypeSymbol targetSymbol, ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder, Dictionary<string, AliasAndUsingDirective> usingAliases, InContainerBinder binder, ImportRecord importRecord) { if (alias == null) { usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingDirective: null)); } else { IdentifierNameSyntax aliasSyntax; if (!TryParseIdentifierNameSyntax(alias, out aliasSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{alias}'"); return false; } var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder); usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingDirective: null)); } return true; } private static bool TryParseIdentifierNameSyntax(string name, out IdentifierNameSyntax syntax) { Debug.Assert(name != null); if (name == MetadataReferenceProperties.GlobalAlias) { syntax = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); return true; } NameSyntax nameSyntax; if (!SyntaxHelpers.TryParseDottedName(name, out nameSyntax) || nameSyntax.Kind() != SyntaxKind.IdentifierName) { syntax = null; return false; } syntax = (IdentifierNameSyntax)nameSyntax; return true; } internal CommonMessageProvider MessageProvider { get { return this.Compilation.MessageProvider; } } private static DkmClrCompilationResultFlags GetLocalResultFlags(LocalSymbol local) { // CONSIDER: We might want to prevent the user from modifying pinned locals - // that's pretty dangerous. return local.IsConst ? DkmClrCompilationResultFlags.ReadOnlyResult : DkmClrCompilationResultFlags.None; } /// <summary> /// Generate the set of locals to use for binding. /// </summary> private static ImmutableArray<LocalSymbol> GetLocalsForBinding( ImmutableArray<LocalSymbol> locals, ImmutableArray<string> displayClassVariableNamesInOrder, ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { var builder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var local in locals) { var name = local.Name; if (name == null) { continue; } if (GeneratedNames.GetKind(name) != GeneratedNameKind.None) { continue; } // Although Roslyn doesn't name synthesized locals unless they are well-known to EE, // Dev12 did so we need to skip them here. if (GeneratedNames.IsSynthesizedLocalName(name)) { continue; } builder.Add(local); } foreach (var variableName in displayClassVariableNamesInOrder) { var variable = displayClassVariables[variableName]; switch (variable.Kind) { case DisplayClassVariableKind.Local: case DisplayClassVariableKind.Parameter: builder.Add(new EEDisplayClassFieldLocalSymbol(variable)); break; } } return builder.ToImmutableAndFree(); } /// <summary> /// Return a mapping of captured variables (parameters, locals, and /// "this") to locals. The mapping is needed to expose the original /// local identifiers (those from source) in the binder. /// </summary> private static void GetDisplayClassVariables( MethodSymbol method, ImmutableArray<LocalSymbol> locals, InScopeHoistedLocals inScopeHoistedLocals, out ImmutableArray<string> displayClassVariableNamesInOrder, out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables, out ImmutableHashSet<string> hoistedParameterNames) { // Calculated the shortest paths from locals to instances of display // classes. There should not be two instances of the same display // class immediately within any particular method. var displayClassTypes = PooledHashSet<NamedTypeSymbol>.GetInstance(); var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance(); // Add any display class instances from locals (these will contain any hoisted locals). foreach (var local in locals) { var name = local.Name; if ((name != null) && (GeneratedNames.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField)) { var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local); displayClassTypes.Add(instance.Type); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } foreach (var parameter in method.Parameters) { if (GeneratedNames.GetKind(parameter.Name) == GeneratedNameKind.TransparentIdentifier) { var instance = new DisplayClassInstanceFromParameter(parameter); displayClassTypes.Add(instance.Type); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } var containingType = method.ContainingType; bool isIteratorOrAsyncMethod = false; if (IsDisplayClassType(containingType)) { if (!method.IsStatic) { // Add "this" display class instance. var instance = new DisplayClassInstanceFromParameter(method.ThisParameter); displayClassTypes.Add(instance.Type); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } isIteratorOrAsyncMethod = GeneratedNames.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType; } if (displayClassInstances.Any()) { // Find any additional display class instances breadth first. for (int depth = 0; GetDisplayClassInstances(displayClassTypes, displayClassInstances, depth) > 0; depth++) { } // The locals are the set of all fields from the display classes. var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance(); var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance(); var parameterNames = PooledHashSet<string>.GetInstance(); if (isIteratorOrAsyncMethod) { Debug.Assert(IsDisplayClassType(containingType)); foreach (var field in containingType.GetMembers().OfType<FieldSymbol>()) { // All iterator and async state machine fields (including hoisted locals) have mangled names, except // for hoisted parameters (whose field names are always the same as the original source parameters). var fieldName = field.Name; if (GeneratedNames.GetKind(fieldName) == GeneratedNameKind.None) { parameterNames.Add(fieldName); } } } else { foreach (var p in method.Parameters) { parameterNames.Add(p.Name); } } var pooledHoistedParameterNames = PooledHashSet<string>.GetInstance(); foreach (var instance in displayClassInstances) { GetDisplayClassVariables( displayClassVariableNamesInOrderBuilder, displayClassVariablesBuilder, parameterNames, inScopeHoistedLocals, instance, pooledHoistedParameterNames); } hoistedParameterNames = pooledHoistedParameterNames.ToImmutableHashSet<string>(); pooledHoistedParameterNames.Free(); parameterNames.Free(); displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree(); displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary(); displayClassVariablesBuilder.Free(); } else { hoistedParameterNames = ImmutableHashSet<string>.Empty; displayClassVariableNamesInOrder = ImmutableArray<string>.Empty; displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; } displayClassTypes.Free(); displayClassInstances.Free(); } /// <summary> /// Return the set of display class instances that can be reached /// from the given local. A particular display class may be reachable /// from multiple locals. In those cases, the instance from the /// shortest path (fewest intermediate fields) is returned. /// </summary> private static int GetDisplayClassInstances( HashSet<NamedTypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, int depth) { Debug.Assert(displayClassInstances.All(p => p.Depth <= depth)); var atDepth = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance(); atDepth.AddRange(displayClassInstances.Where(p => p.Depth == depth)); Debug.Assert(atDepth.Count > 0); int n = 0; foreach (var instance in atDepth) { n += GetDisplayClassInstances(displayClassTypes, displayClassInstances, instance); } atDepth.Free(); return n; } private static int GetDisplayClassInstances( HashSet<NamedTypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, DisplayClassInstanceAndFields instance) { // Display class instance. The display class fields are variables. int n = 0; foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldType = field.Type; var fieldKind = GeneratedNames.GetKind(field.Name); if (fieldKind == GeneratedNameKind.DisplayClassLocalOrField || fieldKind == GeneratedNameKind.TransparentIdentifier || IsTransparentIdentifierFieldInAnonymousType(field) || (fieldKind == GeneratedNameKind.ThisProxyField && GeneratedNames.GetKind(fieldType.Name) == GeneratedNameKind.LambdaDisplayClass)) // Async lambda case. { Debug.Assert(!field.IsStatic); // A local that is itself a display class instance. if (displayClassTypes.Add((NamedTypeSymbol)fieldType)) { var other = instance.FromField(field); displayClassInstances.Add(other); n++; } } } return n; } private static bool IsTransparentIdentifierFieldInAnonymousType(FieldSymbol field) { string fieldName = field.Name; if (GeneratedNames.GetKind(fieldName) != GeneratedNameKind.AnonymousTypeField) { return false; } GeneratedNameKind kind; int openBracketOffset; int closeBracketOffset; if (!GeneratedNames.TryParseGeneratedName(fieldName, out kind, out openBracketOffset, out closeBracketOffset)) { return false; } fieldName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); return GeneratedNames.GetKind(fieldName) == GeneratedNameKind.TransparentIdentifier; } private static void GetDisplayClassVariables( ArrayBuilder<string> displayClassVariableNamesInOrderBuilder, Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder, HashSet<string> parameterNames, InScopeHoistedLocals inScopeHoistedLocals, DisplayClassInstanceAndFields instance, HashSet<string> hoistedParameterNames) { // Display class instance. The display class fields are variables. foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldName = field.Name; REPARSE: DisplayClassVariableKind variableKind; string variableName; GeneratedNameKind fieldKind; int openBracketOffset; int closeBracketOffset; GeneratedNames.TryParseGeneratedName(fieldName, out fieldKind, out openBracketOffset, out closeBracketOffset); switch (fieldKind) { case GeneratedNameKind.AnonymousTypeField: Debug.Assert(fieldName == field.Name); // This only happens once. fieldName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); goto REPARSE; case GeneratedNameKind.TransparentIdentifier: // A transparent identifier (field) in an anonymous type synthesized for a transparent identifier. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.DisplayClassLocalOrField: // A local that is itself a display class instance. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.HoistedLocalField: // Filter out hoisted locals that are known to be out-of-scope at the current IL offset. // Hoisted locals with invalid indices will be included since more information is better // than less in error scenarios. if (!inScopeHoistedLocals.IsInScope(fieldName)) { continue; } variableName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); variableKind = DisplayClassVariableKind.Local; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.ThisProxyField: // A reference to "this". variableName = fieldName; variableKind = DisplayClassVariableKind.This; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.None: // A reference to a parameter or local. variableName = fieldName; if (parameterNames.Contains(variableName)) { variableKind = DisplayClassVariableKind.Parameter; hoistedParameterNames.Add(variableName); } else { variableKind = DisplayClassVariableKind.Local; } Debug.Assert(!field.IsStatic); break; default: continue; } if (displayClassVariablesBuilder.ContainsKey(variableName)) { // Only expecting duplicates for async state machine // fields (that should be at the top-level). Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1); Debug.Assert(instance.Fields.Count() >= 1); // greater depth Debug.Assert((variableKind == DisplayClassVariableKind.Parameter) || (variableKind == DisplayClassVariableKind.This)); } else if (variableKind != DisplayClassVariableKind.This || GeneratedNames.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass) { // In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one. // In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one). displayClassVariableNamesInOrderBuilder.Add(variableName); displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field)); } } } private static bool IsDisplayClassType(NamedTypeSymbol type) { switch (GeneratedNames.GetKind(type.Name)) { case GeneratedNameKind.LambdaDisplayClass: case GeneratedNameKind.StateMachineType: return true; default: return false; } } private static NamedTypeSymbol GetNonDisplayClassContainer(NamedTypeSymbol type) { // 1) Display class and state machine types are always nested within the types // that use them (so that they can access private members of those types). // 2) The native compiler used to produce nested display classes for nested lambdas, // so we may have to walk out more than one level. while (IsDisplayClassType(type)) { type = type.ContainingType; } Debug.Assert((object)type != null); return type; } /// <summary> /// Identifies the method in which binding should occur. /// </summary> /// <param name="candidateSubstitutedSourceMethod"> /// The symbol of the method that is currently on top of the callstack, with /// EE type parameters substituted in place of the original type parameters. /// </param> /// <param name="sourceMethodMustBeInstance"> /// True if "this" is available via a display class in the current context. /// </param> /// <returns> /// If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated, /// then we will attempt to determine which user-defined method caused it to be /// generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/> /// is a state machine MoveNext method, then we will try to find the iterator or /// async method for which it was generated. If we are able to find the original /// method, then we will substitute in the EE type parameters. Otherwise, we will /// return <paramref name="candidateSubstitutedSourceMethod"/>. /// </returns> /// <remarks> /// In the event that the original method is overloaded, we may not be able to determine /// which overload actually corresponds to the state machine. In particular, we do not /// have information about the signature of the original method (i.e. number of parameters, /// parameter types and ref-kinds, return type). However, we conjecture that this /// level of uncertainty is acceptable, since parameters are managed by a separate binder /// in the synthesized binder chain and we have enough information to check the other method /// properties that are used during binding (e.g. static-ness, generic arity, type parameter /// constraints). /// </remarks> internal static MethodSymbol GetSubstitutedSourceMethod( MethodSymbol candidateSubstitutedSourceMethod, bool sourceMethodMustBeInstance) { var candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType; string desiredMethodName; if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceType.Name, GeneratedNameKind.StateMachineType, out desiredMethodName) || GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LambdaMethod, out desiredMethodName)) { // We could be in the MoveNext method of an async lambda. string tempMethodName; if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LambdaMethod, out tempMethodName)) { desiredMethodName = tempMethodName; var containing = candidateSubstitutedSourceType.ContainingType; Debug.Assert((object)containing != null); if (GeneratedNames.GetKind(containing.Name) == GeneratedNameKind.LambdaDisplayClass) { candidateSubstitutedSourceType = containing; sourceMethodMustBeInstance = candidateSubstitutedSourceType.MemberNames.Select(GeneratedNames.GetKind).Contains(GeneratedNameKind.ThisProxyField); } } var desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters; // Type containing the original iterator, async, or lambda-containing method. var substitutedSourceType = GetNonDisplayClassContainer(candidateSubstitutedSourceType); foreach (var candidateMethod in substitutedSourceType.GetMembers().OfType<MethodSymbol>()) { if (IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, sourceMethodMustBeInstance)) { return desiredTypeParameters.Length == 0 ? candidateMethod : candidateMethod.Construct(candidateSubstitutedSourceType.TypeArguments); } } Debug.Assert(false, "Why didn't we find a substituted source method for " + candidateSubstitutedSourceMethod + "?"); } return candidateSubstitutedSourceMethod; } private static bool IsViableSourceMethod( MethodSymbol candidateMethod, string desiredMethodName, ImmutableArray<TypeParameterSymbol> desiredTypeParameters, bool desiredMethodMustBeInstance) { return !candidateMethod.IsAbstract && (!(desiredMethodMustBeInstance && candidateMethod.IsStatic)) && candidateMethod.Name == desiredMethodName && HaveSameConstraints(candidateMethod.TypeParameters, desiredTypeParameters); } private static bool HaveSameConstraints(ImmutableArray<TypeParameterSymbol> candidateTypeParameters, ImmutableArray<TypeParameterSymbol> desiredTypeParameters) { int arity = candidateTypeParameters.Length; if (arity != desiredTypeParameters.Length) { return false; } else if (arity == 0) { return true; } var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var candidateTypeMap = new TypeMap(candidateTypeParameters, indexedTypeParameters, allowAlpha: true); var desiredTypeMap = new TypeMap(desiredTypeParameters, indexedTypeParameters, allowAlpha: true); return MemberSignatureComparer.HaveSameConstraints(candidateTypeParameters, candidateTypeMap, desiredTypeParameters, desiredTypeMap); } private struct DisplayClassInstanceAndFields { internal readonly DisplayClassInstance Instance; internal readonly ConsList<FieldSymbol> Fields; internal DisplayClassInstanceAndFields(DisplayClassInstance instance) : this(instance, ConsList<FieldSymbol>.Empty) { Debug.Assert(IsDisplayClassType(instance.Type) || GeneratedNames.GetKind(instance.Type.Name) == GeneratedNameKind.AnonymousType); } private DisplayClassInstanceAndFields(DisplayClassInstance instance, ConsList<FieldSymbol> fields) { this.Instance = instance; this.Fields = fields; } internal NamedTypeSymbol Type { get { return this.Fields.Any() ? (NamedTypeSymbol)this.Fields.Head.Type : this.Instance.Type; } } internal int Depth { get { return this.Fields.Count(); } } internal DisplayClassInstanceAndFields FromField(FieldSymbol field) { Debug.Assert(IsDisplayClassType((NamedTypeSymbol)field.Type) || GeneratedNames.GetKind(field.Type.Name) == GeneratedNameKind.AnonymousType); return new DisplayClassInstanceAndFields(this.Instance, this.Fields.Prepend(field)); } internal DisplayClassVariable ToVariable(string name, DisplayClassVariableKind kind, FieldSymbol field) { return new DisplayClassVariable(name, kind, this.Instance, this.Fields.Prepend(field)); } } } }
/* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ using System; using System.Collections; using System.IO; using System.Text; using NUnit.Framework; using Razorvine.Pickle; namespace Pyrolite.Tests.Pickle { /// <summary> /// Unit tests for the pickler utils. /// </summary> [TestFixture] public class PickleUtilsTest { private byte[] filedata; [TestFixtureSetUp] public void setUp() { filedata=Encoding.UTF8.GetBytes("str1\nstr2 \n str3 \nend"); } [TestFixtureTearDown] public void tearDown() { } [Test] public void testReadline() { Stream bis = new MemoryStream(filedata); PickleUtils p=new PickleUtils(bis); Assert.AreEqual("str1", p.readline()); Assert.AreEqual("str2 ", p.readline()); Assert.AreEqual(" str3 ", p.readline()); Assert.AreEqual("end", p.readline()); try { p.readline(); Assert.Fail("expected IOException"); } catch(IOException) {} } [Test] public void testReadlineWithLF() { Stream bis=new MemoryStream(filedata); PickleUtils p=new PickleUtils(bis); Assert.AreEqual("str1\n", p.readline(true)); Assert.AreEqual("str2 \n", p.readline(true)); Assert.AreEqual(" str3 \n", p.readline(true)); Assert.AreEqual("end", p.readline(true)); try { p.readline(true); Assert.Fail("expected IOException"); } catch(IOException) {} } [Test] public void testReadbytes() { Stream bis=new MemoryStream(filedata); PickleUtils p=new PickleUtils(bis); Assert.AreEqual(115, p.readbyte()); Assert.AreEqual(new byte[]{}, p.readbytes(0)); Assert.AreEqual(new byte[]{116}, p.readbytes(1)); Assert.AreEqual(new byte[]{114,49,10,115,116}, p.readbytes(5)); try { p.readbytes(999); Assert.Fail("expected IOException"); } catch(IOException) {} } [Test] public void testReadbytes_into() { Stream bis=new MemoryStream(filedata); PickleUtils p=new PickleUtils(bis); byte[] bytes = new byte[] {0,0,0,0,0,0,0,0,0,0}; p.readbytes_into(bytes, 1, 4); Assert.AreEqual(new byte[] {0,115,116,114,49,0,0,0,0,0}, bytes); p.readbytes_into(bytes, 8, 1); Assert.AreEqual(new byte[] {0,115,116,114,49,0,0,0,10,0}, bytes); } [Test] public void testBytes_to_integer() { try { PickleUtils.bytes_to_integer(new byte[] {}); Assert.Fail("expected PickleException"); } catch (PickleException) {} try { PickleUtils.bytes_to_integer(new byte[] {0}); Assert.Fail("expected PickleException"); } catch (PickleException) {} Assert.AreEqual(0x00000000, PickleUtils.bytes_to_integer(new byte[] {0x00, 0x00})); Assert.AreEqual(0x00003412, PickleUtils.bytes_to_integer(new byte[] {0x12, 0x34})); Assert.AreEqual(0x0000ffff, PickleUtils.bytes_to_integer(new byte[] {0xff, 0xff})); Assert.AreEqual(0x00000000, PickleUtils.bytes_to_integer(new byte[] {0,0,0,0})); Assert.AreEqual(0x12345678, PickleUtils.bytes_to_integer(new byte[] {0x78, 0x56, 0x34, 0x12})); Assert.AreEqual(-8380352, PickleUtils.bytes_to_integer(new byte[] {0x40, 0x20, 0x80, 0xff})); Assert.AreEqual(0x01cc02ee, PickleUtils.bytes_to_integer(new byte[] {0xee, 0x02, 0xcc, 0x01})); Assert.AreEqual(-872288766, PickleUtils.bytes_to_integer(new byte[] {0x02, 0xee, 0x01, 0xcc})); Assert.AreEqual(-285212674, PickleUtils.bytes_to_integer(new byte[] {0xfe, 0xff, 0xff, 0xee})); try { PickleUtils.bytes_to_integer(new byte[] { 200,50,25,100,1,2,3,4}); Assert.Fail("expected PickleException"); } catch (PickleException) {} } [Test] public void testBytes_to_uint() { try { PickleUtils.bytes_to_uint(new byte[] {},0); Assert.Fail("expected PickleException"); } catch (PickleException) {} try { PickleUtils.bytes_to_uint(new byte[] {0},0); Assert.Fail("expected PickleException"); } catch (PickleException) {} Assert.AreEqual(0x000000000L, PickleUtils.bytes_to_uint(new byte[] {0,0,0,0} ,0)); Assert.AreEqual(0x012345678L, PickleUtils.bytes_to_uint(new byte[] {0x78, 0x56, 0x34, 0x12} ,0)); Assert.AreEqual(0x0ff802040L, PickleUtils.bytes_to_uint(new byte[] {0x40, 0x20, 0x80, 0xff} ,0)); Assert.AreEqual(0x0eefffffeL, PickleUtils.bytes_to_uint(new byte[] {0xfe, 0xff, 0xff,0xee} ,0)); } [Test] public void testBytes_to_long() { try { PickleUtils.bytes_to_long(new byte[] {}, 0); Assert.Fail("expected PickleException"); } catch (PickleException) {} try { PickleUtils.bytes_to_long(new byte[] {0}, 0); Assert.Fail("expected PickleException"); } catch (PickleException) {} Assert.AreEqual(0x00000000L, PickleUtils.bytes_to_long(new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} ,0)); Assert.AreEqual(0x00003412L, PickleUtils.bytes_to_long(new byte[] {0x12, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} ,0)); Assert.AreEqual(-0xffffffffffff01L, PickleUtils.bytes_to_long(new byte[] {0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff} ,0)); Assert.AreEqual(0L, PickleUtils.bytes_to_long(new byte[] {0,0,0,0,0,0,0,0} ,0)); Assert.AreEqual(-0x778899aabbccddefL, PickleUtils.bytes_to_long(new byte[] {0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88} ,0)); Assert.AreEqual(0x1122334455667788L, PickleUtils.bytes_to_long(new byte[] {0x88,0x77,0x66,0x55,0x44,0x33,0x22,0x11} ,0)); Assert.AreEqual(-1L, PickleUtils.bytes_to_long(new byte[] {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff} ,0)); Assert.AreEqual(-2L, PickleUtils.bytes_to_long(new byte[] {0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff} ,0)); } [Test] public void testInteger_to_bytes() { PickleUtils p=new PickleUtils(null); Assert.AreEqual(new byte[]{0,0,0,0}, p.integer_to_bytes(0)); Assert.AreEqual(new byte[]{0x78, 0x56, 0x34, 0x12}, p.integer_to_bytes(0x12345678)); Assert.AreEqual(new byte[]{0x40, 0x20, 0x80, 0xff}, p.integer_to_bytes(-8380352)); Assert.AreEqual(new byte[]{0xfe, 0xff, 0xff ,0xee}, p.integer_to_bytes(-285212674)); Assert.AreEqual(new byte[]{0xff, 0xff, 0xff, 0xff}, p.integer_to_bytes(-1)); Assert.AreEqual(new byte[]{0xee, 0x02, 0xcc, 0x01}, p.integer_to_bytes(0x01cc02ee)); Assert.AreEqual(new byte[]{0x02, 0xee, 0x01, 0xcc}, p.integer_to_bytes(-872288766)); } [Test] public void testBytes_to_double() { try { PickleUtils.bytes_to_double(new byte[] {} ,0); Assert.Fail("expected PickleException"); } catch (PickleException) {} try { PickleUtils.bytes_to_double(new byte[] {0} ,0); Assert.Fail("expected PickleException"); } catch (PickleException) {} Assert.AreEqual(0.0d, PickleUtils.bytes_to_double(new byte[] {0,0,0,0,0,0,0,0} ,0)); Assert.AreEqual(1.0d, PickleUtils.bytes_to_double(new byte[] {0x3f,0xf0,0,0,0,0,0,0} ,0)); Assert.AreEqual(1.1d, PickleUtils.bytes_to_double(new byte[] {0x3f,0xf1,0x99,0x99,0x99,0x99,0x99,0x9a} ,0)); Assert.AreEqual(1234.5678d, PickleUtils.bytes_to_double(new byte[] {0x40,0x93,0x4a,0x45,0x6d,0x5c,0xfa,0xad} ,0)); Assert.AreEqual(2.17e123d, PickleUtils.bytes_to_double(new byte[] {0x59,0x8a,0x42,0xd1,0xce,0xf5,0x3f,0x46} ,0)); Assert.AreEqual(1.23456789e300d, PickleUtils.bytes_to_double(new byte[] {0x7e,0x3d,0x7e,0xe8,0xbc,0xaf,0x28,0x3a} ,0)); Assert.AreEqual(double.PositiveInfinity, PickleUtils.bytes_to_double(new byte[] {0x7f,0xf0,0,0,0,0,0,0} ,0)); Assert.AreEqual(double.NegativeInfinity, PickleUtils.bytes_to_double(new byte[] {0xff,0xf0,0,0,0,0,0,0} ,0)); try { PickleUtils.bytes_to_double(new byte[] { 200,50,25,100} ,0); Assert.Fail("expected PickleException"); } catch (PickleException) {} // test offset Assert.AreEqual(1.23456789e300d, PickleUtils.bytes_to_double(new byte[] {0,0,0,0x7e,0x3d,0x7e,0xe8,0xbc,0xaf,0x28,0x3a} ,3)); Assert.AreEqual(1.23456789e300d, PickleUtils.bytes_to_double(new byte[] {0x7e,0x3d,0x7e,0xe8,0xbc,0xaf,0x28,0x3a,0,0,0} ,0)); } [Test] public void testBytes_to_float() { try { PickleUtils.bytes_to_float(new byte[] {}, 0); Assert.Fail("expected PickleException"); } catch (PickleException) {} try { PickleUtils.bytes_to_float(new byte[] {0}, 0); Assert.Fail("expected PickleException"); } catch (PickleException) {} Assert.IsTrue(0.0f == PickleUtils.bytes_to_float(new byte[] {0,0,0,0}, 0)); Assert.IsTrue(1.0f == PickleUtils.bytes_to_float(new byte[] {0x3f,0x80,0,0} ,0)); Assert.IsTrue(1.1f == PickleUtils.bytes_to_float(new byte[] {0x3f,0x8c,0xcc,0xcd} ,0)); Assert.IsTrue(1234.5678f == PickleUtils.bytes_to_float(new byte[] {0x44,0x9a,0x52,0x2b} ,0)); Assert.IsTrue(float.PositiveInfinity == PickleUtils.bytes_to_float(new byte[] {0x7f,0x80,0,0} ,0)); Assert.IsTrue(float.NegativeInfinity == PickleUtils.bytes_to_float(new byte[] {0xff,0x80,0,0} ,0)); // test offset Assert.IsTrue(1234.5678f == PickleUtils.bytes_to_float(new byte[] {0,0,0, 0x44,0x9a,0x52,0x2b} ,3)); Assert.IsTrue(1234.5678f == PickleUtils.bytes_to_float(new byte[] {0x44,0x9a,0x52,0x2b,0,0,0} ,0)); } [Test] public void testDouble_to_bytes() { PickleUtils p=new PickleUtils(null); Assert.AreEqual(new byte[]{0,0,0,0,0,0,0,0}, p.double_to_bytes(0.0d)); Assert.AreEqual(new byte[]{0x3f,0xf0,0,0,0,0,0,0}, p.double_to_bytes(1.0d)); Assert.AreEqual(new byte[]{0x3f,0xf1,0x99,0x99,0x99,0x99,0x99,0x9a}, p.double_to_bytes(1.1d)); Assert.AreEqual(new byte[]{0x40,0x93,0x4a,0x45,0x6d,0x5c,0xfa,0xad}, p.double_to_bytes(1234.5678d)); Assert.AreEqual(new byte[]{0x59,0x8a,0x42,0xd1,0xce,0xf5,0x3f,0x46}, p.double_to_bytes(2.17e123d)); Assert.AreEqual(new byte[]{0x7e,0x3d,0x7e,0xe8,0xbc,0xaf,0x28,0x3a}, p.double_to_bytes(1.23456789e300d)); // cannot test NaN because it's not always the same byte representation... // Assert.AreEqual(new byte[]{0xff,0xf8,0,0,0,0,0,0}, p.double_to_bytes(Double.NaN)); Assert.AreEqual(new byte[]{0x7f,0xf0,0,0,0,0,0,0}, p.double_to_bytes(Double.PositiveInfinity)); Assert.AreEqual(new byte[]{0xff,0xf0,0,0,0,0,0,0}, p.double_to_bytes(Double.NegativeInfinity)); } [Test] public void testDecode_long() { PickleUtils p=new PickleUtils(null); Assert.AreEqual(0L, p.decode_long(new byte[0])); Assert.AreEqual(0L, p.decode_long(new byte[]{0})); Assert.AreEqual(1L, p.decode_long(new byte[]{1})); Assert.AreEqual(10L, p.decode_long(new byte[]{10})); Assert.AreEqual(255L, p.decode_long(new byte[]{0xff,0x00})); Assert.AreEqual(32767L, p.decode_long(new byte[]{0xff,0x7f})); Assert.AreEqual(-256L, p.decode_long(new byte[]{0x00,0xff})); Assert.AreEqual(-32768L, p.decode_long(new byte[]{0x00,0x80})); Assert.AreEqual(-128L, p.decode_long(new byte[]{0x80})); Assert.AreEqual(127L, p.decode_long(new byte[]{0x7f})); Assert.AreEqual(128L, p.decode_long(new byte[]{0x80, 0x00})); Assert.AreEqual(128L, p.decode_long(new byte[]{0x80, 0x00})); Assert.AreEqual(0x78563412L, p.decode_long(new byte[]{0x12,0x34,0x56,0x78})); Assert.AreEqual(0x785634f2L, p.decode_long(new byte[]{0xf2,0x34,0x56,0x78})); Assert.AreEqual(0x12345678L, p.decode_long(new byte[]{0x78,0x56,0x34,0x12})); Assert.AreEqual(-231451016L, p.decode_long(new byte[]{0x78,0x56,0x34,0xf2})); Assert.AreEqual(0xf2345678L, p.decode_long(new byte[]{0x78,0x56,0x34,0xf2,0x00})); } } }
/* * InformationMachineAPI.PCL * * */ using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using InformationMachineAPI.PCL; namespace InformationMachineAPI.PCL.Models { public class UserPurchase : INotifyPropertyChanged { // These fields hold the values for the public properties. private long id; private UserStore userStore; private List<PurchaseItemData> purchaseItems; private DateTime? date; private double? total; private double? totalWithoutTax; private double? tax; private string orderNumber; private string receiptId; private List<ReceiptImage> receiptImageUrls; /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("id")] public long Id { get { return this.id; } set { this.id = value; onPropertyChanged("Id"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("user_store")] public UserStore UserStore { get { return this.userStore; } set { this.userStore = value; onPropertyChanged("UserStore"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("purchase_items")] public List<PurchaseItemData> PurchaseItems { get { return this.purchaseItems; } set { this.purchaseItems = value; onPropertyChanged("PurchaseItems"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("date")] public DateTime? Date { get { return this.date; } set { this.date = value; onPropertyChanged("Date"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("total")] public double? Total { get { return this.total; } set { this.total = value; onPropertyChanged("Total"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("total_without_tax")] public double? TotalWithoutTax { get { return this.totalWithoutTax; } set { this.totalWithoutTax = value; onPropertyChanged("TotalWithoutTax"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("tax")] public double? Tax { get { return this.tax; } set { this.tax = value; onPropertyChanged("Tax"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("order_number")] public string OrderNumber { get { return this.orderNumber; } set { this.orderNumber = value; onPropertyChanged("OrderNumber"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("receipt_id")] public string ReceiptId { get { return this.receiptId; } set { this.receiptId = value; onPropertyChanged("ReceiptId"); } } /// <summary> /// TODO: Write general description for this method /// </summary> [JsonProperty("receipt_image_urls")] public List<ReceiptImage> ReceiptImageUrls { get { return this.receiptImageUrls; } set { this.receiptImageUrls = value; onPropertyChanged("ReceiptImageUrls"); } } /// <summary> /// Property changed event for observer pattern /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises event when a property is changed /// </summary> /// <param name="propertyName">Name of the changed property</param> protected void onPropertyChanged(String propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
// 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; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Collections.Generic; using System.Security; using System.Runtime.CompilerServices; namespace System.Runtime.Serialization { #if USE_REFEMIT || NET_NATIVE public class XmlObjectSerializerWriteContextComplex : XmlObjectSerializerWriteContext #else internal class XmlObjectSerializerWriteContextComplex : XmlObjectSerializerWriteContext #endif { private SerializationMode _mode; internal XmlObjectSerializerWriteContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { _mode = SerializationMode.SharedContract; this.preserveObjectReferences = serializer.PreserveObjectReferences; } internal XmlObjectSerializerWriteContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { } internal override SerializationMode Mode { get { return _mode; } } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract) { return false; } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName) { return false; } #if NET_NATIVE public override void WriteAnyType(XmlWriterDelegator xmlWriter, object value) #else internal override void WriteAnyType(XmlWriterDelegator xmlWriter, object value) #endif { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteAnyType(value); } #if NET_NATIVE public override void WriteString(XmlWriterDelegator xmlWriter, string value) #else internal override void WriteString(XmlWriterDelegator xmlWriter, string value) #endif { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteString(value); } #if NET_NATIVE public override void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) #else internal override void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(string), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteString(value); xmlWriter.WriteEndElementPrimitive(); } } #if NET_NATIVE public override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) #else internal override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) #endif { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteBase64(value); } #if NET_NATIVE public override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) #else internal override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(byte[]), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteBase64(value); xmlWriter.WriteEndElementPrimitive(); } } #if NET_NATIVE public override void WriteUri(XmlWriterDelegator xmlWriter, Uri value) #else internal override void WriteUri(XmlWriterDelegator xmlWriter, Uri value) #endif { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteUri(value); } #if NET_NATIVE public override void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) #else internal override void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(Uri), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteUri(value); xmlWriter.WriteEndElementPrimitive(); } } #if NET_NATIVE public override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value) #else internal override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value) #endif { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteQName(value); } #if NET_NATIVE public override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) #else internal override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(XmlQualifiedName), true/*isMemberTypeSerializable*/, name, ns); else { if (ns != null && ns.Value != null && ns.Value.Length > 0) xmlWriter.WriteStartElement(Globals.ElementPrefix, name, ns); else xmlWriter.WriteStartElement(name, ns); if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteQName(value); xmlWriter.WriteEndElement(); } } internal override bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (preserveObjectReferences && !this.IsGetOnlyCollection) { bool isNew = true; int objectId = SerializedObjects.GetId(obj, ref isNew); if (isNew) xmlWriter.WriteAttributeInt(Globals.SerPrefix, DictionaryGlobals.IdLocalName, DictionaryGlobals.SerializationNamespace, objectId); else { xmlWriter.WriteAttributeInt(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, objectId); xmlWriter.WriteAttributeBool(Globals.XsiPrefix, DictionaryGlobals.XsiNilLocalName, DictionaryGlobals.SchemaInstanceNamespace, true); } return !isNew; } return base.OnHandleReference(xmlWriter, obj, canContainCyclicReference); } internal override void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (preserveObjectReferences && !this.IsGetOnlyCollection) return; base.OnEndHandleReference(xmlWriter, obj, canContainCyclicReference); } private void InternalSerializeWithSurrogate(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) { RuntimeTypeHandle objTypeHandle = isDeclaredType ? declaredTypeHandle : obj.GetType().TypeHandle; object oldObj = obj; Type objType = Type.GetTypeFromHandle(objTypeHandle); Type declaredType = GetSurrogatedType(Type.GetTypeFromHandle(declaredTypeHandle)); declaredTypeHandle = declaredType.TypeHandle; throw new PlatformNotSupportedException(); } internal override void WriteArraySize(XmlWriterDelegator xmlWriter, int size) { if (preserveObjectReferences && size > -1) xmlWriter.WriteAttributeInt(Globals.SerPrefix, DictionaryGlobals.ArraySizeLocalName, DictionaryGlobals.SerializationNamespace, size); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using Newtonsoft.Json; using System.Xml.Linq; namespace MangaPortal.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (C) 2014 dot42 // // Original filename: Stream.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Java.Io; using JInputStream = Java.Io.InputStream; using JOutputStream = Java.Io.OutputStream; namespace System.IO { /// <summary> /// Sequence of bytes. /// </summary> public abstract class Stream : IDisposable { private class NullStream : Stream { public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return true; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { } } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override int ReadByte() { return -1; } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int count) { } public override void WriteByte(byte value) { } } private InputStreamWrapper inputStreamWrapper; private OutputStreamWrapper outputStreamWrapper; /// <summary> /// A Stream with no backing store. /// </summary> public static readonly Stream Null = new NullStream(); /// <summary> /// Is reading from this stream supported? /// </summary> public abstract bool CanRead { get; } /// <summary> /// Is writing to this stream supported? /// </summary> public abstract bool CanWrite { get; } /// <summary> /// Is seeking supported? /// </summary> public abstract bool CanSeek { get; } /// <summary> /// Gets the length of this sequence in bytes. /// </summary> public abstract long Length { get; } /// <summary> /// Gets/sets the position within this stream. /// </summary> public abstract long Position { get; set; } /// <summary> /// Close this stream and any resources that it may hold. /// </summary> public virtual void Close() { Dispose(true); } /// <summary> /// Copy bytes from this stream into the given destination. /// </summary> public void CopyTo(Stream destination) { CopyTo(destination, 4096); } /// <summary> /// Copy bytes from this stream into the given destination. /// </summary> public void CopyTo(Stream destination, int bufferSize) { var buf = new byte[bufferSize]; int len; while ((len = Read(buf, 0, buf.Length)) > 0) { destination.Write(buf, 0, len); } } /// <summary> /// Perform application defined cleanup of the resource. /// </summary> public void Dispose() { } /// <summary> /// Release unmanaged resources. /// </summary> /// <param name="disposing">If set, also release managed resources.</param> protected virtual void Dispose(bool disposing) { } /// <summary> /// Ensure that any buffered data is written to the underlying device. /// </summary> public abstract void Flush(); /// <summary> /// Read a sequence of bytes from this stream and advance the position of this stream. /// </summary> /// <param name="buffer">Destination</param> /// <param name="offset">Offset within the buffer</param> /// <param name="count">Number of bytes to read.</param> /// <returns>The total number of bytes read or 0 if the end of the stream has been reached.</returns> public abstract int Read(byte[] buffer, int offset, int count); /// <summary> /// Read a single byte and advance the position of this stream. /// </summary> /// <returns>The byte that was read or -1 if at the end of the stream.</returns> public virtual int ReadByte() { var buffer = new byte[1]; return (Read(buffer, 0, 1) == 0) ? -1 : buffer[0]; } /// <summary> /// Set the position of this stream. /// </summary> /// <param name="offset">Byte offset relative to origin.</param> /// <param name="origin">Reference point.</param> /// <returns>New position of the stream.</returns> public abstract long Seek(long offset, SeekOrigin origin); /// <summary> /// Sets the length of the current stream. /// </summary> /// <param name="value">The new length of the stream.</param> public abstract void SetLength(long value); /// <summary> /// Write a sequence of bytes to this stream and advance the position of this stream. /// </summary> /// <param name="buffer">Destination</param> /// <param name="offset">Offset within the buffer</param> /// <param name="count">Number of bytes to write.</param> public abstract void Write(byte[] buffer, int offset, int count); /// <summary> /// Write a single byte and advance the position of this stream. /// </summary> public virtual void WriteByte(byte value) { Write(new[] { value }, 0, 1); } /// <summary> /// Create a stream that wraps a java <see cref="Java.Io.InputStream"/>. /// </summary> public static Stream Wrap(JInputStream source) { return new JavaInputStreamWrapper(source); } /// <summary> /// Create a stream that wraps a java <see cref="Java.Io.OutputStream"/>. /// </summary> public static Stream Wrap(JOutputStream source) { return new JavaOutputStreamWrapper(source); } /// <summary> /// Create a java <see cref="Java.Io.InputStream"/> that wraps the given stream. /// </summary> public static implicit operator JInputStream(Stream source) { return source.inputStreamWrapper ?? (source.inputStreamWrapper = new InputStreamWrapper(source)); } /// <summary> /// Create a java <see cref="Java.Io.OutputStream"/> that wraps the given stream. /// </summary> public static implicit operator JOutputStream(Stream source) { return source.outputStreamWrapper ?? (source.outputStreamWrapper = new OutputStreamWrapper(source)); } } }
// 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. // ---------------------------------------------------------------------------------- // Interop library code // // Marshalling helpers used by MCG // // NOTE: // These source code are being published to InternalAPIs and consumed by RH builds // Use PublishInteropAPI.bat to keep the InternalAPI copies in sync // ---------------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.InteropServices; using System.Threading; using System.Text; using System.Runtime; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using Internal.NativeFormat; #if !CORECLR using Internal.Runtime.Augments; #endif #if RHTESTCL using OutputClass = System.Console; #else using OutputClass = System.Diagnostics.Debug; #endif namespace System.Runtime.InteropServices { /// <summary> /// Expose functionality from System.Private.CoreLib and forwards calls to InteropExtensions in System.Private.CoreLib /// </summary> [CLSCompliant(false)] public static partial class McgMarshal { public static void SaveLastWin32Error() { PInvokeMarshal.SaveLastWin32Error(); } public static bool GuidEquals(ref Guid left, ref Guid right) { return InteropExtensions.GuidEquals(ref left, ref right); } public static bool ComparerEquals<T>(T left, T right) { return InteropExtensions.ComparerEquals<T>(left, right); } public static T CreateClass<T>() where T : class { return InteropExtensions.UncheckedCast<T>(InteropExtensions.RuntimeNewObject(typeof(T).TypeHandle)); } public static bool IsEnum(object obj) { #if RHTESTCL return false; #else return InteropExtensions.IsEnum(obj.GetTypeHandle()); #endif } public static bool IsCOMObject(Type type) { #if RHTESTCL return false; #else return type.GetTypeInfo().IsSubclassOf(typeof(__ComObject)); #endif } public static T FastCast<T>(object value) where T : class { // We have an assert here, to verify that a "real" cast would have succeeded. // However, casting on weakly-typed RCWs modifies their state, by doing a QI and caching // the result. This often makes things work which otherwise wouldn't work (especially variance). Debug.Assert(value == null || value is T); return InteropExtensions.UncheckedCast<T>(value); } /// <summary> /// Converts a managed DateTime to native OLE datetime /// Used by MCG marshalling code /// </summary> public static double ToNativeOleDate(DateTime dateTime) { return InteropExtensions.ToNativeOleDate(dateTime); } /// <summary> /// Converts native OLE datetime to managed DateTime /// Used by MCG marshalling code /// </summary> public static DateTime FromNativeOleDate(double nativeOleDate) { return InteropExtensions.FromNativeOleDate(nativeOleDate); } /// <summary> /// Used in Marshalling code /// Call safeHandle.InitializeHandle to set the internal _handle field /// </summary> public static void InitializeHandle(SafeHandle safeHandle, IntPtr win32Handle) { InteropExtensions.InitializeHandle(safeHandle, win32Handle); } /// <summary> /// Check if obj's type is the same as represented by normalized handle /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static bool IsOfType(object obj, RuntimeTypeHandle handle) { return obj.IsOfType(handle); } #if ENABLE_MIN_WINRT public static unsafe void SetExceptionErrorCode(Exception exception, int errorCode) { InteropExtensions.SetExceptionErrorCode(exception, errorCode); } /// <summary> /// Used in Marshalling code /// Gets the handle of the CriticalHandle /// </summary> public static IntPtr GetHandle(CriticalHandle criticalHandle) { return InteropExtensions.GetCriticalHandle(criticalHandle); } /// <summary> /// Used in Marshalling code /// Sets the handle of the CriticalHandle /// </summary> public static void SetHandle(CriticalHandle criticalHandle, IntPtr handle) { InteropExtensions.SetCriticalHandle(criticalHandle, handle); } #endif } /// <summary> /// McgMarshal helpers exposed to be used by MCG /// </summary> public static partial class McgMarshal { #region Type marshalling public static Type TypeNameToType(HSTRING nativeTypeName, int nativeTypeKind) { #if ENABLE_WINRT return McgTypeHelpers.TypeNameToType(nativeTypeName, nativeTypeKind); #else throw new NotSupportedException("TypeNameToType"); #endif } internal static Type TypeNameToType(string nativeTypeName, int nativeTypeKind) { #if ENABLE_WINRT return McgTypeHelpers.TypeNameToType(nativeTypeName, nativeTypeKind, checkTypeKind: false); #else throw new NotSupportedException("TypeNameToType"); #endif } public static unsafe void TypeToTypeName( Type type, out HSTRING nativeTypeName, out int nativeTypeKind) { #if ENABLE_WINRT McgTypeHelpers.TypeToTypeName(type, out nativeTypeName, out nativeTypeKind); #else throw new NotSupportedException("TypeToTypeName"); #endif } /// <summary> /// Fetch type name /// </summary> /// <param name="typeHandle">type</param> /// <returns>type name</returns> internal static string TypeToTypeName(RuntimeTypeHandle typeHandle, out int nativeTypeKind) { #if ENABLE_WINRT TypeKind typekind; string typeName; McgTypeHelpers.TypeToTypeName(typeHandle, out typeName, out typekind); nativeTypeKind = (int)typekind; return typeName; #else throw new NotSupportedException("TypeToTypeName"); #endif } #endregion #region String marshalling [CLSCompliant(false)] public static unsafe void StringBuilderToUnicodeString(System.Text.StringBuilder stringBuilder, ushort* destination) { PInvokeMarshal.StringBuilderToUnicodeString(stringBuilder, destination); } [CLSCompliant(false)] public static unsafe void UnicodeStringToStringBuilder(ushort* newBuffer, System.Text.StringBuilder stringBuilder) { PInvokeMarshal.UnicodeStringToStringBuilder(newBuffer, stringBuilder); } #if !RHTESTCL [CLSCompliant(false)] public static unsafe void StringBuilderToAnsiString(System.Text.StringBuilder stringBuilder, byte* pNative, bool bestFit, bool throwOnUnmappableChar) { PInvokeMarshal.StringBuilderToAnsiString(stringBuilder, pNative, bestFit, throwOnUnmappableChar); } [CLSCompliant(false)] public static unsafe void AnsiStringToStringBuilder(byte* newBuffer, System.Text.StringBuilder stringBuilder) { PInvokeMarshal.AnsiStringToStringBuilder(newBuffer, stringBuilder); } /// <summary> /// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG /// </summary> /// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string. /// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling /// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks> [CLSCompliant(false)] public static unsafe string AnsiStringToString(byte* pchBuffer) { return PInvokeMarshal.AnsiStringToString(pchBuffer); } /// <summary> /// Convert UNICODE string to ANSI string. /// </summary> /// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that /// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks> [CLSCompliant(false)] public static unsafe byte* StringToAnsiString(string str, bool bestFit, bool throwOnUnmappableChar) { return PInvokeMarshal.StringToAnsiString(str, bestFit, throwOnUnmappableChar); } /// <summary> /// Convert UNICODE wide char array to ANSI ByVal byte array. /// </summary> /// <remarks> /// * This version works with array instead string, it means that there will be NO NULL to terminate the array. /// * The buffer to store the byte array must be allocated by the caller and must fit managedArray.Length. /// </remarks> /// <param name="managedArray">UNICODE wide char array</param> /// <param name="pNative">Allocated buffer where the ansi characters must be placed. Could NOT be null. Buffer size must fit char[].Length.</param> [CLSCompliant(false)] public static unsafe void ByValWideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, int expectedCharCount, bool bestFit, bool throwOnUnmappableChar) { PInvokeMarshal.ByValWideCharArrayToAnsiCharArray(managedArray, pNative, expectedCharCount, bestFit, throwOnUnmappableChar); } [CLSCompliant(false)] public static unsafe void ByValAnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray) { PInvokeMarshal.ByValAnsiCharArrayToWideCharArray(pNative, managedArray); } [CLSCompliant(false)] public static unsafe void WideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, bool bestFit, bool throwOnUnmappableChar) { PInvokeMarshal.WideCharArrayToAnsiCharArray(managedArray, pNative, bestFit, throwOnUnmappableChar); } /// <summary> /// Convert ANSI ByVal byte array to UNICODE wide char array, best fit /// </summary> /// <remarks> /// * This version works with array instead to string, it means that the len must be provided and there will be NO NULL to /// terminate the array. /// * The buffer to the UNICODE wide char array must be allocated by the caller. /// </remarks> /// <param name="pNative">Pointer to the ANSI byte array. Could NOT be null.</param> /// <param name="lenInBytes">Maximum buffer size.</param> /// <param name="managedArray">Wide char array that has already been allocated.</param> [CLSCompliant(false)] public static unsafe void AnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray) { PInvokeMarshal.AnsiCharArrayToWideCharArray(pNative, managedArray); } /// <summary> /// Convert a single UNICODE wide char to a single ANSI byte. /// </summary> /// <param name="managedArray">single UNICODE wide char value</param> public static unsafe byte WideCharToAnsiChar(char managedValue, bool bestFit, bool throwOnUnmappableChar) { return PInvokeMarshal.WideCharToAnsiChar(managedValue, bestFit, throwOnUnmappableChar); } /// <summary> /// Convert a single ANSI byte value to a single UNICODE wide char value, best fit. /// </summary> /// <param name="nativeValue">Single ANSI byte value.</param> public static unsafe char AnsiCharToWideChar(byte nativeValue) { return PInvokeMarshal.AnsiCharToWideChar(nativeValue); } /// <summary> /// Convert UNICODE string to ANSI ByVal string. /// </summary> /// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that /// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks> /// <param name="str">Unicode string.</param> /// <param name="pNative"> Allocated buffer where the ansi string must be placed. Could NOT be null. Buffer size must fit str.Length.</param> [CLSCompliant(false)] public static unsafe void StringToByValAnsiString(string str, byte* pNative, int charCount, bool bestFit, bool throwOnUnmappableChar) { PInvokeMarshal.StringToByValAnsiString(str, pNative, charCount, bestFit, throwOnUnmappableChar); } /// <summary> /// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG /// </summary> /// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string. /// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling /// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks> [CLSCompliant(false)] public static unsafe string ByValAnsiStringToString(byte* pchBuffer, int charCount) { return PInvokeMarshal.ByValAnsiStringToString(pchBuffer, charCount); } #endif #if ENABLE_WINRT [MethodImplAttribute(MethodImplOptions.NoInlining)] public static unsafe HSTRING StringToHString(string sourceString) { if (sourceString == null) throw new ArgumentNullException(nameof(sourceString), SR.Null_HString); return StringToHStringInternal(sourceString); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static unsafe HSTRING StringToHStringForField(string sourceString) { #if !RHTESTCL if (sourceString == null) throw new MarshalDirectiveException(SR.BadMarshalField_Null_HString); #endif return StringToHStringInternal(sourceString); } private static unsafe HSTRING StringToHStringInternal(string sourceString) { HSTRING ret; int hr = StringToHStringNoNullCheck(sourceString, &ret); if (hr < 0) throw Marshal.GetExceptionForHR(hr); return ret; } [MethodImplAttribute(MethodImplOptions.NoInlining)] internal static unsafe int StringToHStringNoNullCheck(string sourceString, HSTRING* hstring) { fixed (char* pChars = sourceString) { int hr = ExternalInterop.WindowsCreateString(pChars, (uint)sourceString.Length, (void*)hstring); return hr; } } #endif //ENABLE_WINRT #endregion #region COM marshalling /// <summary> /// Explicit AddRef for RCWs /// You can't call IFoo.AddRef anymore as IFoo no longer derive from IUnknown /// You need to call McgMarshal.AddRef(); /// </summary> /// <remarks> /// Used by prefast MCG plugin (mcgimportpft) only /// </remarks> [CLSCompliant(false)] public static int AddRef(__ComObject obj) { return obj.AddRef(); } /// <summary> /// Explicit Release for RCWs /// You can't call IFoo.Release anymore as IFoo no longer derive from IUnknown /// You need to call McgMarshal.Release(); /// </summary> /// <remarks> /// Used by prefast MCG plugin (mcgimportpft) only /// </remarks> [CLSCompliant(false)] public static int Release(__ComObject obj) { return obj.Release(); } [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe int ComAddRef(IntPtr pComItf) { return CalliIntrinsics.StdCall__AddRef(((__com_IUnknown*)(void*)pComItf)->pVtable-> pfnAddRef, pComItf); } [MethodImpl(MethodImplOptions.NoInlining)] internal static unsafe int ComRelease_StdCall(IntPtr pComItf) { return CalliIntrinsics.StdCall__Release(((__com_IUnknown*)(void*)pComItf)->pVtable-> pfnRelease, pComItf); } /// <summary> /// Inline version of ComRelease /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] //reduces MCG-generated code size public static unsafe int ComRelease(IntPtr pComItf) { IntPtr pRelease = ((__com_IUnknown*)(void*)pComItf)->pVtable->pfnRelease; // Check if the COM object is implemented by PN Interop code, for which we can call directly if (pRelease == AddrOfIntrinsics.AddrOf<AddrOfRelease>(__vtable_IUnknown.Release)) { return __interface_ccw.DirectRelease(pComItf); } // Normal slow path, do not inline return ComRelease_StdCall(pComItf); } [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe int ComSafeRelease(IntPtr pComItf) { if (pComItf != default(IntPtr)) { return ComRelease(pComItf); } return 0; } public static int FinalReleaseComObject(object o) { if (o == null) throw new ArgumentNullException(nameof(o)); __ComObject co = null; // Make sure the obj is an __ComObject. try { co = (__ComObject)o; } catch (InvalidCastException) { throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o)); } co.FinalReleaseSelf(); return 0; } /// <summary> /// Returns the cached WinRT factory RCW under the current context /// </summary> [CLSCompliant(false)] public static unsafe __ComObject GetActivationFactory(string className, RuntimeTypeHandle factoryIntf) { #if ENABLE_MIN_WINRT return FactoryCache.Get().GetActivationFactory(className, factoryIntf); #else throw new PlatformNotSupportedException("GetActivationFactory"); #endif } /// <summary> /// Used by CCW infrastructure code to return the target object from this pointer /// </summary> /// <returns>The target object pointed by this pointer</returns> public static object ThisPointerToTargetObject(IntPtr pUnk) { return ComCallableObject.GetTarget(pUnk); } [CLSCompliant(false)] public static object ComInterfaceToObject_NoUnboxing( IntPtr pComItf, RuntimeTypeHandle interfaceType) { return McgComHelpers.ComInterfaceToObjectInternal( pComItf, interfaceType, default(RuntimeTypeHandle), McgComHelpers.CreateComObjectFlags.SkipTypeResolutionAndUnboxing ); } /// <summary> /// Shared CCW Interface To Object /// </summary> /// <param name="pComItf"></param> /// <param name="interfaceType"></param> /// <param name="classTypeInSignature"></param> /// <returns></returns> [CLSCompliant(false)] public static object ComInterfaceToObject( System.IntPtr pComItf, RuntimeTypeHandle interfaceType, RuntimeTypeHandle classTypeInSignature) { #if ENABLE_MIN_WINRT if (interfaceType.Equals(typeof(object).TypeHandle)) { return McgMarshal.IInspectableToObject(pComItf); } if (interfaceType.Equals(typeof(System.String).TypeHandle)) { return McgMarshal.HStringToString(pComItf); } if (interfaceType.IsComClass()) { RuntimeTypeHandle defaultInterface = interfaceType.GetDefaultInterface(); Debug.Assert(!defaultInterface.IsNull()); return ComInterfaceToObjectInternal(pComItf, defaultInterface, interfaceType); } #endif return ComInterfaceToObjectInternal( pComItf, interfaceType, classTypeInSignature ); } [CLSCompliant(false)] public static object ComInterfaceToObject( IntPtr pComItf, RuntimeTypeHandle interfaceType) { return ComInterfaceToObject(pComItf, interfaceType, default(RuntimeTypeHandle)); } private static object ComInterfaceToObjectInternal( IntPtr pComItf, RuntimeTypeHandle interfaceType, RuntimeTypeHandle classTypeInSignature) { object result = McgComHelpers.ComInterfaceToObjectInternal(pComItf, interfaceType, classTypeInSignature, McgComHelpers.CreateComObjectFlags.None); // // Make sure the type we returned is actually of the right type // NOTE: Don't pass null to IsInstanceOfClass as it'll return false // if (!classTypeInSignature.IsNull() && result != null) { if (!InteropExtensions.IsInstanceOfClass(result, classTypeInSignature)) throw new InvalidCastException(); } return result; } public static unsafe IntPtr ComQueryInterfaceNoThrow(IntPtr pComItf, ref Guid iid) { int hr = 0; return ComQueryInterfaceNoThrow(pComItf, ref iid, out hr); } public static unsafe IntPtr ComQueryInterfaceNoThrow(IntPtr pComItf, ref Guid iid, out int hr) { IntPtr pComIUnk; hr = ComQueryInterfaceWithHR(pComItf, ref iid, out pComIUnk); return pComIUnk; } internal static unsafe int ComQueryInterfaceWithHR(IntPtr pComItf, ref Guid iid, out IntPtr ppv) { IntPtr pComIUnk; int hr; fixed (Guid* unsafe_iid = &iid) { hr = CalliIntrinsics.StdCall__QueryInterface(((__com_IUnknown*)(void*)pComItf)->pVtable-> pfnQueryInterface, pComItf, new IntPtr(unsafe_iid), new IntPtr(&pComIUnk)); } if (hr != 0) { ppv = default(IntPtr); } else { ppv = pComIUnk; } return hr; } /// <summary> /// Helper function to copy vTable to native heap on CoreCLR. /// </summary> /// <typeparam name="T">Vtbl type</typeparam> /// <param name="pVtbl">static v-table field , always a valid pointer</param> /// <param name="pNativeVtbl">Pointer to Vtable on native heap on CoreCLR , on N it's an alias for pVtbl</param> public static unsafe IntPtr GetCCWVTableCopy(void* pVtbl, ref IntPtr pNativeVtbl, int size) { if (pNativeVtbl == default(IntPtr)) { #if CORECLR // On CoreCLR copy vTable to native heap , on N VTable is frozen. IntPtr pv = Marshal.AllocHGlobal(size); int* pSrc = (int*)pVtbl; int* pDest = (int*)pv.ToPointer(); int pSize = sizeof(int); // this should never happen , if a CCW is discarded we never get here. Debug.Assert(size >= pSize); for (int i = 0; i < size; i += pSize) { *pDest++ = *pSrc++; } if (Interlocked.CompareExchange(ref pNativeVtbl, pv, default(IntPtr)) != default(IntPtr)) { // Another thread sneaked-in and updated pNativeVtbl , just use the update from other thread Marshal.FreeHGlobal(pv); } #else // .NET NATIVE // Wrap it in an IntPtr pNativeVtbl = (IntPtr)pVtbl; #endif // CORECLR } return pNativeVtbl; } [CLSCompliant(false)] public static IntPtr ObjectToComInterface( object obj, RuntimeTypeHandle typeHnd) { #if ENABLE_MIN_WINRT if (typeHnd.Equals(typeof(object).TypeHandle)) { return McgMarshal.ObjectToIInspectable(obj); } if (typeHnd.Equals(typeof(System.String).TypeHandle)) { return McgMarshal.StringToHString((string)obj).handle; } if (typeHnd.IsComClass()) { Debug.Assert(obj == null || obj is __ComObject); /// /// This code path should be executed only for WinRT classes /// typeHnd = typeHnd.GetDefaultInterface(); Debug.Assert(!typeHnd.IsNull()); } #endif return McgComHelpers.ObjectToComInterfaceInternal( obj, typeHnd ); } public static IntPtr ObjectToIInspectable(Object obj) { #if ENABLE_MIN_WINRT return ObjectToComInterface(obj, InternalTypes.IInspectable); #else throw new PlatformNotSupportedException("ObjectToIInspectable"); #endif } // This is not a safe function to use for any funtion pointers that do not point // at a static function. This is due to the behavior of shared generics, // where instance function entry points may share the exact same address // but static functions are always represented in delegates with customized // stubs. private static bool DelegateTargetMethodEquals(Delegate del, IntPtr pfn) { RuntimeTypeHandle thDummy; return del.GetFunctionPointer(out thDummy) == pfn; } [MethodImpl(MethodImplOptions.NoInlining)] public static IntPtr DelegateToComInterface(Delegate del, RuntimeTypeHandle typeHnd) { if (del == null) return default(IntPtr); IntPtr stubFunctionAddr = typeHnd.GetDelegateInvokeStub(); object targetObj; // // If the delegate points to the forward stub for the native delegate, // then we want the RCW associated with the native interface. Otherwise, // this is a managed delegate, and we want the CCW associated with it. // if (DelegateTargetMethodEquals(del, stubFunctionAddr)) targetObj = del.Target; else targetObj = del; return McgMarshal.ObjectToComInterface(targetObj, typeHnd); } [MethodImpl(MethodImplOptions.NoInlining)] public static Delegate ComInterfaceToDelegate(IntPtr pComItf, RuntimeTypeHandle typeHnd) { if (pComItf == default(IntPtr)) return null; object obj = ComInterfaceToObject(pComItf, typeHnd, /* classIndexInSignature */ default(RuntimeTypeHandle)); // // If the object we got back was a managed delegate, then we're good. Otherwise, // the object is an RCW for a native delegate, so we need to wrap it with a managed // delegate that invokes the correct stub. // Delegate del = obj as Delegate; if (del == null) { Debug.Assert(obj is __ComObject); IntPtr stubFunctionAddr = typeHnd.GetDelegateInvokeStub(); del = InteropExtensions.CreateDelegate( typeHnd, stubFunctionAddr, obj, /*isStatic:*/ true, /*isVirtual:*/ false, /*isOpen:*/ false); } return del; } /// <summary> /// Marshal array of objects /// </summary> [MethodImplAttribute(MethodImplOptions.NoInlining)] unsafe public static void ObjectArrayToComInterfaceArray(uint len, System.IntPtr* dst, object[] src, RuntimeTypeHandle typeHnd) { for (uint i = 0; i < len; i++) { dst[i] = McgMarshal.ObjectToComInterface(src[i], typeHnd); } } /// <summary> /// Allocate native memory, and then marshal array of objects /// </summary> [MethodImplAttribute(MethodImplOptions.NoInlining)] unsafe public static System.IntPtr* ObjectArrayToComInterfaceArrayAlloc(object[] src, RuntimeTypeHandle typeHnd, out uint len) { System.IntPtr* dst = null; len = 0; if (src != null) { len = (uint)src.Length; dst = (System.IntPtr*)PInvokeMarshal.CoTaskMemAlloc((System.UIntPtr)(len * (sizeof(System.IntPtr)))); for (uint i = 0; i < len; i++) { dst[i] = McgMarshal.ObjectToComInterface(src[i], typeHnd); } } return dst; } /// <summary> /// Get outer IInspectable for managed object deriving from native scenario /// At this point the inner is not created yet - you need the outer first and pass it to the factory /// to create the inner /// </summary> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static IntPtr GetOuterIInspectableForManagedObject(__ComObject managedObject) { ComCallableObject ccw = null; try { // // Create the CCW over the RCW // Note that they are actually both the same object // Base class = inner // Derived class = outer // ccw = new ComCallableObject( managedObject, // The target object = managedObject managedObject // The inner RCW (as __ComObject) = managedObject ); // // Retrieve the outer IInspectable // Pass skipInterfaceCheck = true to avoid redundant checks // return ccw.GetComInterfaceForType_NoCheck(InternalTypes.IInspectable, ref Interop.COM.IID_IInspectable); } finally { // // Free the extra ref count initialized by __native_ccw.Init (to protect the CCW from being collected) // if (ccw != null) ccw.Release(); } } [CLSCompliant(false)] public static unsafe IntPtr ManagedObjectToComInterface(Object obj, RuntimeTypeHandle interfaceType) { return McgComHelpers.ManagedObjectToComInterface(obj, interfaceType); } public static unsafe object IInspectableToObject(IntPtr pComItf) { #if ENABLE_WINRT return ComInterfaceToObject(pComItf, InternalTypes.IInspectable); #else throw new PlatformNotSupportedException("IInspectableToObject"); #endif } public static unsafe IntPtr CreateInstanceFromApp(Guid clsid) { #if ENABLE_WINRT Interop.COM.MULTI_QI results; IntPtr pResults = new IntPtr(&results); fixed (Guid* pIID = &Interop.COM.IID_IUnknown) { Guid* pClsid = &clsid; results.pIID = new IntPtr(pIID); results.pItf = IntPtr.Zero; results.hr = 0; int hr = ExternalInterop.CoCreateInstanceFromApp(pClsid, IntPtr.Zero, 0x15 /* (CLSCTX_SERVER) */, IntPtr.Zero, 1, pResults); if (hr < 0) { throw McgMarshal.GetExceptionForHR(hr, /*isWinRTScenario = */ false); } if (results.hr < 0) { throw McgMarshal.GetExceptionForHR(results.hr, /* isWinRTScenario = */ false); } return results.pItf; } #else throw new PlatformNotSupportedException("CreateInstanceFromApp"); #endif } #endregion #region Testing /// <summary> /// Internal-only method to allow testing of apartment teardown code /// </summary> public static void ReleaseRCWsInCurrentApartment() { ContextEntry.RemoveCurrentContext(); } /// <summary> /// Used by detecting leaks /// Used in prefast MCG only /// </summary> public static int GetTotalComObjectCount() { return ComObjectCache.s_comObjectMap.Count; } /// <summary> /// Used by detecting and dumping leaks /// Used in prefast MCG only /// </summary> public static IEnumerable<__ComObject> GetAllComObjects() { List<__ComObject> list = new List<__ComObject>(); for (int i = 0; i < ComObjectCache.s_comObjectMap.GetMaxCount(); ++i) { IntPtr pHandle = default(IntPtr); if (ComObjectCache.s_comObjectMap.GetValue(i, ref pHandle) && (pHandle != default(IntPtr))) { GCHandle handle = GCHandle.FromIntPtr(pHandle); list.Add(InteropExtensions.UncheckedCast<__ComObject>(handle.Target)); } } return list; } #endregion /// <summary> /// This method returns HR for the exception being thrown. /// 1. On Windows8+, WinRT scenarios we do the following. /// a. Check whether the exception has any IRestrictedErrorInfo associated with it. /// If so, it means that this exception was actually caused by a native exception in which case we do simply use the same /// message and stacktrace. /// b. If not, this is actually a managed exception and in this case we RoOriginateLanguageException with the msg, hresult and the IErrorInfo /// aasociated with the managed exception. This helps us to retrieve the same exception in case it comes back to native. /// 2. On win8 and for classic COM scenarios. /// a. We create IErrorInfo for the given Exception object and SetErrorInfo with the given IErrorInfo. /// </summary> /// <param name="ex"></param> [MethodImpl(MethodImplOptions.NoInlining)] public static int GetHRForExceptionWinRT(Exception ex) { #if ENABLE_WINRT return ExceptionHelpers.GetHRForExceptionWithErrorPropogationNoThrow(ex, true); #else // TODO : ExceptionHelpers should be platform specific , move it to // seperate source files return 0; //return Marshal.GetHRForException(ex); #endif } [MethodImpl(MethodImplOptions.NoInlining)] public static int GetHRForException(Exception ex) { #if ENABLE_WINRT return ExceptionHelpers.GetHRForExceptionWithErrorPropogationNoThrow(ex, false); #else return ex.HResult; #endif } [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowOnExternalCallFailed(int hr, System.RuntimeTypeHandle typeHnd) { bool isWinRTScenario #if ENABLE_WINRT = typeHnd.IsSupportIInspectable(); #else = false; #endif throw McgMarshal.GetExceptionForHR(hr, isWinRTScenario); } /// <summary> /// This method returns a new Exception object given the HR value. /// </summary> /// <param name="hr"></param> /// <param name="isWinRTScenario"></param> public static Exception GetExceptionForHR(int hr, bool isWinRTScenario) { #if ENABLE_WINRT return ExceptionHelpers.GetExceptionForHRInternalNoThrow(hr, isWinRTScenario, !isWinRTScenario); #elif CORECLR return Marshal.GetExceptionForHR(hr); #else return new COMException(hr.ToString(), hr); #endif } #region Shared templates #if ENABLE_MIN_WINRT public static void CleanupNative<T>(IntPtr pObject) { if (typeof(T) == typeof(string)) { global::System.Runtime.InteropServices.McgMarshal.FreeHString(pObject); } else { global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(pObject); } } #endif #endregion #if ENABLE_MIN_WINRT [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe IntPtr ActivateInstance(string typeName) { __ComObject target = McgMarshal.GetActivationFactory( typeName, InternalTypes.IActivationFactoryInternal ); IntPtr pIActivationFactoryInternalItf = target.QueryInterface_NoAddRef_Internal( InternalTypes.IActivationFactoryInternal, /* cacheOnly= */ false, /* throwOnQueryInterfaceFailure= */ true ); __com_IActivationFactoryInternal* pIActivationFactoryInternal = (__com_IActivationFactoryInternal*)pIActivationFactoryInternalItf; IntPtr pResult = default(IntPtr); int hr = CalliIntrinsics.StdCall<int>( pIActivationFactoryInternal->pVtable->pfnActivateInstance, pIActivationFactoryInternal, &pResult ); GC.KeepAlive(target); if (hr < 0) { throw McgMarshal.GetExceptionForHR(hr, /* isWinRTScenario = */ true); } return pResult; } #endif [MethodImpl(MethodImplOptions.NoInlining)] public static IntPtr GetInterface( __ComObject obj, RuntimeTypeHandle typeHnd) { return obj.QueryInterface_NoAddRef_Internal( typeHnd); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static object GetDynamicAdapter(__ComObject obj, RuntimeTypeHandle requestedType, RuntimeTypeHandle existingType) { return obj.GetDynamicAdapter(requestedType, existingType); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static object GetDynamicAdapter(__ComObject obj, RuntimeTypeHandle requestedType) { return obj.GetDynamicAdapter(requestedType, default(RuntimeTypeHandle)); } #region "PInvoke Delegate" public static IntPtr GetStubForPInvokeDelegate(RuntimeTypeHandle delegateType, Delegate dele) { #if CORECLR throw new NotSupportedException(); #else return PInvokeMarshal.GetStubForPInvokeDelegate(dele); #endif } /// <summary> /// Retrieve the corresponding P/invoke instance from the stub /// </summary> public static Delegate GetPInvokeDelegateForStub(IntPtr pStub, RuntimeTypeHandle delegateType) { #if CORECLR if (pStub == IntPtr.Zero) return null; McgPInvokeDelegateData pInvokeDelegateData; if (!McgModuleManager.GetPInvokeDelegateData(delegateType, out pInvokeDelegateData)) { return null; } return CalliIntrinsics.Call__Delegate( pInvokeDelegateData.ForwardDelegateCreationStub, pStub ); #else return PInvokeMarshal.GetPInvokeDelegateForStub(pStub, delegateType); #endif } /// <summary> /// Retrieves the function pointer for the current open static delegate that is being called /// </summary> public static IntPtr GetCurrentCalleeOpenStaticDelegateFunctionPointer() { #if RHTESTCL || CORECLR || CORERT throw new NotSupportedException(); #else return PInvokeMarshal.GetCurrentCalleeOpenStaticDelegateFunctionPointer(); #endif } /// <summary> /// Retrieves the current delegate that is being called /// </summary> public static T GetCurrentCalleeDelegate<T>() where T : class // constraint can't be System.Delegate { #if RHTESTCL || CORECLR || CORERT throw new NotSupportedException(); #else return PInvokeMarshal.GetCurrentCalleeDelegate<T>(); #endif } #endregion } /// <summary> /// McgMarshal helpers exposed to be used by MCG /// </summary> public static partial class McgMarshal { public static object UnboxIfBoxed(object target) { return UnboxIfBoxed(target, null); } public static object UnboxIfBoxed(object target, string className) { // // If it is a managed wrapper, unbox it // object unboxedObj = McgComHelpers.UnboxManagedWrapperIfBoxed(target); if (unboxedObj != target) return unboxedObj; if (className == null) className = System.Runtime.InteropServices.McgComHelpers.GetRuntimeClassName(target); if (!String.IsNullOrEmpty(className)) { IntPtr unboxingStub; if (McgModuleManager.TryGetUnboxingStub(className, out unboxingStub)) { object ret = CalliIntrinsics.Call<object>(unboxingStub, target); if (ret != null) return ret; } #if ENABLE_WINRT else if(McgModuleManager.UseDynamicInterop) { BoxingInterfaceKind boxingInterfaceKind; RuntimeTypeHandle[] genericTypeArgument; if (DynamicInteropBoxingHelpers.TryGetBoxingArgumentTypeHandleFromString(className, out boxingInterfaceKind, out genericTypeArgument)) { Debug.Assert(target is __ComObject); return DynamicInteropBoxingHelpers.Unboxing(boxingInterfaceKind, genericTypeArgument, target); } } #endif } return null; } internal static object BoxIfBoxable(object target) { return BoxIfBoxable(target, default(RuntimeTypeHandle)); } /// <summary> /// Given a boxed value type, return a wrapper supports the IReference interface /// </summary> /// <param name="typeHandleOverride"> /// You might want to specify how to box this. For example, any object[] derived array could /// potentially boxed as object[] if everything else fails /// </param> internal static object BoxIfBoxable(object target, RuntimeTypeHandle typeHandleOverride) { RuntimeTypeHandle expectedTypeHandle = typeHandleOverride; if (expectedTypeHandle.Equals(default(RuntimeTypeHandle))) expectedTypeHandle = target.GetTypeHandle(); RuntimeTypeHandle boxingWrapperType; IntPtr boxingStub; int boxingPropertyType; if (McgModuleManager.TryGetBoxingWrapperType(expectedTypeHandle, target, out boxingWrapperType, out boxingPropertyType, out boxingStub)) { if (!boxingWrapperType.IsInvalid()) { // // IReference<T> / IReferenceArray<T> / IKeyValuePair<K, V> // All these scenarios require a managed wrapper // // Allocate the object object refImplType = InteropExtensions.RuntimeNewObject(boxingWrapperType); if (boxingPropertyType >= 0) { Debug.Assert(refImplType is BoxedValue); BoxedValue boxed = InteropExtensions.UncheckedCast<BoxedValue>(refImplType); // Call ReferenceImpl<T>.Initialize(obj, type); boxed.Initialize(target, boxingPropertyType); } else { Debug.Assert(refImplType is BoxedKeyValuePair); BoxedKeyValuePair boxed = InteropExtensions.UncheckedCast<BoxedKeyValuePair>(refImplType); // IKeyValuePair<,>, call CLRIKeyValuePairImpl<K,V>.Initialize(object obj); // IKeyValuePair<,>[], call CLRIKeyValuePairArrayImpl<K,V>.Initialize(object obj); refImplType = boxed.Initialize(target); } return refImplType; } else { // // General boxing for projected types, such as System.Uri // return CalliIntrinsics.Call<object>(boxingStub, target); } } return null; } } }
/* Copyright (c) 2014, Lars Brubaker All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using MatterHackers.Agg.Image; using MatterHackers.Agg.Platform; using MatterHackers.Agg.RasterizerScanline; using MatterHackers.Agg.UI; using MatterHackers.Agg.UI.Examples; using MatterHackers.Agg.VertexSource; namespace MatterHackers.Agg { internal class pattern_src_brightness_to_alpha_RGBA_Bytes : ImageProxy { private static byte[] brightness_to_alpha = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 251, 251, 251, 251, 251, 251, 251, 251, 251, 250, 250, 250, 250, 250, 250, 250, 250, 249, 249, 249, 249, 249, 249, 249, 248, 248, 248, 248, 248, 248, 248, 247, 247, 247, 247, 247, 246, 246, 246, 246, 246, 246, 245, 245, 245, 245, 245, 244, 244, 244, 244, 243, 243, 243, 243, 243, 242, 242, 242, 242, 241, 241, 241, 241, 240, 240, 240, 239, 239, 239, 239, 238, 238, 238, 238, 237, 237, 237, 236, 236, 236, 235, 235, 235, 234, 234, 234, 233, 233, 233, 232, 232, 232, 231, 231, 230, 230, 230, 229, 229, 229, 228, 228, 227, 227, 227, 226, 226, 225, 225, 224, 224, 224, 223, 223, 222, 222, 221, 221, 220, 220, 219, 219, 219, 218, 218, 217, 217, 216, 216, 215, 214, 214, 213, 213, 212, 212, 211, 211, 210, 210, 209, 209, 208, 207, 207, 206, 206, 205, 204, 204, 203, 203, 202, 201, 201, 200, 200, 199, 198, 198, 197, 196, 196, 195, 194, 194, 193, 192, 192, 191, 190, 190, 189, 188, 188, 187, 186, 186, 185, 184, 183, 183, 182, 181, 180, 180, 179, 178, 177, 177, 176, 175, 174, 174, 173, 172, 171, 171, 170, 169, 168, 167, 166, 166, 165, 164, 163, 162, 162, 161, 160, 159, 158, 157, 156, 156, 155, 154, 153, 152, 151, 150, 149, 148, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 132, 131, 130, 129, 128, 128, 127, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 105, 104, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 91, 90, 89, 88, 87, 86, 85, 84, 82, 81, 80, 79, 78, 77, 75, 74, 73, 72, 71, 70, 69, 67, 66, 65, 64, 63, 61, 60, 59, 58, 57, 56, 54, 53, 52, 51, 50, 48, 47, 46, 45, 44, 42, 41, 40, 39, 37, 36, 35, 34, 33, 31, 30, 29, 28, 27, 25, 24, 23, 22, 20, 19, 18, 17, 15, 14, 13, 12, 11, 9, 8, 7, 6, 4, 3, 2, 1 }; public pattern_src_brightness_to_alpha_RGBA_Bytes(ImageBuffer rb) : base(new ImageBuffer(rb, new BlenderBGRA())) { } public override Color GetPixel(int x, int y) { Color c = linkedImage.GetPixel(x, y); c.Alpha0To255 = brightness_to_alpha[c.Red0To255 + c.Green0To255 + c.Blue0To255]; return c; } }; public class line_patterns_application : GuiWidget, IDemoApp { private Color m_ctrl_color; private CheckBox m_approximation_method; private bezier_ctrl m_curve1 = new bezier_ctrl(); private bezier_ctrl m_curve2 = new bezier_ctrl(); private bezier_ctrl m_curve3 = new bezier_ctrl(); private bezier_ctrl m_curve4 = new bezier_ctrl(); private bezier_ctrl m_curve5 = new bezier_ctrl(); private bezier_ctrl m_curve6 = new bezier_ctrl(); private bezier_ctrl m_curve7 = new bezier_ctrl(); private bezier_ctrl m_curve8 = new bezier_ctrl(); private bezier_ctrl m_curve9 = new bezier_ctrl(); private Slider m_scale_x; private Slider m_start_x; public static ImageBuffer rbuf_img0 = new ImageBuffer(); public static ImageBuffer rbuf_img1 = new ImageBuffer(); public static ImageBuffer rbuf_img2 = new ImageBuffer(); public static ImageBuffer rbuf_img3 = new ImageBuffer(); public static ImageBuffer rbuf_img4 = new ImageBuffer(); public static ImageBuffer rbuf_img5 = new ImageBuffer(); public static ImageBuffer rbuf_img6 = new ImageBuffer(); public static ImageBuffer rbuf_img7 = new ImageBuffer(); public static ImageBuffer rbuf_img8 = new ImageBuffer(); static line_patterns_application() { var ImageIO = AggContext.ImageIO; if (!ImageIO.LoadImageData("1.bmp", line_patterns_application.rbuf_img0) || !ImageIO.LoadImageData("2.bmp", line_patterns_application.rbuf_img1) || !ImageIO.LoadImageData("3.bmp", line_patterns_application.rbuf_img2) || !ImageIO.LoadImageData("4.bmp", line_patterns_application.rbuf_img3) || !ImageIO.LoadImageData("5.bmp", line_patterns_application.rbuf_img4) || !ImageIO.LoadImageData("6.bmp", line_patterns_application.rbuf_img5) || !ImageIO.LoadImageData("7.bmp", line_patterns_application.rbuf_img6) || !ImageIO.LoadImageData("8.bmp", line_patterns_application.rbuf_img7) || !ImageIO.LoadImageData("9.bmp", line_patterns_application.rbuf_img8)) { String buf = "There must be files 1%s...9%s\n" + "Download and unzip:\n" + "http://www.antigrain.com/line_patterns.bmp.zip\n" + "or\n" + "http://www.antigrain.com/line_patterns.ppm.tar.gz\n"; throw new System.Exception(buf); } } public line_patterns_application() { AnchorAll(); m_ctrl_color = new Color(0, 0.3, 0.5, 0.3); m_scale_x = new Slider(5.0, 5.0, 240.0, 12.0); m_start_x = new Slider(250.0, 5.0, 495.0, 12.0); m_approximation_method = new CheckBox(10, 30, "Approximation Method = curve_div"); m_curve1.line_color(m_ctrl_color); m_curve2.line_color(m_ctrl_color); m_curve3.line_color(m_ctrl_color); m_curve4.line_color(m_ctrl_color); m_curve5.line_color(m_ctrl_color); m_curve6.line_color(m_ctrl_color); m_curve7.line_color(m_ctrl_color); m_curve8.line_color(m_ctrl_color); m_curve9.line_color(m_ctrl_color); m_curve1.curve(64, 19, 14, 126, 118, 266, 19, 265); m_curve2.curve(112, 113, 178, 32, 200, 132, 125, 438); m_curve3.curve(401, 24, 326, 149, 285, 11, 177, 77); m_curve4.curve(188, 427, 129, 295, 19, 283, 25, 410); m_curve5.curve(451, 346, 302, 218, 265, 441, 459, 400); m_curve6.curve(454, 198, 14, 13, 220, 291, 483, 283); m_curve7.curve(301, 398, 355, 231, 209, 211, 170, 353); m_curve8.curve(484, 101, 222, 33, 486, 435, 487, 138); m_curve9.curve(143, 147, 11, 45, 83, 427, 132, 197); AddChild(m_curve1); AddChild(m_curve2); AddChild(m_curve3); AddChild(m_curve4); AddChild(m_curve5); AddChild(m_curve6); AddChild(m_curve7); AddChild(m_curve8); AddChild(m_curve9); AddChild(m_approximation_method); m_scale_x.Text = "Scale X=%.2f"; m_scale_x.SetRange(0.2, 3.0); m_scale_x.Value = 1.0; AddChild(m_scale_x); m_start_x.Text = "Start X=%.2f"; m_start_x.SetRange(0.0, 10.0); m_start_x.Value = 0.0; AddChild(m_start_x); m_approximation_method.CheckedStateChanged += m_approximation_method_CheckedStateChanged; } public string Title { get; } = "Line Patterns"; public string DemoCategory { get; } = "Vector"; public string DemoDescription { get; } = "AGG Example. Drawing Lines with Image Patterns"; private void m_approximation_method_CheckedStateChanged(object sender, EventArgs e) { Curves.CurveApproximationMethod method = Curves.CurveApproximationMethod.curve_div; if (m_approximation_method.Checked) { method = Curves.CurveApproximationMethod.curve_inc; m_approximation_method.Text = "Approximation Method = curve_inc"; } else { m_approximation_method.Text = "Approximation Method = curve_div"; } m_curve1.curve().approximation_method(method); m_curve2.curve().approximation_method(method); m_curve3.curve().approximation_method(method); m_curve4.curve().approximation_method(method); m_curve5.curve().approximation_method(method); m_curve6.curve().approximation_method(method); m_curve7.curve().approximation_method(method); m_curve8.curve().approximation_method(method); m_curve9.curve().approximation_method(method); } private void draw_curve(line_image_pattern patt, rasterizer_outline_aa ras, ImageLineRenderer ren, pattern_src_brightness_to_alpha_RGBA_Bytes src, IVertexSource vs) { patt.create(src); ren.scale_x(m_scale_x.Value); ren.start_x(m_start_x.Value); ras.add_path(vs); } public override void OnDraw(Graphics2D graphics2D) { ImageClippingProxy ren_base = new ImageClippingProxy(graphics2D.DestImage); ren_base.clear(new ColorF(1.0, 1.0, .95)); ScanlineRasterizer ras = new ScanlineRasterizer(); ScanlineCachePacked8 sl = new ScanlineCachePacked8(); // Pattern source. Must have an interface: // width() const // height() const // pixel(int x, int y) const // Any agg::renderer_base<> or derived // is good for the use as a source. //----------------------------------- pattern_src_brightness_to_alpha_RGBA_Bytes p1 = new pattern_src_brightness_to_alpha_RGBA_Bytes(rbuf_img0); pattern_src_brightness_to_alpha_RGBA_Bytes p2 = new pattern_src_brightness_to_alpha_RGBA_Bytes(rbuf_img1); pattern_src_brightness_to_alpha_RGBA_Bytes p3 = new pattern_src_brightness_to_alpha_RGBA_Bytes(rbuf_img2); pattern_src_brightness_to_alpha_RGBA_Bytes p4 = new pattern_src_brightness_to_alpha_RGBA_Bytes(rbuf_img3); pattern_src_brightness_to_alpha_RGBA_Bytes p5 = new pattern_src_brightness_to_alpha_RGBA_Bytes(rbuf_img4); pattern_src_brightness_to_alpha_RGBA_Bytes p6 = new pattern_src_brightness_to_alpha_RGBA_Bytes(rbuf_img5); pattern_src_brightness_to_alpha_RGBA_Bytes p7 = new pattern_src_brightness_to_alpha_RGBA_Bytes(rbuf_img6); pattern_src_brightness_to_alpha_RGBA_Bytes p8 = new pattern_src_brightness_to_alpha_RGBA_Bytes(rbuf_img7); pattern_src_brightness_to_alpha_RGBA_Bytes p9 = new pattern_src_brightness_to_alpha_RGBA_Bytes(rbuf_img8); //pattern_filter_bilinear_RGBA_Bytes fltr = new pattern_filter_bilinear_RGBA_Bytes(); // Filtering functor // agg::line_image_pattern is the main container for the patterns. It creates // a copy of the patterns extended according to the needs of the filter. // agg::line_image_pattern can operate with arbitrary image width, but if the // width of the pattern is power of 2, it's better to use the modified // version agg::line_image_pattern_pow2 because it works about 15-25 percent // faster than agg::line_image_pattern (because of using simple masking instead // of expensive '%' operation). //-- Create with specifying the source //-- Create uninitialized and set the source line_image_pattern patt = new line_image_pattern(new pattern_filter_bilinear_RGBA_Bytes()); ImageLineRenderer ren_img = new ImageLineRenderer(ren_base, patt); rasterizer_outline_aa ras_img = new rasterizer_outline_aa(ren_img); draw_curve(patt, ras_img, ren_img, p1, m_curve1.curve()); /* draw_curve(patt, ras_img, ren_img, p2, m_curve2.curve()); draw_curve(patt, ras_img, ren_img, p3, m_curve3.curve()); draw_curve(patt, ras_img, ren_img, p4, m_curve4.curve()); draw_curve(patt, ras_img, ren_img, p5, m_curve5.curve()); draw_curve(patt, ras_img, ren_img, p6, m_curve6.curve()); draw_curve(patt, ras_img, ren_img, p7, m_curve7.curve()); draw_curve(patt, ras_img, ren_img, p8, m_curve8.curve()); draw_curve(patt, ras_img, ren_img, p9, m_curve9.curve()); */ base.OnDraw(graphics2D); } [STAThread] public static void Main(string[] args) { var demoWidget = new line_patterns_application(); var systemWindow = new SystemWindow(500, 450); systemWindow.Title = demoWidget.Title; systemWindow.AddChild(demoWidget); systemWindow.ShowAsSystemWindow(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Apress.Recipes.WebApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; namespace Org.BouncyCastle.Crypto.Engines { /** * A class that provides CAST key encryption operations, * such as encoding data and generating keys. * * All the algorithms herein are from the Internet RFC's * * RFC2144 - Cast5 (64bit block, 40-128bit key) * RFC2612 - CAST6 (128bit block, 128-256bit key) * * and implement a simplified cryptography interface. */ public class Cast5Engine : IBlockCipher { internal static readonly uint[] S1 = { 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf }, S2 = { 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1 }, S3 = { 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783 }, S4 = { 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2 }, S5 = { 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4 }, S6 = { 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f }, S7 = { 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3 }, S8 = { 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e }; //==================================== // Useful constants //==================================== internal static readonly int MAX_ROUNDS = 16; internal static readonly int RED_ROUNDS = 12; private const int BLOCK_SIZE = 8; // bytes = 64 bits private int[] _Kr = new int[17]; // the rotating round key private uint[] _Km = new uint[17]; // the masking round key private bool _encrypting; private byte[] _workingKey; private int _rounds = MAX_ROUNDS; public Cast5Engine() { } /** * initialise a CAST cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { if (!(parameters is KeyParameter)) throw new ArgumentException("Invalid parameter passed to "+ AlgorithmName +" init - " + parameters.GetType().ToString()); _encrypting = forEncryption; _workingKey = ((KeyParameter)parameters).GetKey(); SetKey(_workingKey); } public virtual string AlgorithmName { get { return "CAST5"; } } public virtual bool IsPartialBlockOkay { get { return false; } } public virtual int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { int blockSize = GetBlockSize(); if (_workingKey == null) throw new InvalidOperationException(AlgorithmName + " not initialised"); if ((inOff + blockSize) > input.Length) throw new DataLengthException("Input buffer too short"); if ((outOff + blockSize) > output.Length) throw new DataLengthException("Output buffer too short"); if (_encrypting) { return EncryptBlock(input, inOff, output, outOff); } else { return DecryptBlock(input, inOff, output, outOff); } } public virtual void Reset() { } public virtual int GetBlockSize() { return BLOCK_SIZE; } //================================== // Private Implementation //================================== /* * Creates the subkeys using the same nomenclature * as described in RFC2144. * * See section 2.4 */ internal virtual void SetKey(byte[] key) { /* * Determine the key size here, if required * * if keysize <= 80bits, use 12 rounds instead of 16 * if keysize < 128bits, pad with 0 * * Typical key sizes => 40, 64, 80, 128 */ if (key.Length < 11) { _rounds = RED_ROUNDS; } int [] z = new int[16]; int [] x = new int[16]; uint z03, z47, z8B, zCF; uint x03, x47, x8B, xCF; /* copy the key into x */ for (int i=0; i< key.Length; i++) { x[i] = (int)(key[i] & 0xff); } /* * This will look different because the selection of * bytes from the input key I've already chosen the * correct int. */ x03 = IntsTo32bits(x, 0x0); x47 = IntsTo32bits(x, 0x4); x8B = IntsTo32bits(x, 0x8); xCF = IntsTo32bits(x, 0xC); z03 = x03 ^S5[x[0xD]] ^S6[x[0xF]] ^S7[x[0xC]] ^S8[x[0xE]] ^S7[x[0x8]]; Bits32ToInts(z03, z, 0x0); z47 = x8B ^S5[z[0x0]] ^S6[z[0x2]] ^S7[z[0x1]] ^S8[z[0x3]] ^S8[x[0xA]]; Bits32ToInts(z47, z, 0x4); z8B = xCF ^S5[z[0x7]] ^S6[z[0x6]] ^S7[z[0x5]] ^S8[z[0x4]] ^S5[x[0x9]]; Bits32ToInts(z8B, z, 0x8); zCF = x47 ^S5[z[0xA]] ^S6[z[0x9]] ^S7[z[0xB]] ^S8[z[0x8]] ^S6[x[0xB]]; Bits32ToInts(zCF, z, 0xC); _Km[ 1]= S5[z[0x8]] ^ S6[z[0x9]] ^ S7[z[0x7]] ^ S8[z[0x6]] ^ S5[z[0x2]]; _Km[ 2]= S5[z[0xA]] ^ S6[z[0xB]] ^ S7[z[0x5]] ^ S8[z[0x4]] ^ S6[z[0x6]]; _Km[ 3]= S5[z[0xC]] ^ S6[z[0xD]] ^ S7[z[0x3]] ^ S8[z[0x2]] ^ S7[z[0x9]]; _Km[ 4]= S5[z[0xE]] ^ S6[z[0xF]] ^ S7[z[0x1]] ^ S8[z[0x0]] ^ S8[z[0xC]]; z03 = IntsTo32bits(z, 0x0); z47 = IntsTo32bits(z, 0x4); z8B = IntsTo32bits(z, 0x8); zCF = IntsTo32bits(z, 0xC); x03 = z8B ^S5[z[0x5]] ^S6[z[0x7]] ^S7[z[0x4]] ^S8[z[0x6]] ^S7[z[0x0]]; Bits32ToInts(x03, x, 0x0); x47 = z03 ^S5[x[0x0]] ^S6[x[0x2]] ^S7[x[0x1]] ^S8[x[0x3]] ^S8[z[0x2]]; Bits32ToInts(x47, x, 0x4); x8B = z47 ^S5[x[0x7]] ^S6[x[0x6]] ^S7[x[0x5]] ^S8[x[0x4]] ^S5[z[0x1]]; Bits32ToInts(x8B, x, 0x8); xCF = zCF ^S5[x[0xA]] ^S6[x[0x9]] ^S7[x[0xB]] ^S8[x[0x8]] ^S6[z[0x3]]; Bits32ToInts(xCF, x, 0xC); _Km[ 5]= S5[x[0x3]] ^ S6[x[0x2]] ^ S7[x[0xC]] ^ S8[x[0xD]] ^ S5[x[0x8]]; _Km[ 6]= S5[x[0x1]] ^ S6[x[0x0]] ^ S7[x[0xE]] ^ S8[x[0xF]] ^ S6[x[0xD]]; _Km[ 7]= S5[x[0x7]] ^ S6[x[0x6]] ^ S7[x[0x8]] ^ S8[x[0x9]] ^ S7[x[0x3]]; _Km[ 8]= S5[x[0x5]] ^ S6[x[0x4]] ^ S7[x[0xA]] ^ S8[x[0xB]] ^ S8[x[0x7]]; x03 = IntsTo32bits(x, 0x0); x47 = IntsTo32bits(x, 0x4); x8B = IntsTo32bits(x, 0x8); xCF = IntsTo32bits(x, 0xC); z03 = x03 ^S5[x[0xD]] ^S6[x[0xF]] ^S7[x[0xC]] ^S8[x[0xE]] ^S7[x[0x8]]; Bits32ToInts(z03, z, 0x0); z47 = x8B ^S5[z[0x0]] ^S6[z[0x2]] ^S7[z[0x1]] ^S8[z[0x3]] ^S8[x[0xA]]; Bits32ToInts(z47, z, 0x4); z8B = xCF ^S5[z[0x7]] ^S6[z[0x6]] ^S7[z[0x5]] ^S8[z[0x4]] ^S5[x[0x9]]; Bits32ToInts(z8B, z, 0x8); zCF = x47 ^S5[z[0xA]] ^S6[z[0x9]] ^S7[z[0xB]] ^S8[z[0x8]] ^S6[x[0xB]]; Bits32ToInts(zCF, z, 0xC); _Km[ 9]= S5[z[0x3]] ^ S6[z[0x2]] ^ S7[z[0xC]] ^ S8[z[0xD]] ^ S5[z[0x9]]; _Km[10]= S5[z[0x1]] ^ S6[z[0x0]] ^ S7[z[0xE]] ^ S8[z[0xF]] ^ S6[z[0xc]]; _Km[11]= S5[z[0x7]] ^ S6[z[0x6]] ^ S7[z[0x8]] ^ S8[z[0x9]] ^ S7[z[0x2]]; _Km[12]= S5[z[0x5]] ^ S6[z[0x4]] ^ S7[z[0xA]] ^ S8[z[0xB]] ^ S8[z[0x6]]; z03 = IntsTo32bits(z, 0x0); z47 = IntsTo32bits(z, 0x4); z8B = IntsTo32bits(z, 0x8); zCF = IntsTo32bits(z, 0xC); x03 = z8B ^S5[z[0x5]] ^S6[z[0x7]] ^S7[z[0x4]] ^S8[z[0x6]] ^S7[z[0x0]]; Bits32ToInts(x03, x, 0x0); x47 = z03 ^S5[x[0x0]] ^S6[x[0x2]] ^S7[x[0x1]] ^S8[x[0x3]] ^S8[z[0x2]]; Bits32ToInts(x47, x, 0x4); x8B = z47 ^S5[x[0x7]] ^S6[x[0x6]] ^S7[x[0x5]] ^S8[x[0x4]] ^S5[z[0x1]]; Bits32ToInts(x8B, x, 0x8); xCF = zCF ^S5[x[0xA]] ^S6[x[0x9]] ^S7[x[0xB]] ^S8[x[0x8]] ^S6[z[0x3]]; Bits32ToInts(xCF, x, 0xC); _Km[13]= S5[x[0x8]] ^ S6[x[0x9]] ^ S7[x[0x7]] ^ S8[x[0x6]] ^ S5[x[0x3]]; _Km[14]= S5[x[0xA]] ^ S6[x[0xB]] ^ S7[x[0x5]] ^ S8[x[0x4]] ^ S6[x[0x7]]; _Km[15]= S5[x[0xC]] ^ S6[x[0xD]] ^ S7[x[0x3]] ^ S8[x[0x2]] ^ S7[x[0x8]]; _Km[16]= S5[x[0xE]] ^ S6[x[0xF]] ^ S7[x[0x1]] ^ S8[x[0x0]] ^ S8[x[0xD]]; x03 = IntsTo32bits(x, 0x0); x47 = IntsTo32bits(x, 0x4); x8B = IntsTo32bits(x, 0x8); xCF = IntsTo32bits(x, 0xC); z03 = x03 ^S5[x[0xD]] ^S6[x[0xF]] ^S7[x[0xC]] ^S8[x[0xE]] ^S7[x[0x8]]; Bits32ToInts(z03, z, 0x0); z47 = x8B ^S5[z[0x0]] ^S6[z[0x2]] ^S7[z[0x1]] ^S8[z[0x3]] ^S8[x[0xA]]; Bits32ToInts(z47, z, 0x4); z8B = xCF ^S5[z[0x7]] ^S6[z[0x6]] ^S7[z[0x5]] ^S8[z[0x4]] ^S5[x[0x9]]; Bits32ToInts(z8B, z, 0x8); zCF = x47 ^S5[z[0xA]] ^S6[z[0x9]] ^S7[z[0xB]] ^S8[z[0x8]] ^S6[x[0xB]]; Bits32ToInts(zCF, z, 0xC); _Kr[ 1]=(int)((S5[z[0x8]]^S6[z[0x9]]^S7[z[0x7]]^S8[z[0x6]] ^ S5[z[0x2]])&0x1f); _Kr[ 2]=(int)((S5[z[0xA]]^S6[z[0xB]]^S7[z[0x5]]^S8[z[0x4]] ^ S6[z[0x6]])&0x1f); _Kr[ 3]=(int)((S5[z[0xC]]^S6[z[0xD]]^S7[z[0x3]]^S8[z[0x2]] ^ S7[z[0x9]])&0x1f); _Kr[ 4]=(int)((S5[z[0xE]]^S6[z[0xF]]^S7[z[0x1]]^S8[z[0x0]] ^ S8[z[0xC]])&0x1f); z03 = IntsTo32bits(z, 0x0); z47 = IntsTo32bits(z, 0x4); z8B = IntsTo32bits(z, 0x8); zCF = IntsTo32bits(z, 0xC); x03 = z8B ^S5[z[0x5]] ^S6[z[0x7]] ^S7[z[0x4]] ^S8[z[0x6]] ^S7[z[0x0]]; Bits32ToInts(x03, x, 0x0); x47 = z03 ^S5[x[0x0]] ^S6[x[0x2]] ^S7[x[0x1]] ^S8[x[0x3]] ^S8[z[0x2]]; Bits32ToInts(x47, x, 0x4); x8B = z47 ^S5[x[0x7]] ^S6[x[0x6]] ^S7[x[0x5]] ^S8[x[0x4]] ^S5[z[0x1]]; Bits32ToInts(x8B, x, 0x8); xCF = zCF ^S5[x[0xA]] ^S6[x[0x9]] ^S7[x[0xB]] ^S8[x[0x8]] ^S6[z[0x3]]; Bits32ToInts(xCF, x, 0xC); _Kr[ 5]=(int)((S5[x[0x3]]^S6[x[0x2]]^S7[x[0xC]]^S8[x[0xD]]^S5[x[0x8]])&0x1f); _Kr[ 6]=(int)((S5[x[0x1]]^S6[x[0x0]]^S7[x[0xE]]^S8[x[0xF]]^S6[x[0xD]])&0x1f); _Kr[ 7]=(int)((S5[x[0x7]]^S6[x[0x6]]^S7[x[0x8]]^S8[x[0x9]]^S7[x[0x3]])&0x1f); _Kr[ 8]=(int)((S5[x[0x5]]^S6[x[0x4]]^S7[x[0xA]]^S8[x[0xB]]^S8[x[0x7]])&0x1f); x03 = IntsTo32bits(x, 0x0); x47 = IntsTo32bits(x, 0x4); x8B = IntsTo32bits(x, 0x8); xCF = IntsTo32bits(x, 0xC); z03 = x03 ^S5[x[0xD]] ^S6[x[0xF]] ^S7[x[0xC]] ^S8[x[0xE]] ^S7[x[0x8]]; Bits32ToInts(z03, z, 0x0); z47 = x8B ^S5[z[0x0]] ^S6[z[0x2]] ^S7[z[0x1]] ^S8[z[0x3]] ^S8[x[0xA]]; Bits32ToInts(z47, z, 0x4); z8B = xCF ^S5[z[0x7]] ^S6[z[0x6]] ^S7[z[0x5]] ^S8[z[0x4]] ^S5[x[0x9]]; Bits32ToInts(z8B, z, 0x8); zCF = x47 ^S5[z[0xA]] ^S6[z[0x9]] ^S7[z[0xB]] ^S8[z[0x8]] ^S6[x[0xB]]; Bits32ToInts(zCF, z, 0xC); _Kr[ 9]=(int)((S5[z[0x3]]^S6[z[0x2]]^S7[z[0xC]]^S8[z[0xD]]^S5[z[0x9]])&0x1f); _Kr[10]=(int)((S5[z[0x1]]^S6[z[0x0]]^S7[z[0xE]]^S8[z[0xF]]^S6[z[0xc]])&0x1f); _Kr[11]=(int)((S5[z[0x7]]^S6[z[0x6]]^S7[z[0x8]]^S8[z[0x9]]^S7[z[0x2]])&0x1f); _Kr[12]=(int)((S5[z[0x5]]^S6[z[0x4]]^S7[z[0xA]]^S8[z[0xB]]^S8[z[0x6]])&0x1f); z03 = IntsTo32bits(z, 0x0); z47 = IntsTo32bits(z, 0x4); z8B = IntsTo32bits(z, 0x8); zCF = IntsTo32bits(z, 0xC); x03 = z8B ^S5[z[0x5]] ^S6[z[0x7]] ^S7[z[0x4]] ^S8[z[0x6]] ^S7[z[0x0]]; Bits32ToInts(x03, x, 0x0); x47 = z03 ^S5[x[0x0]] ^S6[x[0x2]] ^S7[x[0x1]] ^S8[x[0x3]] ^S8[z[0x2]]; Bits32ToInts(x47, x, 0x4); x8B = z47 ^S5[x[0x7]] ^S6[x[0x6]] ^S7[x[0x5]] ^S8[x[0x4]] ^S5[z[0x1]]; Bits32ToInts(x8B, x, 0x8); xCF = zCF ^S5[x[0xA]] ^S6[x[0x9]] ^S7[x[0xB]] ^S8[x[0x8]] ^S6[z[0x3]]; Bits32ToInts(xCF, x, 0xC); _Kr[13]=(int)((S5[x[0x8]]^S6[x[0x9]]^S7[x[0x7]]^S8[x[0x6]]^S5[x[0x3]])&0x1f); _Kr[14]=(int)((S5[x[0xA]]^S6[x[0xB]]^S7[x[0x5]]^S8[x[0x4]]^S6[x[0x7]])&0x1f); _Kr[15]=(int)((S5[x[0xC]]^S6[x[0xD]]^S7[x[0x3]]^S8[x[0x2]]^S7[x[0x8]])&0x1f); _Kr[16]=(int)((S5[x[0xE]]^S6[x[0xF]]^S7[x[0x1]]^S8[x[0x0]]^S8[x[0xD]])&0x1f); } /** * Encrypt the given input starting at the given offset and place * the result in the provided buffer starting at the given offset. * * @param src The plaintext buffer * @param srcIndex An offset into src * @param dst The ciphertext buffer * @param dstIndex An offset into dst */ internal virtual int EncryptBlock( byte[] src, int srcIndex, byte[] dst, int dstIndex) { // process the input block // batch the units up into a 32 bit chunk and go for it // the array is in bytes, the increment is 8x8 bits = 64 uint L0 = Pack.BE_To_UInt32(src, srcIndex); uint R0 = Pack.BE_To_UInt32(src, srcIndex + 4); uint[] result = new uint[2]; CAST_Encipher(L0, R0, result); // now stuff them into the destination block Pack.UInt32_To_BE(result[0], dst, dstIndex); Pack.UInt32_To_BE(result[1], dst, dstIndex + 4); return BLOCK_SIZE; } /** * Decrypt the given input starting at the given offset and place * the result in the provided buffer starting at the given offset. * * @param src The plaintext buffer * @param srcIndex An offset into src * @param dst The ciphertext buffer * @param dstIndex An offset into dst */ internal virtual int DecryptBlock( byte[] src, int srcIndex, byte[] dst, int dstIndex) { // process the input block // batch the units up into a 32 bit chunk and go for it // the array is in bytes, the increment is 8x8 bits = 64 uint L16 = Pack.BE_To_UInt32(src, srcIndex); uint R16 = Pack.BE_To_UInt32(src, srcIndex + 4); uint[] result = new uint[2]; CAST_Decipher(L16, R16, result); // now stuff them into the destination block Pack.UInt32_To_BE(result[0], dst, dstIndex); Pack.UInt32_To_BE(result[1], dst, dstIndex + 4); return BLOCK_SIZE; } /** * The first of the three processing functions for the * encryption and decryption. * * @param D the input to be processed * @param Kmi the mask to be used from Km[n] * @param Kri the rotation value to be used * */ internal static uint F1(uint D, uint Kmi, int Kri) { uint I = Kmi + D; I = I << Kri | (I >> (32-Kri)); return ((S1[(I>>24)&0xff]^S2[(I>>16)&0xff])-S3[(I>>8)&0xff])+S4[I&0xff]; } /** * The second of the three processing functions for the * encryption and decryption. * * @param D the input to be processed * @param Kmi the mask to be used from Km[n] * @param Kri the rotation value to be used * */ internal static uint F2(uint D, uint Kmi, int Kri) { uint I = Kmi ^ D; I = I << Kri | (I >> (32-Kri)); return ((S1[(I>>24)&0xff]-S2[(I>>16)&0xff])+S3[(I>>8)&0xff])^S4[I&0xff]; } /** * The third of the three processing functions for the * encryption and decryption. * * @param D the input to be processed * @param Kmi the mask to be used from Km[n] * @param Kri the rotation value to be used * */ internal static uint F3(uint D, uint Kmi, int Kri) { uint I = Kmi - D; I = I << Kri | (I >> (32-Kri)); return ((S1[(I>>24)&0xff]+S2[(I>>16)&0xff])^S3[(I>>8)&0xff])-S4[I&0xff]; } /** * Does the 16 rounds to encrypt the block. * * @param L0 the LH-32bits of the plaintext block * @param R0 the RH-32bits of the plaintext block */ internal void CAST_Encipher(uint L0, uint R0, uint[] result) { uint Lp = L0; // the previous value, equiv to L[i-1] uint Rp = R0; // equivalent to R[i-1] /* * numbering consistent with paper to make * checking and validating easier */ uint Li = L0, Ri = R0; for (int i = 1; i<=_rounds ; i++) { Lp = Li; Rp = Ri; Li = Rp; switch (i) { case 1: case 4: case 7: case 10: case 13: case 16: Ri = Lp ^ F1(Rp, _Km[i], _Kr[i]); break; case 2: case 5: case 8: case 11: case 14: Ri = Lp ^ F2(Rp, _Km[i], _Kr[i]); break; case 3: case 6: case 9: case 12: case 15: Ri = Lp ^ F3(Rp, _Km[i], _Kr[i]); break; } } result[0] = Ri; result[1] = Li; return; } internal void CAST_Decipher(uint L16, uint R16, uint[] result) { uint Lp = L16; // the previous value, equiv to L[i-1] uint Rp = R16; // equivalent to R[i-1] /* * numbering consistent with paper to make * checking and validating easier */ uint Li = L16, Ri = R16; for (int i = _rounds; i > 0; i--) { Lp = Li; Rp = Ri; Li = Rp; switch (i) { case 1: case 4: case 7: case 10: case 13: case 16: Ri = Lp ^ F1(Rp, _Km[i], _Kr[i]); break; case 2: case 5: case 8: case 11: case 14: Ri = Lp ^ F2(Rp, _Km[i], _Kr[i]); break; case 3: case 6: case 9: case 12: case 15: Ri = Lp ^ F3(Rp, _Km[i], _Kr[i]); break; } } result[0] = Ri; result[1] = Li; return; } internal static void Bits32ToInts(uint inData, int[] b, int offset) { b[offset + 3] = (int) (inData & 0xff); b[offset + 2] = (int) ((inData >> 8) & 0xff); b[offset + 1] = (int) ((inData >> 16) & 0xff); b[offset] = (int) ((inData >> 24) & 0xff); } internal static uint IntsTo32bits(int[] b, int i) { return (uint)(((b[i] & 0xff) << 24) | ((b[i+1] & 0xff) << 16) | ((b[i+2] & 0xff) << 8) | ((b[i+3] & 0xff))); } } }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace AccessBridgeExplorer.Utils { /// <summary> /// Display a tree structure based on a <see cref="TreeListViewModel{TNode}"/> /// in a <see cref="ListView"/>. /// </summary> public class TreeListView<TNode> where TNode : class { private readonly ListView _listView; private readonly ExpandedNodeState _nodeState = new ExpandedNodeState(); private TreeListViewModel<TNode> _currentModel; /// <summary> /// Setup event handlers and image list. Can be called in the Forms /// constructor, just after <code>InitializeComponent</code>. /// </summary> public TreeListView(ListView listView, ImageList stateImageList) { _listView = listView; listView.FullRowSelect = true; listView.GridLines = true; listView.HeaderStyle = ColumnHeaderStyle.Nonclickable; listView.MultiSelect = false; listView.SmallImageList = stateImageList; listView.UseCompatibleStateImageBehavior = false; listView.View = View.Details; listView.HideSelection = false; listView.MouseClick += ListViewOnMouseClick; listView.MouseDoubleClick += ListViewOnMouseDoubleClick; listView.KeyDown += ListViewOnKeyDown; } /// <summary> /// Invoked when a <see cref="TNode"/> object is added or removed from the /// underlying list of <see cref="ListView"/> items, as a result of a /// collapse/expand operation. /// </summary> public event EventHandler<NodeVisibilityChangedArg<TNode>> NodeVisibilityChanged; /// <summary> /// Invoked when a <see cref="TNode"/> object is expanded in this <see /// cref="TreeListView{TNode}"/> /// </summary> public event EventHandler<NodeArgs<TNode>> NodeExpanded; /// <summary> /// Invoked when a <see cref="TNode"/> object is collapsed in this <see /// cref="TreeListView{TNode}"/> /// </summary> public event EventHandler<NodeArgs<TNode>> NodeCollapsed; /// <summary> /// Return the list of <see cref="TNode"/> corresponding the list of items /// selected in this <see cref="TreeListView{TNode}"/>. /// </summary> public IList<TNode> SelectedNodes { get { return _listView .SelectedItems .Cast<ListViewItem>() .Select(x => ((ListViewItemTag)x.Tag).Node) .ToList(); } } /// <summary> /// Set a new <paramref name="model"/> to be displayed in the <see /// cref="ListView"/>. /// </summary> public void SetModel(TreeListViewModel<TNode> model) { _listView.BeginUpdate(); try { _currentModel = model; UpdateListView(); } finally { _listView.EndUpdate(); } } /// <summary> /// Remove the current <see cref="TreeNodeCollection"/> and remove all entries /// displayed in the <see cref="ListView"/>. /// </summary> public void Clear() { _listView.Items.Clear(); _currentModel = null; } /// <summary> /// Update the list view contents minimally after a group has been /// expanded/collapsed. /// </summary> private void UpdateListView() { _listView.BeginUpdate(); try { var oldItems = _listView.Items.AsList(); var oldNodes = new HashSet<TNode>(oldItems.Select(x => ((ListViewItemTag)x.Tag).Node)); var newItems = CreateListViewItems(_currentModel, _nodeState); var newNodes = new HashSet<TNode>(newItems.Select(x => ((ListViewItemTag)x.Tag).Node)); ListHelpers.IncrementalUpdate(oldItems, newItems, new ListViewOperations()); // Fire events related to adding/removing nodes from the display // inserted = newItems \ oldItems // removed = oldItems \ newItems foreach (var node in newNodes) { if (!oldNodes.Contains(node)) OnNodeVisibilityChanged(new NodeVisibilityChangedArg<TNode>(node, true)); } foreach (var node in oldNodes) { if (!newNodes.Contains(node)) OnNodeVisibilityChanged(new NodeVisibilityChangedArg<TNode>(node, false)); } } finally { _listView.EndUpdate(); } } /// <summary> /// Create all list view items corresponding to all the properties and property groups /// that should be displayed in the list view. Children of property groups that are not /// expanded are skipped -- they will be created when the groups are expanded. /// </summary> private List<ListViewItem> CreateListViewItems(TreeListViewModel<TNode> model, ExpandedNodeState expandedNodeState) { var itemList = new List<ListViewItem>(); if (model == null) return itemList; if (model.IsRootVisible()) { CreateListViewItem(itemList, expandedNodeState, "", 0, model, model.GetRootNode()); } else { Enumerable.Range(0, model.GetChildCount(model.GetRootNode())).ForEach(index => { CreateListViewItem(itemList, expandedNodeState, "", 0, model, model.GetChildAt(model.GetRootNode(), index)); }); } return itemList; } private void CreateListViewItem(List<ListViewItem> itemList, ExpandedNodeState expandedNodeState, string parentPath, int indent, TreeListViewModel<TNode> model, TNode node) { var propertyNodePath = MakeNodePath(model, parentPath, node); var item = new ListViewItem(); itemList.Add(item); // Add the item before (optional) recursive call // Add sub-properties recursively (if group) if (model.IsNodeExpandable(node)) { var isExpanded = expandedNodeState.IsExpanded(model, node, propertyNodePath); item.ImageIndex = isExpanded ? 1 : 0; if (isExpanded) { Enumerable.Range(0, model.GetChildCount(node)).ForEach(index => { CreateListViewItem(itemList, expandedNodeState, propertyNodePath, indent + 1, model, model.GetChildAt(node, index)); }); } } // Setup final item properties after recursion, in case property node // value, for example, was changed as a side effect of the recursive call. item.Text = model.GetNodeText(node); var subItemCount = model.GetNodeSubItemCount(node); for (var subItem = 0; subItem < subItemCount; subItem++) { item.SubItems.Add(model.GetNodeSubItemAt(node, subItem)); } item.Tag = new ListViewItemTag(node, propertyNodePath); item.IndentCount = indent; } private class ListViewOperations : IncrementalUpdateOperations<ListViewItem, ListViewItem> { public override int FindItem(IList<ListViewItem> items, int startIndex, ListViewItem newItem) { return FindIndexOfTag(items, startIndex, newItem.Tag); } public override void InsertItem(IList<ListViewItem> items, int index, ListViewItem newItem) { items.Insert(index, newItem); } public override void UpdateItem(IList<ListViewItem> items, int index, ListViewItem newItem) { ListViewItem oldItem = items[index]; // Note: For performance reason, we only assign values if they have changed if (oldItem.ImageIndex != newItem.ImageIndex) oldItem.ImageIndex = newItem.ImageIndex; if (oldItem.StateImageIndex != newItem.StateImageIndex) oldItem.StateImageIndex = newItem.StateImageIndex; if (oldItem.IndentCount != newItem.IndentCount) oldItem.IndentCount = newItem.IndentCount; if (!ReferenceEquals(oldItem.Tag, newItem.Tag)) { oldItem.Tag = newItem.Tag; } // SubItem[0] is the same as the Text property. So we just need to // synchronize the SubItems collections. for (var i = 0; i < newItem.SubItems.Count; i++) { var newText = newItem.SubItems[i].Text; if (i < oldItem.SubItems.Count) { if (oldItem.SubItems[i].Text != newText) oldItem.SubItems[i].Text = newText; } else { oldItem.SubItems.Add(newText); } } // If there were more subitems in the existing item, remove them for (var i = oldItem.SubItems.Count - 1; i >= newItem.SubItems.Count; i--) { oldItem.SubItems.RemoveAt(i); } } private int FindIndexOfTag(IList<ListViewItem> oldItems, int startIndex, object tag) { var itemTag = (ListViewItemTag)tag; for (var index = startIndex; index < oldItems.Count; index++) { var oldItemTag = (ListViewItemTag)oldItems[index].Tag; if (Equals(itemTag.Path, oldItemTag.Path)) return index; } return -1; } } private static string MakeNodePath(TreeListViewModel<TNode> model, string path, TNode node) { var text = model.GetNodePathComponent(node).Replace('\\', '-'); if (string.IsNullOrEmpty(path)) return text; return path + "\\" + text; } /// <summary> /// Toggle expanded/collapsed state of the selecte list view item if /// left/right keys are pressed and the item is a group. /// </summary> private void ListViewOnKeyDown(object sender, KeyEventArgs e) { var listView = (ListView)sender; if (listView.SelectedItems.Count == 0) return; var item = listView.SelectedItems[0]; var itemState = (ListViewItemTag)item.Tag; var node = itemState.Node; if (node == null) return; switch (e.KeyCode) { case Keys.Add: case Keys.Right: if (!_nodeState.IsExpanded(_currentModel, node, itemState.Path)) ToggleExpanded(item); break; case Keys.Subtract: case Keys.Left: if (_nodeState.IsExpanded(_currentModel, node, itemState.Path)) ToggleExpanded(item); break; } } /// <summary> /// Toggle the expanded/collapsed state of the list view item target of the /// double click event. /// </summary> private void ListViewOnMouseDoubleClick(object sender, MouseEventArgs e) { var listView = (ListView)sender; var info = listView.HitTest(e.Location); if (info.Location == ListViewHitTestLocations.None) return; ToggleExpanded(info.Item); } /// <summary> /// Toggle expanded/collapsed state if mouse click on the image associated /// with the list view item target of the click event. /// </summary> private void ListViewOnMouseClick(object sender, MouseEventArgs e) { var listView = (ListView)sender; var info = listView.HitTest(e.Location); if (info.Location != ListViewHitTestLocations.Image) return; ToggleExpanded(info.Item); } private void ToggleExpanded(ListViewItem item) { var itemState = (ListViewItemTag)item.Tag; var node = itemState.Node; if (node == null) return; var isExpanded = _nodeState.IsExpanded(_currentModel, node, itemState.Path); _nodeState.SetExpanded(itemState.Path, !isExpanded); if (isExpanded) OnNodeCollapsed(new NodeArgs<TNode>(node)); else OnNodeExpanded(new NodeArgs<TNode>(node)); UpdateListView(); } /// <summary> /// State associated with each item in the list view. The state is stored in /// the <see cref="ListViewItem.Tag"/> property. /// </summary> private class ListViewItemTag { private readonly TNode _node; private readonly string _path; public ListViewItemTag(TNode node, string path) { _node = node; _path = path ?? ""; } public TNode Node { get { return _node; } } public string Path { get { return _path; } } } /// <summary> /// Store the expanded/collapsed state of each group of the property list so /// that when switching to a new property list, we can re-apply the /// expanded/collapsed state to corresponding group in the new list. /// </summary> public class ExpandedNodeState { private readonly Dictionary<string, bool> _expandedStates = new Dictionary<string, bool>(); public void SetExpanded(string path, bool expanded) { _expandedStates[path] = expanded; } public bool IsExpanded(TreeListViewModel<TNode> model, TNode node, string path) { bool savedState; if (_expandedStates.TryGetValue(path, out savedState)) { return savedState; } return model.IsNodeExpanded(node); } } protected virtual void OnNodeVisibilityChanged(NodeVisibilityChangedArg<TNode> e) { var handler = NodeVisibilityChanged; if (handler != null) handler(this, e); } protected virtual void OnNodeExpanded(NodeArgs<TNode> e) { var handler = NodeExpanded; if (handler != null) handler(this, e); } protected virtual void OnNodeCollapsed(NodeArgs<TNode> e) { var handler = NodeCollapsed; if (handler != null) handler(this, e); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.Utilities.Common { using System; using System.Collections.Generic; using System.Globalization; using System.Management.Automation; using System.Reflection; using System.ServiceModel; using System.ServiceModel.Dispatcher; using System.Threading; using ServiceManagement; public abstract class ServiceManagementBaseCmdlet : CloudBaseCmdlet<IServiceManagement> { protected override IServiceManagement CreateChannel() { // If ShareChannel is set by a unit test, use the same channel that // was passed into out constructor. This allows the test to submit // a mock that we use for all network calls. if (ShareChannel) { return Channel; } var messageInspectors = new List<IClientMessageInspector> { new ServiceManagementClientOutputMessageInspector(), new HttpRestMessageInspector(this.WriteDebug) }; var clientOptions = new ServiceManagementClientOptions(null, null, null, 0, RetryPolicy.NoRetryPolicy, ServiceManagementClientOptions.DefaultOptions.WaitTimeForOperationToComplete, messageInspectors); var smClient = new ServiceManagementClient(new Uri(this.ServiceEndpoint), CurrentSubscription.SubscriptionId, CurrentSubscription.Certificate, clientOptions); Type serviceManagementClientType = typeof(ServiceManagementClient); PropertyInfo propertyInfo = serviceManagementClientType.GetProperty("SyncService", BindingFlags.Instance | BindingFlags.NonPublic); var syncService = (IServiceManagement)propertyInfo.GetValue(smClient, null); return syncService; } /// <summary> /// Invoke the given operation within an OperationContextScope if the /// channel supports it. /// </summary> /// <param name="action">The action to invoke.</param> protected override void InvokeInOperationContext(Action action) { IContextChannel contextChannel = ToContextChannel(); if (contextChannel != null) { using (new OperationContextScope(contextChannel)) { action(); } } else { action(); } } protected virtual IContextChannel ToContextChannel() { try { return Channel.ToContextChannel(); } catch (Exception) { return null; } } protected void ExecuteClientAction(object input, string operationDescription, Action<string> action) { Operation operation = null; WriteVerboseWithTimestamp(string.Format("Begin Operation: {0}", operationDescription)); RetryCall(action); operation = GetOperation(); WriteVerboseWithTimestamp(string.Format("Completed Operation: {0}", operationDescription)); if (operation != null) { var context = new ManagementOperationContext { OperationDescription = operationDescription, OperationId = operation.OperationTrackingId, OperationStatus = operation.Status }; WriteObject(context, true); } } protected void ExecuteClientActionInOCS(object input, string operationDescription, Action<string> action) { IContextChannel contextChannel = null; try { contextChannel = Channel.ToContextChannel(); } catch (Exception) { // Do nothing, proceed. } if (contextChannel != null) { object context = null; using (new OperationContextScope(contextChannel)) { Operation operation = null; WriteVerboseWithTimestamp(string.Format("Begin Operation: {0}", operationDescription)); try { RetryCall(action); operation = GetOperation(); } catch (ServiceManagementClientException ex) { WriteErrorDetails(ex); } WriteVerboseWithTimestamp(string.Format("Completed Operation: {0}", operationDescription)); if (operation != null) { context = new ManagementOperationContext { OperationDescription = operationDescription, OperationId = operation.OperationTrackingId, OperationStatus = operation.Status }; } } if (context != null) { WriteObject(context, true); } } else { RetryCall(action); } } protected virtual void WriteErrorDetails(ServiceManagementClientException exception) { if (CommandRuntime != null) { WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null)); } } protected void ExecuteClientActionInOCS<TResult>(object input, string operationDescription, Func<string, TResult> action, Func<Operation, TResult, object> contextFactory) where TResult : class { IContextChannel contextChannel = null; try { contextChannel = Channel.ToContextChannel(); } catch (Exception) { // Do nothing, proceed. } if (contextChannel != null) { object context = null; using (new OperationContextScope(contextChannel)) { TResult result = null; Operation operation = null; WriteVerboseWithTimestamp(string.Format("Begin Operation: {0}", operationDescription)); try { result = RetryCall(action); operation = GetOperation(); } catch (ServiceManagementClientException ex) { WriteErrorDetails(ex); } WriteVerboseWithTimestamp(string.Format("Completed Operation: {0}", operationDescription)); if (result != null && operation != null) { context = contextFactory(operation, result); } } if (context != null) { WriteObject(context, true); } } else { TResult result = RetryCall(action); if (result != null) { WriteObject(result, true); } } } protected Operation GetOperation() { Operation operation = null; try { string operationId = RetrieveOperationId(); if (!string.IsNullOrEmpty(operationId)) { operation = RetryCall(s => GetOperationStatus(this.CurrentSubscription.SubscriptionId, operationId)); if (string.Compare(operation.Status, OperationState.Failed, StringComparison.OrdinalIgnoreCase) == 0) { var errorMessage = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", operation.Status, operation.Error.Message); var exception = new Exception(errorMessage); WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null)); } } else { operation = new Operation { OperationTrackingId = string.Empty, Status = OperationState.Failed }; } } catch (ServiceManagementClientException ex) { WriteErrorDetails(ex); } return operation; } protected override Operation GetOperationStatus(string subscriptionId, string operationId) { var channel = (IServiceManagement)Channel; return channel.GetOperationStatus(subscriptionId, operationId); } } }
// Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using System; using System.Linq; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.UI.Controls; using Foundation; using UIKit; namespace ArcGISRuntime.Samples.ManageBookmarks { [Register("ManageBookmarks")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Manage bookmarks", category: "Map", description: "Access and create bookmarks on a map.", instructions: "The map in the sample comes pre-populated with a set of bookmarks. To access a bookmark and move to that location, tap on a bookmark's name from the list. To add a bookmark, pan and/or zoom to a new location and tap on the 'Add Bookmark' button. Enter a unique name for the bookmark and tap ok, and the bookmark will be added to the list", tags: new[] { "bookmark", "extent", "location", "zoom" })] public class ManageBookmarks : UIViewController { // Hold references to UI controls. private MapView _myMapView; private UIBarButtonItem _bookmarksButton; private UIBarButtonItem _addButton; private UIAlertController _textInputAlertController; public ManageBookmarks() { Title = "Manage bookmarks"; } private void Initialize() { // Create a map with labeled imagery basemap. Map map = new Map(BasemapStyle.ArcGISImagery); // Add default bookmarks. AddDefaultBookmarks(map); // Zoom to the last bookmark. map.InitialViewpoint = map.Bookmarks.Last().Viewpoint; // Show the map. _myMapView.Map = map; } private void AddDefaultBookmarks(Map map) { // Bookmark 1. // Create a new bookmark. Bookmark myBookmark = new Bookmark { Name = "Mysterious Desert Pattern", Viewpoint = new Viewpoint(27.3805833, 33.6321389, 6000) }; // Add the bookmark to bookmark collection of the map. map.Bookmarks.Add(myBookmark); // Bookmark 2. myBookmark = new Bookmark { Name = "Dormant Volcano", Viewpoint = new Viewpoint(-39.299987, 174.060858, 600000) }; map.Bookmarks.Add(myBookmark); // Bookmark 3. myBookmark = new Bookmark { Name = "Guitar-Shaped Forest", Viewpoint = new Viewpoint(-33.867886, -63.985, 40000) }; map.Bookmarks.Add(myBookmark); // Bookmark 4. myBookmark = new Bookmark { Name = "Grand Prismatic Spring", Viewpoint = new Viewpoint(44.525049, -110.83819, 6000) }; map.Bookmarks.Add(myBookmark); } private void OnAddBookmarksButtonClicked(object sender, EventArgs e) { // Create Alert for naming the bookmark. if (_textInputAlertController == null) { _textInputAlertController = UIAlertController.Create("Provide the bookmark name", "", UIAlertControllerStyle.Alert); // Add Text Input. _textInputAlertController.AddTextField(textField => { }); void HandleAlertAction(UIAlertAction action) { // Get the name from the text field. string name = _textInputAlertController.TextFields[0].Text; // Exit if the name is empty. if (String.IsNullOrEmpty(name)) return; // Check to see if there is a bookmark with same name. bool doesNameExist = _myMapView.Map.Bookmarks.Any(b => b.Name == name); if (doesNameExist) return; // Create a new bookmark. Bookmark myBookmark = new Bookmark { Name = name, // Get the current viewpoint from map and assign it to bookmark . Viewpoint = _myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry) }; // Add the bookmark to bookmark collection of the map. _myMapView.Map.Bookmarks.Add(myBookmark); } // Add Actions. _textInputAlertController.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null)); _textInputAlertController.AddAction(UIAlertAction.Create("Done", UIAlertActionStyle.Default, HandleAlertAction)); } // Show the alert. PresentViewController(_textInputAlertController, true, null); } private void OnShowBookmarksButtonClicked(object sender, EventArgs e) { // Create a new Alert Controller. UIAlertController actionAlert = UIAlertController.Create("Bookmarks", "", UIAlertControllerStyle.Alert); // Add Bookmarks as Actions. foreach (Bookmark myBookmark in _myMapView.Map.Bookmarks) { actionAlert.AddAction(UIAlertAction.Create(myBookmark.Name, UIAlertActionStyle.Default, action => _myMapView.SetViewpoint(myBookmark.Viewpoint))); } // Display the alert. PresentViewController(actionAlert, true, null); } public override void ViewDidLoad() { base.ViewDidLoad(); Initialize(); } public override void LoadView() { // Create the views. View = new UIView {BackgroundColor = ApplicationTheme.BackgroundColor}; _myMapView = new MapView(); _myMapView.TranslatesAutoresizingMaskIntoConstraints = false; _bookmarksButton = new UIBarButtonItem(); _bookmarksButton.Title = "Bookmarks"; _addButton = new UIBarButtonItem(UIBarButtonSystemItem.Add); UIToolbar toolbar = new UIToolbar(); toolbar.TranslatesAutoresizingMaskIntoConstraints = false; toolbar.Items = new[] { _bookmarksButton, new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), _addButton }; // Add the views. View.AddSubviews(_myMapView, toolbar); // Lay out the views. NSLayoutConstraint.ActivateConstraints(new[] { _myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor), _myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), _myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor), toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor), toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor) }); } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); // Subscribe to events. _bookmarksButton.Clicked += OnShowBookmarksButtonClicked; _addButton.Clicked += OnAddBookmarksButtonClicked; } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); // Unsubscribe from events, per best practice. _bookmarksButton.Clicked -= OnShowBookmarksButtonClicked; _addButton.Clicked -= OnAddBookmarksButtonClicked; // Remove the reference to the alert controller, preventing a memory leak. _textInputAlertController = null; } } }
using System; using System.Collections.Generic; using System.Numerics; using GUI.Types.Renderer; using GUI.Utils; using OpenTK.Graphics.OpenGL; using ValveResourceFormat.ResourceTypes; using ValveResourceFormat.Serialization; namespace GUI.Types.ParticleRenderer.Renderers { internal class RenderSprites : IParticleRenderer { private const int VertexSize = 9; private readonly Shader shader; private readonly int quadVao; private readonly int glTexture; private readonly Texture.SpritesheetData spriteSheetData; private readonly float animationRate = 0.1f; private readonly bool additive; private readonly float overbrightFactor = 1; private readonly long orientationType; private float[] rawVertices; private QuadIndexBuffer quadIndices; private int vertexBufferHandle; public RenderSprites(IKeyValueCollection keyValues, VrfGuiContext vrfGuiContext) { shader = vrfGuiContext.ShaderLoader.LoadShader("vrf.particle.sprite", new Dictionary<string, bool>()); quadIndices = vrfGuiContext.QuadIndices; // The same quad is reused for all particles quadVao = SetupQuadBuffer(); if (keyValues.ContainsKey("m_hTexture")) { var textureSetup = LoadTexture(keyValues.GetProperty<string>("m_hTexture"), vrfGuiContext); glTexture = textureSetup.TextureIndex; spriteSheetData = textureSetup.TextureData?.GetSpriteSheetData(); } else { glTexture = vrfGuiContext.MaterialLoader.GetErrorTexture(); } additive = keyValues.GetProperty<bool>("m_bAdditive"); if (keyValues.ContainsKey("m_flOverbrightFactor")) { overbrightFactor = keyValues.GetFloatProperty("m_flOverbrightFactor"); } if (keyValues.ContainsKey("m_nOrientationType")) { orientationType = keyValues.GetIntegerProperty("m_nOrientationType"); } if (keyValues.ContainsKey("m_flAnimationRate")) { animationRate = keyValues.GetFloatProperty("m_flAnimationRate"); } } private int SetupQuadBuffer() { GL.UseProgram(shader.Program); // Create and bind VAO var vao = GL.GenVertexArray(); GL.BindVertexArray(vao); vertexBufferHandle = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferHandle); int stride = sizeof(float) * VertexSize; var positionAttributeLocation = GL.GetAttribLocation(shader.Program, "aVertexPosition"); GL.VertexAttribPointer(positionAttributeLocation, 3, VertexAttribPointerType.Float, false, stride, 0); var colorAttributeLocation = GL.GetAttribLocation(shader.Program, "aVertexColor"); GL.VertexAttribPointer(colorAttributeLocation, 4, VertexAttribPointerType.Float, false, stride, sizeof(float) * 3); var uvAttributeLocation = GL.GetAttribLocation(shader.Program, "aTexCoords"); GL.VertexAttribPointer(uvAttributeLocation, 2, VertexAttribPointerType.Float, false, stride, sizeof(float) * 7); GL.EnableVertexAttribArray(positionAttributeLocation); GL.EnableVertexAttribArray(colorAttributeLocation); GL.EnableVertexAttribArray(uvAttributeLocation); GL.BindVertexArray(0); return vao; } private static (int TextureIndex, Texture TextureData) LoadTexture(string textureName, VrfGuiContext vrfGuiContext) { var textureResource = vrfGuiContext.LoadFileByAnyMeansNecessary(textureName + "_c"); if (textureResource == null) { return (vrfGuiContext.MaterialLoader.GetErrorTexture(), null); } return (vrfGuiContext.MaterialLoader.LoadTexture(textureName), (Texture)textureResource.DataBlock); } private void EnsureSpaceForVertices(int count) { int numFloats = count * VertexSize; if (rawVertices == null) { rawVertices = new float[numFloats]; } else if (rawVertices.Length < numFloats) { int nextSize = (((count / 64) + 1) * 64) * VertexSize; Array.Resize(ref rawVertices, nextSize); } } private void UpdateVertices(ParticleBag particleBag, Matrix4x4 modelViewMatrix) { var particles = particleBag.LiveParticles; // Create billboarding rotation (always facing camera) Matrix4x4.Decompose(modelViewMatrix, out _, out Quaternion modelViewRotation, out _); modelViewRotation = Quaternion.Inverse(modelViewRotation); var billboardMatrix = Matrix4x4.CreateFromQuaternion(modelViewRotation); // Update vertex buffer EnsureSpaceForVertices(particleBag.Count * 4); for (int i = 0; i < particleBag.Count; ++i) { // Positions var modelMatrix = orientationType == 0 ? particles[i].GetRotationMatrix() * billboardMatrix * particles[i].GetTransformationMatrix() : particles[i].GetRotationMatrix() * particles[i].GetTransformationMatrix(); var tl = Vector4.Transform(new Vector4(-1, -1, 0, 1), modelMatrix); var bl = Vector4.Transform(new Vector4(-1, 1, 0, 1), modelMatrix); var br = Vector4.Transform(new Vector4(1, 1, 0, 1), modelMatrix); var tr = Vector4.Transform(new Vector4(1, -1, 0, 1), modelMatrix); int quadStart = i * VertexSize * 4; rawVertices[quadStart + 0] = tl.X; rawVertices[quadStart + 1] = tl.Y; rawVertices[quadStart + 2] = tl.Z; rawVertices[quadStart + (VertexSize * 1) + 0] = bl.X; rawVertices[quadStart + (VertexSize * 1) + 1] = bl.Y; rawVertices[quadStart + (VertexSize * 1) + 2] = bl.Z; rawVertices[quadStart + (VertexSize * 2) + 0] = br.X; rawVertices[quadStart + (VertexSize * 2) + 1] = br.Y; rawVertices[quadStart + (VertexSize * 2) + 2] = br.Z; rawVertices[quadStart + (VertexSize * 3) + 0] = tr.X; rawVertices[quadStart + (VertexSize * 3) + 1] = tr.Y; rawVertices[quadStart + (VertexSize * 3) + 2] = tr.Z; // Colors for (int j = 0; j < 4; ++j) { rawVertices[quadStart + (VertexSize * j) + 3] = particles[i].Color.X; rawVertices[quadStart + (VertexSize * j) + 4] = particles[i].Color.Y; rawVertices[quadStart + (VertexSize * j) + 5] = particles[i].Color.Z; rawVertices[quadStart + (VertexSize * j) + 6] = particles[i].Alpha; } // UVs if (spriteSheetData != null && spriteSheetData.Sequences.Length > 0 && spriteSheetData.Sequences[0].Frames.Length > 0) { var sequence = spriteSheetData.Sequences[particles[i].Sequence % spriteSheetData.Sequences.Length]; var particleTime = particles[i].ConstantLifetime - particles[i].Lifetime; var frame = particleTime * sequence.FramesPerSecond * animationRate; var currentFrame = sequence.Frames[(int)Math.Floor(frame) % sequence.Frames.Length]; // Lerp frame coords and size var subFrameTime = frame % 1.0f; var offset = (currentFrame.StartMins * (1 - subFrameTime)) + (currentFrame.EndMins * subFrameTime); var scale = ((currentFrame.StartMaxs - currentFrame.StartMins) * (1 - subFrameTime)) + ((currentFrame.EndMaxs - currentFrame.EndMins) * subFrameTime); rawVertices[quadStart + (VertexSize * 0) + 7] = offset.X + (scale.X * 0); rawVertices[quadStart + (VertexSize * 0) + 8] = offset.Y + (scale.Y * 1); rawVertices[quadStart + (VertexSize * 1) + 7] = offset.X + (scale.X * 0); rawVertices[quadStart + (VertexSize * 1) + 8] = offset.Y + (scale.Y * 0); rawVertices[quadStart + (VertexSize * 2) + 7] = offset.X + (scale.X * 1); rawVertices[quadStart + (VertexSize * 2) + 8] = offset.Y + (scale.Y * 0); rawVertices[quadStart + (VertexSize * 3) + 7] = offset.X + (scale.X * 1); rawVertices[quadStart + (VertexSize * 3) + 8] = offset.Y + (scale.Y * 1); } else { rawVertices[quadStart + (VertexSize * 0) + 7] = 0; rawVertices[quadStart + (VertexSize * 0) + 8] = 1; rawVertices[quadStart + (VertexSize * 1) + 7] = 0; rawVertices[quadStart + (VertexSize * 1) + 8] = 0; rawVertices[quadStart + (VertexSize * 2) + 7] = 1; rawVertices[quadStart + (VertexSize * 2) + 8] = 0; rawVertices[quadStart + (VertexSize * 3) + 7] = 1; rawVertices[quadStart + (VertexSize * 3) + 8] = 1; } } GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferHandle); GL.BufferData(BufferTarget.ArrayBuffer, particleBag.Count * VertexSize * 4 * sizeof(float), rawVertices, BufferUsageHint.DynamicDraw); } public void Render(ParticleBag particleBag, Matrix4x4 viewProjectionMatrix, Matrix4x4 modelViewMatrix) { if (particleBag.Count == 0) { return; } // Update vertex buffer UpdateVertices(particleBag, modelViewMatrix); // Draw it GL.Enable(EnableCap.Blend); GL.UseProgram(shader.Program); if (additive) { GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.One); } else { GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha); } GL.BindVertexArray(quadVao); GL.EnableVertexAttribArray(0); GL.ActiveTexture(TextureUnit.Texture0); GL.BindTexture(TextureTarget.Texture2D, glTexture); GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferHandle); GL.Uniform1(shader.GetUniformLocation("uTexture"), 0); // set texture unit 0 as uTexture uniform var otkProjection = viewProjectionMatrix.ToOpenTK(); GL.UniformMatrix4(shader.GetUniformLocation("uProjectionViewMatrix"), false, ref otkProjection); // TODO: This formula is a guess but still seems too bright compared to valve particles GL.Uniform1(shader.GetUniformLocation("uOverbrightFactor"), overbrightFactor); GL.Disable(EnableCap.CullFace); GL.Enable(EnableCap.DepthTest); GL.DepthMask(false); GL.BindBuffer(BufferTarget.ElementArrayBuffer, quadIndices.GLHandle); GL.DrawElements(BeginMode.Triangles, particleBag.Count * 6, DrawElementsType.UnsignedShort, 0); GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.Enable(EnableCap.CullFace); GL.Disable(EnableCap.DepthTest); GL.DepthMask(true); GL.BindVertexArray(0); GL.UseProgram(0); if (additive) { GL.BlendEquation(BlendEquationMode.FuncAdd); } GL.Disable(EnableCap.Blend); } } }