context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System.Collections; using System.Collections.Generic; using System.Linq; using DotSpatial.Data; using DotSpatial.Serialization; using DotSpatial.Symbology; namespace DotSpatial.Controls { /// <summary> /// MapGroup /// </summary> public class MapGroup : Group, IMapGroup { #region Fields private IMapLayerCollection _layers; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="MapGroup"/> class. /// </summary> public MapGroup() { Layers = new MapLayerCollection(); } /// <summary> /// Initializes a new instance of the <see cref="MapGroup"/> class for the specified map. /// This will place the group at the root level on the MapFrame. /// </summary> /// <param name="map">The map to add this group to.</param> /// <param name="name">The name to appear in the legend text.</param> public MapGroup(IMap map, string name) : base(map.MapFrame, map.ProgressHandler) { Layers = new MapLayerCollection(map.MapFrame, this, map.ProgressHandler); LegendText = name; map.Layers.Add(this); } /// <summary> /// Initializes a new instance of the <see cref="MapGroup"/> class that sits in a layer list and uses the specified progress handler. /// </summary> /// <param name="container">the layer list</param> /// <param name="frame">The map frame.</param> /// <param name="progressHandler">the progress handler</param> public MapGroup(ICollection<IMapLayer> container, IMapFrame frame, IProgressHandler progressHandler) : base(frame, progressHandler) { Layers = new MapLayerCollection(frame, this, progressHandler); container.Add(this); } #endregion #region Properties /// <inheritdoc /> public override int Count => _layers.Count; /// <inheritdoc /> public override bool EventsSuspended => _layers.EventsSuspended; /// <inheritdoc /> public override bool IsReadOnly => _layers.IsReadOnly; /// <summary> /// Gets or sets the collection of layers. /// </summary> [Serialize("Layers")] public new IMapLayerCollection Layers { get { return _layers; } set { if (Layers != null) { IgnoreLayerEvents(_layers); } HandleLayerEvents(value); _layers = value; // set the MapFrame property if (ParentMapFrame != null) { _layers.MapFrame = ParentMapFrame; } } } /// <summary> /// Gets the layers cast as legend items. This allows easier cycling in recursive legend code. /// </summary> public override IEnumerable<ILegendItem> LegendItems { get { // Keep cast for 3.5 framework return _layers.Cast<ILegendItem>(); } } /// <inheritdoc /> public override IFrame MapFrame { get { return base.MapFrame; } set { base.MapFrame = value; if (_layers != null) { IMapFrame newValue = value as IMapFrame; if (newValue != null && _layers.MapFrame == null) { _layers.MapFrame = newValue; } } } } /// <summary> /// Gets or sets the MapFrame that this group ultimately belongs to. This may not /// be the immediate parent of this group. /// </summary> public IMapFrame ParentMapFrame { get { return MapFrame as IMapFrame; } set { MapFrame = value; } } #endregion #region Indexers /// <inheritdoc /> public override ILayer this[int index] { get { return _layers[index]; } set { IMapLayer ml = value as IMapLayer; _layers[index] = ml; } } #endregion #region Methods /// <inheritdoc /> public override void Add(ILayer layer) { IMapLayer ml = layer as IMapLayer; if (ml != null) { _layers.Add(ml); } } /// <inheritdoc /> public override void Clear() { _layers.Clear(); } /// <inheritdoc /> public override bool Contains(ILayer item) { IMapLayer ml = item as IMapLayer; return ml != null && _layers.Contains(ml); } /// <inheritdoc /> public override void CopyTo(ILayer[] array, int arrayIndex) { for (int i = 0; i < Layers.Count; i++) { array[i + arrayIndex] = _layers[i]; } } /// <summary> /// This draws content from the specified geographic regions onto the specified graphics /// object specified by MapArgs. /// </summary> /// <param name="args">The map args.</param> /// <param name="regions">The regions.</param> /// <param name="selected">Indicates whether to draw the normal colored features or the selection colored features.</param> public void DrawRegions(MapArgs args, List<Extent> regions, bool selected) { if (Layers == null) return; foreach (IMapLayer layer in Layers) { if (!layer.IsVisible) continue; if (layer.UseDynamicVisibility && ((layer.DynamicVisibilityMode == DynamicVisibilityMode.ZoomedIn && MapFrame.ViewExtents.Width > layer.DynamicVisibilityWidth) || (layer.DynamicVisibilityMode != DynamicVisibilityMode.ZoomedIn && MapFrame.ViewExtents.Width < layer.DynamicVisibilityWidth))) { continue; // skip the layer if we are zoomed in or out too far. } layer.DrawRegions(args, regions, selected); } } /// <inheritdoc /> public override IEnumerator<ILayer> GetEnumerator() { return new MapLayerEnumerator(_layers.GetEnumerator()); } /// <summary> /// Gets the layers cast as ILayer without any information about the actual drawing methods. /// This is useful for handling methods that my come from various types of maps. /// </summary> /// <returns>An enumerable collection of ILayer</returns> public override IList<ILayer> GetLayers() { return _layers.Cast<ILayer>().ToList(); } /// <inheritdoc /> public override int IndexOf(ILayer item) { IMapLayer ml = item as IMapLayer; if (ml != null) { return _layers.IndexOf(ml); } return -1; } /// <inheritdoc /> public override void Insert(int index, ILayer layer) { IMapLayer ml = layer as IMapLayer; if (ml != null) { _layers.Insert(index, ml); } } /// <inheritdoc /> public override bool Remove(ILayer layer) { IMapLayer ml = layer as IMapLayer; return ml != null && _layers.Remove(ml); } /// <inheritdoc /> public override void RemoveAt(int index) { _layers.RemoveAt(index); } /// <inheritdoc /> public override void ResumeEvents() { _layers.ResumeEvents(); } /// <inheritdoc /> public override void SuspendEvents() { _layers.SuspendEvents(); } /// <inheritdoc /> IEnumerator IEnumerable.GetEnumerator() { return _layers.GetEnumerator(); } /// <summary> /// Overrides the base CreateGroup method to ensure that new groups are GeoGroups. /// </summary> protected override void OnCreateGroup() { new MapGroup(Layers, ParentMapFrame, ProgressHandler) { LegendText = "New Group" }; } #endregion #region Classes /// <summary> /// Transforms an IMapLayer enumerator into an ILayer Enumerator /// </summary> private class MapLayerEnumerator : IEnumerator<ILayer> { #region Fields private readonly IEnumerator<IMapLayer> _enumerator; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="MapLayerEnumerator"/> class. /// </summary> /// <param name="subEnumerator">Enumerator used inside this.</param> public MapLayerEnumerator(IEnumerator<IMapLayer> subEnumerator) { _enumerator = subEnumerator; } #endregion #region Properties /// <inheritdoc /> public ILayer Current => _enumerator.Current; object IEnumerator.Current => _enumerator.Current; #endregion #region Methods /// <inheritdoc /> public void Dispose() { _enumerator.Dispose(); } /// <inheritdoc /> public bool MoveNext() { return _enumerator.MoveNext(); } /// <inheritdoc /> public void Reset() { _enumerator.Reset(); } #endregion } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection; using System.Diagnostics; #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: Type handler for empty or unsupported types. /// </summary> internal sealed class NullTypeInfo : TraceLoggingTypeInfo { public NullTypeInfo() : base(typeof(EmptyStruct)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddGroup(name); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { return; } public override object GetData(object value) { return null; } } /// <summary> /// Type handler for simple scalar types. /// </summary> sealed class ScalarTypeInfo : TraceLoggingTypeInfo { Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc; TraceLoggingDataType nativeFormat; private ScalarTypeInfo( Type type, Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc, TraceLoggingDataType nativeFormat) : base(type) { this.formatFunc = formatFunc; this.nativeFormat = nativeFormat; } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, formatFunc(format, nativeFormat)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar(value); } public static TraceLoggingTypeInfo Boolean() { return new ScalarTypeInfo(typeof(Boolean), Statics.Format8, TraceLoggingDataType.Boolean8); } public static TraceLoggingTypeInfo Byte() { return new ScalarTypeInfo(typeof(Byte), Statics.Format8, TraceLoggingDataType.UInt8); } public static TraceLoggingTypeInfo SByte() { return new ScalarTypeInfo(typeof(SByte), Statics.Format8, TraceLoggingDataType.Int8); } public static TraceLoggingTypeInfo Char() { return new ScalarTypeInfo(typeof(Char), Statics.Format16, TraceLoggingDataType.Char16); } public static TraceLoggingTypeInfo Int16() { return new ScalarTypeInfo(typeof(Int16), Statics.Format16, TraceLoggingDataType.Int16); } public static TraceLoggingTypeInfo UInt16() { return new ScalarTypeInfo(typeof(UInt16), Statics.Format16, TraceLoggingDataType.UInt16); } public static TraceLoggingTypeInfo Int32() { return new ScalarTypeInfo(typeof(Int32), Statics.Format32, TraceLoggingDataType.Int32); } public static TraceLoggingTypeInfo UInt32() { return new ScalarTypeInfo(typeof(UInt32), Statics.Format32, TraceLoggingDataType.UInt32); } public static TraceLoggingTypeInfo Int64() { return new ScalarTypeInfo(typeof(Int64), Statics.Format64, TraceLoggingDataType.Int64); } public static TraceLoggingTypeInfo UInt64() { return new ScalarTypeInfo(typeof(UInt64), Statics.Format64, TraceLoggingDataType.UInt64); } public static TraceLoggingTypeInfo IntPtr() { return new ScalarTypeInfo(typeof(IntPtr), Statics.FormatPtr, Statics.IntPtrType); } public static TraceLoggingTypeInfo UIntPtr() { return new ScalarTypeInfo(typeof(UIntPtr), Statics.FormatPtr, Statics.UIntPtrType); } public static TraceLoggingTypeInfo Single() { return new ScalarTypeInfo(typeof(Single), Statics.Format32, TraceLoggingDataType.Float); } public static TraceLoggingTypeInfo Double() { return new ScalarTypeInfo(typeof(Double), Statics.Format64, TraceLoggingDataType.Double); } public static TraceLoggingTypeInfo Guid() { return new ScalarTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid); } } /// <summary> /// Type handler for arrays of scalars /// </summary> internal sealed class ScalarArrayTypeInfo : TraceLoggingTypeInfo { Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc; TraceLoggingDataType nativeFormat; int elementSize; private ScalarArrayTypeInfo( Type type, Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc, TraceLoggingDataType nativeFormat, int elementSize) : base(type) { this.formatFunc = formatFunc; this.nativeFormat = nativeFormat; this.elementSize = elementSize; } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddArray(name, formatFunc(format, nativeFormat)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddArray(value, elementSize); } public static TraceLoggingTypeInfo Boolean() { return new ScalarArrayTypeInfo(typeof(Boolean[]), Statics.Format8, TraceLoggingDataType.Boolean8, sizeof(Boolean)); } public static TraceLoggingTypeInfo Byte() { return new ScalarArrayTypeInfo(typeof(Byte[]), Statics.Format8, TraceLoggingDataType.UInt8, sizeof(Byte)); } public static TraceLoggingTypeInfo SByte() { return new ScalarArrayTypeInfo(typeof(SByte[]), Statics.Format8, TraceLoggingDataType.Int8, sizeof(SByte)); } public static TraceLoggingTypeInfo Char() { return new ScalarArrayTypeInfo(typeof(Char[]), Statics.Format16, TraceLoggingDataType.Char16, sizeof(Char)); } public static TraceLoggingTypeInfo Int16() { return new ScalarArrayTypeInfo(typeof(Int16[]), Statics.Format16, TraceLoggingDataType.Int16, sizeof(Int16)); } public static TraceLoggingTypeInfo UInt16() { return new ScalarArrayTypeInfo(typeof(UInt16[]), Statics.Format16, TraceLoggingDataType.UInt16, sizeof(UInt16)); } public static TraceLoggingTypeInfo Int32() { return new ScalarArrayTypeInfo(typeof(Int32[]), Statics.Format32, TraceLoggingDataType.Int32, sizeof(Int32)); } public static TraceLoggingTypeInfo UInt32() { return new ScalarArrayTypeInfo(typeof(UInt32[]), Statics.Format32, TraceLoggingDataType.UInt32, sizeof(UInt32)); } public static TraceLoggingTypeInfo Int64() { return new ScalarArrayTypeInfo(typeof(Int64[]), Statics.Format64, TraceLoggingDataType.Int64, sizeof(Int64)); } public static TraceLoggingTypeInfo UInt64() { return new ScalarArrayTypeInfo(typeof(UInt64[]), Statics.Format64, TraceLoggingDataType.UInt64, sizeof(UInt64)); } public static TraceLoggingTypeInfo IntPtr() { return new ScalarArrayTypeInfo(typeof(IntPtr[]), Statics.FormatPtr, Statics.IntPtrType, System.IntPtr.Size); } public static TraceLoggingTypeInfo UIntPtr() { return new ScalarArrayTypeInfo(typeof(UIntPtr[]), Statics.FormatPtr, Statics.UIntPtrType, System.IntPtr.Size); } public static TraceLoggingTypeInfo Single() { return new ScalarArrayTypeInfo(typeof(Single[]), Statics.Format32, TraceLoggingDataType.Float, sizeof(Single)); } public static TraceLoggingTypeInfo Double() { return new ScalarArrayTypeInfo(typeof(Double[]), Statics.Format64, TraceLoggingDataType.Double, sizeof(Double)); } public unsafe static TraceLoggingTypeInfo Guid() { return new ScalarArrayTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid, sizeof(Guid)); } } /// <summary> /// TraceLogging: Type handler for String. /// </summary> internal sealed class StringTypeInfo : TraceLoggingTypeInfo { public StringTypeInfo() : base(typeof(string)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddBinary(name, Statics.MakeDataType(TraceLoggingDataType.CountedUtf16String, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddBinary((string)value.ReferenceValue); } public override object GetData(object value) { if(value == null) { return ""; } return value; } } /// <summary> /// TraceLogging: Type handler for DateTime. /// </summary> internal sealed class DateTimeTypeInfo : TraceLoggingTypeInfo { public DateTimeTypeInfo() : base(typeof(DateTime)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.FileTime, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { var ticks = value.ScalarValue.AsDateTime.Ticks; collector.AddScalar(ticks < 504911232000000000 ? 0 : ticks - 504911232000000000); } } /// <summary> /// TraceLogging: Type handler for DateTimeOffset. /// </summary> internal sealed class DateTimeOffsetTypeInfo : TraceLoggingTypeInfo { public DateTimeOffsetTypeInfo() : base(typeof(DateTimeOffset)) { } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { var group = collector.AddGroup(name); group.AddScalar("Ticks", Statics.MakeDataType(TraceLoggingDataType.FileTime, format)); group.AddScalar("Offset", TraceLoggingDataType.Int64); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { var dateTimeOffset = value.ScalarValue.AsDateTimeOffset; var ticks = dateTimeOffset.Ticks; collector.AddScalar(ticks < 504911232000000000 ? 0 : ticks - 504911232000000000); collector.AddScalar(dateTimeOffset.Offset.Ticks); } } /// <summary> /// TraceLogging: Type handler for TimeSpan. /// </summary> internal sealed class TimeSpanTypeInfo : TraceLoggingTypeInfo { public TimeSpanTypeInfo() : base(typeof(TimeSpan)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Int64, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar(value.ScalarValue.AsTimeSpan.Ticks); } } /// <summary> /// TraceLogging: Type handler for Decimal. (Note: not full-fidelity, exposed as Double.) /// </summary> internal sealed class DecimalTypeInfo : TraceLoggingTypeInfo { public DecimalTypeInfo() : base(typeof(Decimal)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Double, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar((double)value.ScalarValue.AsDecimal); } } /// <summary> /// TraceLogging: Type handler for Nullable. /// </summary> internal sealed class NullableTypeInfo : TraceLoggingTypeInfo { private readonly TraceLoggingTypeInfo valueInfo; private readonly Func<PropertyValue, PropertyValue> hasValueGetter; private readonly Func<PropertyValue, PropertyValue> valueGetter; public NullableTypeInfo(Type type, List<Type> recursionCheck) : base(type) { var typeArgs = type.GenericTypeArguments; Debug.Assert(typeArgs.Length == 1); this.valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck); this.hasValueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("HasValue")); this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value")); } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { var group = collector.AddGroup(name); group.AddScalar("HasValue", TraceLoggingDataType.Boolean8); this.valueInfo.WriteMetadata(group, "Value", format); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { var hasValue = hasValueGetter(value); collector.AddScalar(hasValue); var val = hasValue.ScalarValue.AsBoolean ? valueGetter(value) : valueInfo.PropertyValueFactory(Activator.CreateInstance(valueInfo.DataType)); this.valueInfo.WriteData(collector, val); } } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- using System; using System.Drawing; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Timers; using System.Windows.Forms; using MatterHackers.VectorMath; namespace MatterHackers.Agg.UI { public abstract class WinformsSystemWindow : Form, IPlatformWindow { public static bool SingleWindowMode { get; set; } = false; public static bool EnableInputHook { get; set; } = true; public static bool ShowingSystemDialog { get; set; } = false; public static WinformsSystemWindow MainWindowsFormsWindow { get; private set; } public static Func<SystemWindow, FormInspector> InspectorCreator { get; set; } private static System.Timers.Timer idleCallBackTimer = null; private static bool processingOnIdle = false; private static readonly object SingleInvokeLock = new object(); protected WinformsEventSink EventSink; private SystemWindow _systemWindow; private int drawCount = 0; private int onPaintCount; private bool enableIdleProcessing; public SystemWindow AggSystemWindow { get => _systemWindow; set { _systemWindow = value; if (_systemWindow != null) { this.Caption = _systemWindow.Title; if (SingleWindowMode) { if (firstWindow) { this.MinimumSize = _systemWindow.MinimumSize; } // Set this system window as the event target this.EventSink?.SetActiveSystemWindow(_systemWindow); } else { this.MinimumSize = _systemWindow.MinimumSize; } } } } public bool IsMainWindow { get; } = false; public bool IsInitialized { get; set; } = false; public WinformsSystemWindow() { if (idleCallBackTimer == null) { idleCallBackTimer = new System.Timers.Timer(); // call up to 100 times a second idleCallBackTimer.Interval = 10; idleCallBackTimer.Elapsed += InvokePendingOnIdleActions; idleCallBackTimer.Start(); } // Track first window if (MainWindowsFormsWindow == null) { MainWindowsFormsWindow = this; IsMainWindow = true; } this.TitleBarHeight = RectangleToScreen(ClientRectangle).Top - this.Top; this.AllowDrop = true; string iconPath = File.Exists("application.ico") ? "application.ico" : "../MonoBundle/StaticData/application.ico"; try { if (File.Exists(iconPath)) { this.Icon = new Icon(iconPath); } } catch { } } protected override void OnClosed(EventArgs e) { if (IsMainWindow) { // Ensure that when the MainWindow is closed, we null the field so we can recreate the MainWindow MainWindowsFormsWindow = null; } AggSystemWindow = null; base.OnClosed(e); } public void ReleaseOnIdleGuard() { lock (SingleInvokeLock) { processingOnIdle = false; } } private void InvokePendingOnIdleActions(object sender, ElapsedEventArgs e) { if (!this.IsDisposed) { lock (SingleInvokeLock) { if (!enableIdleProcessing) { // There's a race between the idle timer calling this handler and the code to // start the main event loop. Reaching this handler first seems to cause the // app to get stuck when running the automation test suite on Linux. return; } if (processingOnIdle) { // If the pending invoke has not completed, skip the timer event return; } processingOnIdle = true; } try { if (InvokeRequired) { Invoke(new Action(UiThread.InvokePendingActions)); } else { UiThread.InvokePendingActions(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { lock (SingleInvokeLock) { processingOnIdle = false; } } } } public abstract Graphics2D NewGraphics2D(); protected override void OnPaint(PaintEventArgs paintEventArgs) { if (AggSystemWindow == null || AggSystemWindow.HasBeenClosed) { return; } base.OnPaint(paintEventArgs); if (ShowingSystemDialog) { // We do this because calling Invalidate within an OnPaint message will cause our // SaveDialog to not show its 'overwrite' dialog if needed. // We use the Invalidate to cause a continuous pump of the OnPaint message to call our OnIdle. // We could figure another solution but it must be very careful to ensure we don't break SaveDialog return; } if (ClientSize.Width > 0 && ClientSize.Height > 0) { drawCount++; var graphics2D = this.NewGraphics2D(); if (!SingleWindowMode) { // We must call on draw background as this is effectively our child and that is the way it is done in GuiWidget. // Parents call child OnDrawBackground before they call OnDraw AggSystemWindow.OnDrawBackground(graphics2D); AggSystemWindow.OnDraw(graphics2D); } else { for (var i = 0; i < this.WindowProvider.OpenWindows.Count; i++) { graphics2D.FillRectangle(this.WindowProvider.OpenWindows[0].LocalBounds, new Color(Color.Black, 160)); this.WindowProvider.OpenWindows[i].OnDraw(graphics2D); } } /* var bitmap = new Bitmap((int)SystemWindow.Width, (int)SystemWindow.Height); paintEventArgs.Graphics.DrawImage(bitmap, 0, 0); bitmap.Save($"c:\\temp\\gah-{DateTime.Now.Ticks}.png"); */ CopyBackBufferToScreen(paintEventArgs.Graphics); } // use this to debug that windows are drawing and updating. // onPaintCount++; // Text = string.Format("Draw {0}, OnPaint {1}", drawCount, onPaintCount); } public abstract void CopyBackBufferToScreen(Graphics displayGraphics); protected override void OnPaintBackground(PaintEventArgs e) { // don't call this so that windows will not erase the background. // base.OnPaintBackground(e); } protected override void OnResize(EventArgs e) { var systemWindow = AggSystemWindow; if (systemWindow != null) { systemWindow.LocalBounds = new RectangleDouble(0, 0, ClientSize.Width, ClientSize.Height); // Wait until the control is initialized (and thus WindowState has been set) to ensure we don't wipe out // the persisted data before its loaded if (this.IsInitialized) { // Push the current maximized state into the SystemWindow where it can be used or persisted by Agg applications systemWindow.Maximized = this.WindowState == FormWindowState.Maximized; } systemWindow.Invalidate(); } base.OnResize(e); } protected override void SetVisibleCore(bool value) { // Force Activation/BringToFront behavior when Visibility enabled. This ensures Agg forms // always come to front after ShowSystemWindow() if (value) { this.Activate(); } base.SetVisibleCore(value); } private bool winformAlreadyClosing = false; protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { if (AggSystemWindow != null && !AggSystemWindow.HasBeenClosed) { // Call on closing and check if we can close (a "do you want to save" might cancel the close. :). var eventArgs = new ClosingEventArgs(); AggSystemWindow.OnClosing(eventArgs); if (eventArgs.Cancel) { e.Cancel = true; } else { // Stop the RunOnIdle timer/pump if (this.IsMainWindow) { idleCallBackTimer.Elapsed -= InvokePendingOnIdleActions; idleCallBackTimer.Stop(); // Workaround for "Cannot access disposed object." exception // https://stackoverflow.com/a/9669702/84369 - ".Stop() without .DoEvents() is not enough, as it'll dispose objects without waiting for your thread to finish its work" Application.DoEvents(); } // Close the SystemWindow if (AggSystemWindow != null && !AggSystemWindow.HasBeenClosed) { // Store that the Close operation started here winformAlreadyClosing = true; AggSystemWindow.Close(); } } } base.OnClosing(e); } public ISystemWindowProvider WindowProvider { get; set; } public new virtual Keys ModifierKeys => (Keys)Control.ModifierKeys; // TODO: Why is this member named Caption instead of Title? public string Caption { get => this.Text; set => this.Text = value; } public Point2D DesktopPosition { get => new Point2D(this.DesktopLocation.X, this.DesktopLocation.Y); set { if (!this.Visible) { this.StartPosition = FormStartPosition.Manual; } this.DesktopLocation = new Point(value.x, value.y); } } public new void Show() { this.ClientSize = new Size((int)AggSystemWindow.Width, (int)AggSystemWindow.Height); // Center the window if specified on the SystemWindow if (MainWindowsFormsWindow != this && AggSystemWindow.CenterInParent) { Rectangle desktopBounds = MainWindowsFormsWindow.DesktopBounds; RectangleDouble newItemBounds = AggSystemWindow.LocalBounds; this.Left = desktopBounds.X + desktopBounds.Width / 2 - (int)newItemBounds.Width / 2; this.Top = desktopBounds.Y + desktopBounds.Height / 2 - (int)newItemBounds.Height / 2 - TitleBarHeight / 2; } else if (AggSystemWindow.InitialDesktopPosition == new Point2D(-1, -1)) { this.CenterToScreen(); } else { this.StartPosition = FormStartPosition.Manual; this.DesktopPosition = AggSystemWindow.InitialDesktopPosition; } if (MainWindowsFormsWindow != this && AggSystemWindow.AlwaysOnTopOfMain) { Show(MainWindowsFormsWindow); } else { base.Show(); } } public void ShowModal() { // Release the onidle guard so that the onidle pump continues processing while we block at ShowDialog below Task.Run(() => this.ReleaseOnIdleGuard()); if (MainWindowsFormsWindow != this && AggSystemWindow.CenterInParent) { Rectangle mainBounds = MainWindowsFormsWindow.DesktopBounds; RectangleDouble newItemBounds = AggSystemWindow.LocalBounds; this.Left = mainBounds.X + mainBounds.Width / 2 - (int)newItemBounds.Width / 2; this.Top = mainBounds.Y + mainBounds.Height / 2 - (int)newItemBounds.Height / 2; } this.ShowDialog(); } public void Invalidate(RectangleDouble rectToInvalidate) { // Ignore problems with buggy WinForms on Linux try { this.Invalidate(); } catch (Exception e) { Console.WriteLine("WinForms Exception: " + e.Message); } } public void SetCursor(Cursors cursorToSet) { switch (cursorToSet) { case Cursors.Arrow: this.Cursor = System.Windows.Forms.Cursors.Arrow; break; case Cursors.Hand: this.Cursor = System.Windows.Forms.Cursors.Hand; break; case Cursors.IBeam: this.Cursor = System.Windows.Forms.Cursors.IBeam; break; case Cursors.Cross: this.Cursor = System.Windows.Forms.Cursors.Cross; break; case Cursors.Default: this.Cursor = System.Windows.Forms.Cursors.Default; break; case Cursors.Help: this.Cursor = System.Windows.Forms.Cursors.Help; break; case Cursors.HSplit: this.Cursor = System.Windows.Forms.Cursors.HSplit; break; case Cursors.No: this.Cursor = System.Windows.Forms.Cursors.No; break; case Cursors.NoMove2D: this.Cursor = System.Windows.Forms.Cursors.NoMove2D; break; case Cursors.NoMoveHoriz: this.Cursor = System.Windows.Forms.Cursors.NoMoveHoriz; break; case Cursors.NoMoveVert: this.Cursor = System.Windows.Forms.Cursors.NoMoveVert; break; case Cursors.PanEast: this.Cursor = System.Windows.Forms.Cursors.PanEast; break; case Cursors.PanNE: this.Cursor = System.Windows.Forms.Cursors.PanNE; break; case Cursors.PanNorth: this.Cursor = System.Windows.Forms.Cursors.PanNorth; break; case Cursors.PanNW: this.Cursor = System.Windows.Forms.Cursors.PanNW; break; case Cursors.PanSE: this.Cursor = System.Windows.Forms.Cursors.PanSE; break; case Cursors.PanSouth: this.Cursor = System.Windows.Forms.Cursors.PanSouth; break; case Cursors.PanSW: this.Cursor = System.Windows.Forms.Cursors.PanSW; break; case Cursors.PanWest: this.Cursor = System.Windows.Forms.Cursors.PanWest; break; case Cursors.SizeAll: this.Cursor = System.Windows.Forms.Cursors.SizeAll; break; case Cursors.SizeNESW: this.Cursor = System.Windows.Forms.Cursors.SizeNESW; break; case Cursors.SizeNS: this.Cursor = System.Windows.Forms.Cursors.SizeNS; break; case Cursors.SizeNWSE: this.Cursor = System.Windows.Forms.Cursors.SizeNWSE; break; case Cursors.SizeWE: this.Cursor = System.Windows.Forms.Cursors.SizeWE; break; case Cursors.UpArrow: this.Cursor = System.Windows.Forms.Cursors.UpArrow; break; case Cursors.VSplit: this.Cursor = System.Windows.Forms.Cursors.VSplit; break; case Cursors.WaitCursor: this.Cursor = System.Windows.Forms.Cursors.WaitCursor; break; } } public int TitleBarHeight { get; private set; } = 0; public new Vector2 MinimumSize { get => new Vector2(base.MinimumSize.Width, base.MinimumSize.Height); set { var clientSize = new Size((int)Math.Ceiling(value.X), (int)Math.Ceiling(value.Y)); var windowSize = new Size( clientSize.Width + this.Width - this.ClientSize.Width, clientSize.Height + this.Height - this.ClientSize.Height); base.MinimumSize = windowSize; } } private static bool firstWindow = true; public void ShowSystemWindow(SystemWindow systemWindow) { // If ShowSystemWindow is called on loaded/visible SystemWindow, call BringToFront and exit if (systemWindow.PlatformWindow == this && !SingleWindowMode) { this.BringToFront(); return; } // Set the active SystemWindow & PlatformWindow references this.AggSystemWindow = systemWindow; systemWindow.PlatformWindow = this; systemWindow.AnchorAll(); if (firstWindow) { firstWindow = false; this.Show(); // Enable idle processing now that the window is ready to handle events. lock (SingleInvokeLock) { enableIdleProcessing = true; } Application.Run(this); } else if (!SingleWindowMode) { UiThread.RunOnIdle(() => { if (systemWindow.IsModal) { this.ShowModal(); } else { this.Show(); this.BringToFront(); } }); } else if (SingleWindowMode) { // Notify the embedded window of its new single windows parent size // If client code has called ShowSystemWindow and we're minimized, we must restore in order // to establish correct window bounds from ClientSize below. Otherwise we're zeroed out and // will create invalid surfaces of (0,0) if (this.WindowState == FormWindowState.Minimized) { this.WindowState = FormWindowState.Normal; } systemWindow.Size = new Vector2( this.ClientSize.Width, this.ClientSize.Height); } } public void CloseSystemWindow(SystemWindow systemWindow) { // Prevent our call to SystemWindow.Close from recursing if (winformAlreadyClosing) { return; } // Check for RootSystemWindow, close if found string windowTypeName = systemWindow.GetType().Name; if ((SingleWindowMode && windowTypeName == "RootSystemWindow") || (MainWindowsFormsWindow != null && systemWindow == MainWindowsFormsWindow.AggSystemWindow && !SingleWindowMode)) { // Close the main (first) PlatformWindow if it's being requested and not this instance if (MainWindowsFormsWindow.InvokeRequired) { MainWindowsFormsWindow.Invoke((Action)MainWindowsFormsWindow.Close); } else { MainWindowsFormsWindow.Close(); } return; } if (SingleWindowMode) { AggSystemWindow = this.WindowProvider.TopWindow; AggSystemWindow?.Invalidate(); } else { if (!this.IsDisposed && !this.Disposing) { if (this.InvokeRequired) { this.Invoke((Action)this.Close); } else { this.Close(); } } } } public class FormInspector : Form { public virtual bool Inspecting { get; set; } = true; } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using MSAst = System.Linq.Expressions; #else using MSAst = Microsoft.Scripting.Ast; #endif #if FEATURE_NUMERICS using System.Numerics; #else using Microsoft.Scripting.Math; #endif using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Compiler.Ast; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; using Utils = Microsoft.Scripting.Ast.Utils; namespace IronPython.Runtime { using Ast = MSAst.Expression; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [PythonType("tuple"), Serializable, DebuggerTypeProxy(typeof(CollectionDebugProxy)), DebuggerDisplay("tuple, {Count} items")] public class PythonTuple : ICollection, IEnumerable, IEnumerable<object>, IList, IList<object>, ICodeFormattable, IExpressionSerializable, #if CLR2 IValueEquality, #endif IStructuralEquatable, IStructuralComparable #if FEATURE_READONLY_COLLECTION_INTERFACE , IReadOnlyList<object> #endif { internal readonly object[] _data; internal static readonly PythonTuple EMPTY = new PythonTuple(); public PythonTuple(object o) { this._data = MakeItems(o); } protected PythonTuple(object[] items) { this._data = items; } public PythonTuple() { this._data = ArrayUtils.EmptyObjects; } internal PythonTuple(PythonTuple other, object o) { this._data = other.Expand(o); } #region Python Constructors // Tuples are immutable so their initialization happens in __new__ // They also explicitly implement __new__ so they can perform the // appropriate caching. public static PythonTuple __new__(CodeContext context, PythonType cls) { if (cls == TypeCache.PythonTuple) { return EMPTY; } else { PythonTuple tupObj = cls.CreateInstance(context) as PythonTuple; if (tupObj == null) throw PythonOps.TypeError("{0} is not a subclass of tuple", cls); return tupObj; } } public static PythonTuple __new__(CodeContext context, PythonType cls, object sequence) { if (sequence == null) throw PythonOps.TypeError("iteration over a non-sequence"); if (cls == TypeCache.PythonTuple) { if (sequence.GetType() == typeof(PythonTuple)) return (PythonTuple)sequence; return new PythonTuple(MakeItems(sequence)); } else { PythonTuple tupObj = cls.CreateInstance(context, sequence) as PythonTuple; if (tupObj == null) throw PythonOps.TypeError("{0} is not a subclass of tuple", cls); return tupObj; } } #endregion #region Python 2.6 Methods public int index(object obj, object start) { return index(obj, Converter.ConvertToIndex(start), _data.Length); } public int index(object obj, [DefaultParameterValue(0)]int start) { return index(obj, start, _data.Length); } public int index(object obj, object start, object end) { return index(obj, Converter.ConvertToIndex(start), Converter.ConvertToIndex(end)); } public int index(object obj, int start, int end) { start = PythonOps.FixSliceIndex(start, _data.Length); end = PythonOps.FixSliceIndex(end, _data.Length); for (int i = start; i < end; i++) { if (PythonOps.EqualRetBool(obj, _data[i])) { return i; } } throw PythonOps.ValueError("tuple.index(x): x not in list"); } public int count(object obj) { int cnt = 0; foreach (object elem in _data) { if (PythonOps.EqualRetBool(obj, elem)) { cnt++; } } return cnt; } #endregion internal static PythonTuple Make(object o) { if (o is PythonTuple) return (PythonTuple)o; return new PythonTuple(MakeItems(o)); } internal static PythonTuple MakeTuple(params object[] items) { if (items.Length == 0) return EMPTY; return new PythonTuple(items); } private static object[] MakeItems(object o) { object[] arr; if (o is PythonTuple) { return ((PythonTuple)o)._data; } else if (o is string) { string s = (string)o; object[] res = new object[s.Length]; for (int i = 0; i < res.Length; i++) { res[i] = ScriptingRuntimeHelpers.CharToString(s[i]); } return res; } else if (o is List) { return ((List)o).GetObjectArray(); } else if ((arr = o as object[])!=null) { return ArrayOps.CopyArray(arr, arr.Length); } else { PerfTrack.NoteEvent(PerfTrack.Categories.OverAllocate, "TupleOA: " + PythonTypeOps.GetName(o)); List<object> l = new List<object>(); IEnumerator i = PythonOps.GetEnumerator(o); while (i.MoveNext()) { l.Add(i.Current); } return l.ToArray(); } } /// <summary> /// Return a copy of this tuple's data array. /// </summary> internal object[] ToArray() { return ArrayOps.CopyArray(_data, _data.Length); } #region ISequence Members public virtual int __len__() { return _data.Length; } public virtual object this[int index] { get { return _data[PythonOps.FixIndex(index, _data.Length)]; } } public virtual object this[object index] { get { return this[Converter.ConvertToIndex(index)]; } } public virtual object this[BigInteger index] { get { return this[(int)index]; } } public virtual object __getslice__(int start, int stop) { Slice.FixSliceArguments(_data.Length, ref start, ref stop); if (start == 0 && stop == _data.Length && this.GetType() == typeof(PythonTuple)) { return this; } return MakeTuple(ArrayOps.GetSlice(_data, start, stop)); } public virtual object this[Slice slice] { get { int start, stop, step; slice.indices(_data.Length, out start, out stop, out step); if (start == 0 && stop == _data.Length && step == 1 && this.GetType() == typeof(PythonTuple)) { return this; } return MakeTuple(ArrayOps.GetSlice(_data, start, stop, step)); } } #endregion #region binary operators public static PythonTuple operator +([NotNull]PythonTuple x, [NotNull]PythonTuple y) { return MakeTuple(ArrayOps.Add(x._data, x._data.Length, y._data, y._data.Length)); } private static PythonTuple MultiplyWorker(PythonTuple self, int count) { if (count <= 0) { return EMPTY; } else if (count == 1 && self.GetType() == typeof(PythonTuple)) { return self; } return MakeTuple(ArrayOps.Multiply(self._data, self._data.Length, count)); } public static PythonTuple operator *(PythonTuple x, int n) { return MultiplyWorker(x, n); } public static PythonTuple operator *(int n, PythonTuple x) { return MultiplyWorker(x, n); } public static object operator *([NotNull]PythonTuple self, [NotNull]Index count) { return PythonOps.MultiplySequence<PythonTuple>(MultiplyWorker, self, count, true); } public static object operator *([NotNull]Index count, [NotNull]PythonTuple self) { return PythonOps.MultiplySequence<PythonTuple>(MultiplyWorker, self, count, false); } public static object operator *([NotNull]PythonTuple self, object count) { int index; if (Converter.TryConvertToIndex(count, out index)) { return self * index; } throw PythonOps.TypeErrorForUnIndexableObject(count); } public static object operator *(object count, [NotNull]PythonTuple self) { int index; if (Converter.TryConvertToIndex(count, out index)) { return index * self; } throw PythonOps.TypeErrorForUnIndexableObject(count); } #endregion #region ICollection Members bool ICollection.IsSynchronized { get { return false; } } public int Count { [PythonHidden] get { return _data.Length; } } [PythonHidden] public void CopyTo(Array array, int index) { Array.Copy(_data, 0, array, index, _data.Length); } object ICollection.SyncRoot { get { return this; } } #endregion public virtual IEnumerator __iter__() { return new TupleEnumerator(this); } #region IEnumerable Members [PythonHidden] public IEnumerator GetEnumerator() { return __iter__(); } #endregion private object[] Expand(object value) { object[] args; int length = _data.Length; if (value == null) args = new object[length]; else args = new object[length + 1]; for (int i = 0; i < length; i++) { args[i] = _data[i]; } if (value != null) { args[length] = value; } return args; } public object __getnewargs__() { // Call "new Tuple()" to force result to be a Tuple (otherwise, it could possibly be a Tuple subclass) return PythonTuple.MakeTuple(new PythonTuple(this)); } #region IEnumerable<object> Members IEnumerator<object> IEnumerable<object>.GetEnumerator() { return new TupleEnumerator(this); } #endregion #region IList<object> Members [PythonHidden] public int IndexOf(object item) { for (int i = 0; i < Count; i++) { if (PythonOps.EqualRetBool(this[i], item)) return i; } return -1; } void IList<object>.Insert(int index, object item) { throw new InvalidOperationException("Tuple is readonly"); } void IList<object>.RemoveAt(int index) { throw new InvalidOperationException("Tuple is readonly"); } object IList<object>.this[int index] { get { return this[index]; } set { throw new InvalidOperationException("Tuple is readonly"); } } #endregion #region ICollection<object> Members void ICollection<object>.Add(object item) { throw new InvalidOperationException("Tuple is readonly"); } void ICollection<object>.Clear() { throw new InvalidOperationException("Tuple is readonly"); } [PythonHidden] public bool Contains(object item) { for (int i = 0; i < _data.Length; i++) { if (PythonOps.EqualRetBool(_data[i], item)) { return true; } } return false; } [PythonHidden] public void CopyTo(object[] array, int arrayIndex) { for (int i = 0; i < Count; i++) { array[arrayIndex + i] = this[i]; } } bool ICollection<object>.IsReadOnly { get { return true; } } bool ICollection<object>.Remove(object item) { throw new InvalidOperationException("Tuple is readonly"); } #endregion #region Rich Comparison Members internal int CompareTo(PythonTuple other) { return PythonOps.CompareArrays(_data, _data.Length, other._data, other._data.Length); } public static bool operator >([NotNull]PythonTuple self, [NotNull]PythonTuple other) { return self.CompareTo(other) > 0; } public static bool operator <([NotNull]PythonTuple self, [NotNull]PythonTuple other) { return self.CompareTo(other) < 0; } public static bool operator >=([NotNull]PythonTuple self, [NotNull]PythonTuple other) { return self.CompareTo(other) >= 0; } public static bool operator <=([NotNull]PythonTuple self, [NotNull]PythonTuple other) { return self.CompareTo(other) <= 0; } #endregion #region IStructuralComparable Members int IStructuralComparable.CompareTo(object obj, IComparer comparer) { PythonTuple other = obj as PythonTuple; if (other == null) { throw new ValueErrorException("expected tuple"); } return PythonOps.CompareArrays(_data, _data.Length, other._data, other._data.Length, comparer); } #endregion public override bool Equals(object obj) { if (!Object.ReferenceEquals(this, obj)) { PythonTuple other = obj as PythonTuple; if (other == null || _data.Length != other._data.Length) { return false; } for (int i = 0; i < _data.Length; i++) { object obj1 = this[i], obj2 = other[i]; if (Object.ReferenceEquals(obj1, obj2)) { continue; } else if (obj1 != null) { if (!obj1.Equals(obj2)) { return false; } } else { return false; } } } return true; } public override int GetHashCode() { int hash1 = 6551; int hash2 = hash1; for (int i = 0; i < _data.Length; i += 2) { hash1 = ((hash1 << 27) + ((hash2 + 1) << 1) + (hash1 >> 5)) ^ (_data[i] == null ? NoneTypeOps.NoneHashCode : _data[i].GetHashCode()); if (i == _data.Length - 1) { break; } hash2 = ((hash2 << 5) + ((hash1 - 1) >> 1) + (hash2 >> 27)) ^ (_data[i + 1] == null ? NoneTypeOps.NoneHashCode : _data[i + 1].GetHashCode()); } return hash1 + (hash2 * 1566083941); } private int GetHashCode(HashDelegate dlg) { int hash1 = 6551; int hash2 = hash1; for (int i = 0; i < _data.Length; i += 2) { hash1 = ((hash1 << 27) + ((hash2 + 1) << 1) + (hash1 >> 5)) ^ dlg(_data[i], ref dlg); if (i == _data.Length - 1) { break; } hash2 = ((hash2 << 5) + ((hash1 - 1) >> 1) + (hash2 >> 27)) ^ dlg(_data[i + 1], ref dlg); } return hash1 + (hash2 * 1566083941); } private int GetHashCode(IEqualityComparer comparer) { int hash1 = 6551; int hash2 = hash1; for (int i = 0; i < _data.Length; i += 2) { hash1 = ((hash1 << 27) + ((hash2 + 1) << 1) + (hash1 >> 5)) ^ comparer.GetHashCode(_data[i]); if (i == _data.Length - 1) { break; } hash2 = ((hash2 << 5) + ((hash1 - 1) >> 1) + (hash2 >> 27)) ^ comparer.GetHashCode(_data[i + 1]); } return hash1 + (hash2 * 1566083941); } public override string ToString() { return __repr__(DefaultContext.Default); } #region IValueEquality Members #if CLR2 int IValueEquality.GetValueHashCode() { return GetHashCode(DefaultContext.DefaultPythonContext.InitialHasher); } bool IValueEquality.ValueEquals(object other) { if (!Object.ReferenceEquals(other, this)) { PythonTuple l = other as PythonTuple; if (l == null || _data.Length != l._data.Length) { return false; } for (int i = 0; i < _data.Length; i++) { object obj1 = _data[i], obj2 = l._data[i]; if (Object.ReferenceEquals(obj1, obj2)) { continue; } else if (!PythonOps.EqualRetBool(obj1, obj2)) { return false; } } } return true; } #endif #endregion #region IStructuralEquatable Members int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { // Optimization for when comparer is IronPython's default IEqualityComparer PythonContext.PythonEqualityComparer pythonComparer = comparer as PythonContext.PythonEqualityComparer; if (pythonComparer != null) { return GetHashCode(pythonComparer.Context.InitialHasher); } return GetHashCode(comparer); } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (!Object.ReferenceEquals(other, this)) { PythonTuple l = other as PythonTuple; if (l == null || _data.Length != l._data.Length) { return false; } for (int i = 0; i < _data.Length; i++) { object obj1 = _data[i], obj2 = l._data[i]; if (Object.ReferenceEquals(obj1, obj2)) { continue; } else if (!comparer.Equals(obj1, obj2)) { return false; } } } return true; } #endregion #region ICodeFormattable Members public virtual string/*!*/ __repr__(CodeContext/*!*/ context) { StringBuilder buf = new StringBuilder(); buf.Append("("); for (int i = 0; i < _data.Length; i++) { if (i > 0) buf.Append(", "); buf.Append(PythonOps.Repr(context, _data[i])); } if (_data.Length == 1) buf.Append(","); buf.Append(")"); return buf.ToString(); } #endregion #region IList Members int IList.Add(object value) { throw new InvalidOperationException("Tuple is readonly"); } void IList.Clear() { throw new InvalidOperationException("Tuple is readonly"); } void IList.Insert(int index, object value) { throw new InvalidOperationException("Tuple is readonly"); } bool IList.IsFixedSize { get { return true; } } bool IList.IsReadOnly { get { return true; } } void IList.Remove(object value) { throw new InvalidOperationException("Tuple is readonly"); } void IList.RemoveAt(int index) { throw new InvalidOperationException("Tuple is readonly"); } object IList.this[int index] { get { return this[index]; } set { throw new InvalidOperationException("Tuple is readonly"); } } #endregion #region IExpressionSerializable Members public MSAst.Expression CreateExpression() { Ast[] items = new Ast[Count]; for (int i = 0; i < items.Length; i++) { items[i] = Utils.Constant(this[i]); } return Ast.Call( AstMethods.MakeTuple, Ast.NewArrayInit( typeof(object), items ) ); } #endregion } /// <summary> /// public class to get optimized /// </summary> [PythonType("tupleiterator")] public sealed class TupleEnumerator : IEnumerable, IEnumerator, IEnumerator<object> { private int _curIndex; private PythonTuple _tuple; public TupleEnumerator(PythonTuple t) { _tuple = t; _curIndex = -1; } #region IEnumerator Members public object Current { get { // access _data directly because this is what CPython does: // class T(tuple): // def __getitem__(self): return None // // for x in T((1,2)): print x // prints 1 and 2 return _tuple._data[_curIndex]; } } public bool MoveNext() { if ((_curIndex + 1) >= _tuple.Count) { return false; } _curIndex++; return true; } public void Reset() { _curIndex = -1; } #endregion #region IDisposable Members public void Dispose() { GC.SuppressFinalize(this); } #endregion #region IEnumerable Members public IEnumerator GetEnumerator() { return this; } #endregion } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.IO; using System.Reflection; using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Data.MySQL { /// <summary> /// A MySQL Database manager /// </summary> public class MySQLManager { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The database connection object /// </summary> private MySqlConnection dbcon; /// <summary> /// Connection string for ADO.net /// </summary> private string connectionString; private const string m_waitTimeoutSelect = "select @@wait_timeout"; /// <summary> /// Wait timeout for our connection in ticks. /// </summary> private long m_waitTimeout; /// <summary> /// Make our storage of the timeout this amount smaller than it actually is, to give us a margin on long /// running database operations. /// </summary> private long m_waitTimeoutLeeway = 60 * TimeSpan.TicksPerSecond; /// <summary> /// Holds the last tick time that the connection was used. /// </summary> private long m_lastConnectionUse; /// <summary> /// Initialises and creates a new MySQL connection and maintains it. /// </summary> /// <param name="hostname">The MySQL server being connected to</param> /// <param name="database">The name of the MySQL database being used</param> /// <param name="username">The username logging into the database</param> /// <param name="password">The password for the user logging in</param> /// <param name="cpooling">Whether to use connection pooling or not, can be one of the following: 'yes', 'true', 'no' or 'false', if unsure use 'false'.</param> /// <param name="port">The MySQL server port</param> public MySQLManager(string hostname, string database, string username, string password, string cpooling, string port) { string s = "Server=" + hostname + ";Port=" + port + ";Database=" + database + ";User ID=" + username + ";Password=" + password + ";Pooling=" + cpooling + ";"; Initialise(s); } /// <summary> /// Initialises and creates a new MySQL connection and maintains it. /// </summary> /// <param name="connect">connectionString</param> public MySQLManager(String connect) { Initialise(connect); } /// <summary> /// Initialises and creates a new MySQL connection and maintains it. /// </summary> /// <param name="connect">connectionString</param> public void Initialise(String connect) { try { connectionString = connect; dbcon = new MySqlConnection(connectionString); try { dbcon.Open(); } catch (Exception e) { throw new Exception("Connection error while using connection string [" + connectionString + "]", e); } m_log.Info("[MYSQL]: Connection established"); GetWaitTimeout(); } catch (Exception e) { throw new Exception("Error initialising MySql Database: " + e.ToString()); } } /// <summary> /// Get the wait_timeout value for our connection /// </summary> protected void GetWaitTimeout() { MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon); using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) { m_waitTimeout = Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway; } dbReader.Close(); cmd.Dispose(); } m_lastConnectionUse = DateTime.Now.Ticks; m_log.DebugFormat( "[REGION DB]: Connection wait timeout {0} seconds", m_waitTimeout / TimeSpan.TicksPerSecond); } /// <summary> /// Should be called before any db operation. This checks to see if the connection has not timed out /// </summary> public void CheckConnection() { //m_log.Debug("[REGION DB]: Checking connection"); long timeNow = DateTime.Now.Ticks; if (timeNow - m_lastConnectionUse > m_waitTimeout || dbcon.State != ConnectionState.Open) { m_log.DebugFormat("[REGION DB]: Database connection has gone away - reconnecting"); Reconnect(); } // Strictly, we should set this after the actual db operation. But it's more convenient to set here rather // than require the code to call another method - the timeout leeway should be large enough to cover the // inaccuracy. m_lastConnectionUse = timeNow; } /// <summary> /// Get the connection being used /// </summary> /// <returns>MySqlConnection Object</returns> public MySqlConnection Connection { get { return dbcon; } } /// <summary> /// Shuts down the database connection /// </summary> public void Close() { dbcon.Close(); dbcon = null; } /// <summary> /// Reconnects to the database /// </summary> public void Reconnect() { m_log.Info("[REGION DB] Reconnecting database"); lock (dbcon) { try { // Close the DB connection dbcon.Close(); // Try reopen it dbcon = new MySqlConnection(connectionString); dbcon.Open(); } catch (Exception e) { m_log.Error("Unable to reconnect to database " + e.ToString()); } } } /// <summary> /// Returns the version of this DB provider /// </summary> /// <returns>A string containing the DB provider</returns> public string getVersion() { Module module = GetType().Module; // string dllName = module.Assembly.ManifestModule.Name; Version dllVersion = module.Assembly.GetName().Version; return string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, dllVersion.Revision); } /// <summary> /// Extract a named string resource from the embedded resources /// </summary> /// <param name="name">name of embedded resource</param> /// <returns>string contained within the embedded resource</returns> private string getResourceString(string name) { Assembly assem = GetType().Assembly; string[] names = assem.GetManifestResourceNames(); foreach (string s in names) { if (s.EndsWith(name)) { using (Stream resource = assem.GetManifestResourceStream(s)) { using (StreamReader resourceReader = new StreamReader(resource)) { string resourceString = resourceReader.ReadToEnd(); return resourceString; } } } } throw new Exception(string.Format("Resource '{0}' was not found", name)); } /// <summary> /// Execute a SQL statement stored in a resource, as a string /// </summary> /// <param name="name">name of embedded resource</param> public void ExecuteResourceSql(string name) { CheckConnection(); MySqlCommand cmd = new MySqlCommand(getResourceString(name), dbcon); cmd.ExecuteNonQuery(); } /// <summary> /// Execute a MySqlCommand /// </summary> /// <param name="sql">sql string to execute</param> public void ExecuteSql(string sql) { CheckConnection(); MySqlCommand cmd = new MySqlCommand(sql, dbcon); cmd.ExecuteNonQuery(); } public void ExecuteParameterizedSql(string sql, Dictionary<string, string> parameters) { CheckConnection(); MySqlCommand cmd = (MySqlCommand)dbcon.CreateCommand(); cmd.CommandText = sql; foreach (KeyValuePair<string, string> param in parameters) { cmd.Parameters.AddWithValue(param.Key, param.Value); } cmd.ExecuteNonQuery(); } /// <summary> /// Given a list of tables, return the version of the tables, as seen in the database /// </summary> /// <param name="tableList"></param> public void GetTableVersion(Dictionary<string, string> tableList) { lock (dbcon) { CheckConnection(); MySqlCommand tablesCmd = new MySqlCommand( "SELECT TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=?dbname", dbcon); tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database); using (MySqlDataReader tables = tablesCmd.ExecuteReader()) { while (tables.Read()) { try { string tableName = (string)tables["TABLE_NAME"]; string comment = (string)tables["TABLE_COMMENT"]; if (tableList.ContainsKey(tableName)) { tableList[tableName] = comment; } } catch (Exception e) { m_log.Error(e.ToString()); } } tables.Close(); } } } // TODO: at some time this code should be cleaned up /// <summary> /// Runs a query with protection against SQL Injection by using parameterised input. /// </summary> /// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param> /// <param name="parameters">The parameters - index so that @y is indexed as 'y'</param> /// <returns>A MySQL DB Command</returns> public IDbCommand Query(string sql, Dictionary<string, object> parameters) { try { CheckConnection(); // Not sure if this one is necessary MySqlCommand dbcommand = (MySqlCommand)dbcon.CreateCommand(); dbcommand.CommandText = sql; foreach (KeyValuePair<string, object> param in parameters) { dbcommand.Parameters.AddWithValue(param.Key, param.Value); } return (IDbCommand)dbcommand; } catch (Exception e) { // Return null if it fails. m_log.Error("Failed during Query generation: " + e.ToString()); return null; } } /// <summary> /// Reads a region row from a database reader /// </summary> /// <param name="reader">An active database reader</param> /// <returns>A region profile</returns> public RegionProfileData readSimRow(IDataReader reader) { RegionProfileData retval = new RegionProfileData(); if (reader.Read()) { // Region Main gotta-have-or-we-return-null parts UInt64 tmp64; if (!UInt64.TryParse(reader["regionHandle"].ToString(), out tmp64)) { return null; } else { retval.regionHandle = tmp64; } UUID tmp_uuid; if (!UUID.TryParse(Convert.ToString(reader["uuid"]), out tmp_uuid)) { return null; } else { retval.UUID = tmp_uuid; } // non-critical parts retval.regionName = (string)reader["regionName"]; retval.originUUID = new UUID(Convert.ToString(reader["originUUID"])); // Secrets retval.regionRecvKey = (string)reader["regionRecvKey"]; retval.regionSecret = (string)reader["regionSecret"]; retval.regionSendKey = (string)reader["regionSendKey"]; // Region Server retval.regionDataURI = (string)reader["regionDataURI"]; retval.regionOnline = false; // Needs to be pinged before this can be set. retval.serverHostName = (string)reader["serverIP"]; retval.serverPort = (uint)reader["serverPort"]; retval.httpPort = Convert.ToUInt32(reader["serverHttpPort"].ToString()); retval.remotingPort = Convert.ToUInt32(reader["serverRemotingPort"].ToString()); // Location retval.regionLocX = Convert.ToUInt32(reader["locX"].ToString()); retval.regionLocY = Convert.ToUInt32(reader["locY"].ToString()); retval.regionLocZ = Convert.ToUInt32(reader["locZ"].ToString()); // Neighbours - 0 = No Override retval.regionEastOverrideHandle = Convert.ToUInt64(reader["eastOverrideHandle"].ToString()); retval.regionWestOverrideHandle = Convert.ToUInt64(reader["westOverrideHandle"].ToString()); retval.regionSouthOverrideHandle = Convert.ToUInt64(reader["southOverrideHandle"].ToString()); retval.regionNorthOverrideHandle = Convert.ToUInt64(reader["northOverrideHandle"].ToString()); // Assets retval.regionAssetURI = (string)reader["regionAssetURI"]; retval.regionAssetRecvKey = (string)reader["regionAssetRecvKey"]; retval.regionAssetSendKey = (string)reader["regionAssetSendKey"]; // Userserver retval.regionUserURI = (string)reader["regionUserURI"]; retval.regionUserRecvKey = (string)reader["regionUserRecvKey"]; retval.regionUserSendKey = (string)reader["regionUserSendKey"]; // World Map Addition UUID.TryParse(Convert.ToString(reader["regionMapTexture"]), out retval.regionMapTextureID); UUID.TryParse(Convert.ToString(reader["owner_uuid"]), out retval.owner_uuid); retval.maturity = Convert.ToUInt32(reader["access"]); } else { return null; } return retval; } /// <summary> /// Reads a reservation row from a database reader /// </summary> /// <param name="reader">An active database reader</param> /// <returns>A reservation data object</returns> public ReservationData readReservationRow(IDataReader reader) { ReservationData retval = new ReservationData(); if (reader.Read()) { retval.gridRecvKey = (string)reader["gridRecvKey"]; retval.gridSendKey = (string)reader["gridSendKey"]; retval.reservationCompany = (string)reader["resCompany"]; retval.reservationMaxX = Convert.ToInt32(reader["resXMax"].ToString()); retval.reservationMaxY = Convert.ToInt32(reader["resYMax"].ToString()); retval.reservationMinX = Convert.ToInt32(reader["resXMin"].ToString()); retval.reservationMinY = Convert.ToInt32(reader["resYMin"].ToString()); retval.reservationName = (string)reader["resName"]; retval.status = Convert.ToInt32(reader["status"].ToString()) == 1; UUID tmp; UUID.TryParse(Convert.ToString(reader["userUUID"]), out tmp); retval.userUUID = tmp; } else { return null; } return retval; } /// <summary> /// Reads an agent row from a database reader /// </summary> /// <param name="reader">An active database reader</param> /// <returns>A user session agent</returns> public UserAgentData readAgentRow(IDataReader reader) { UserAgentData retval = new UserAgentData(); if (reader.Read()) { // Agent IDs UUID tmp; if (!UUID.TryParse(Convert.ToString(reader["UUID"]), out tmp)) return null; retval.ProfileID = tmp; UUID.TryParse(Convert.ToString(reader["sessionID"]), out tmp); retval.SessionID = tmp; UUID.TryParse(Convert.ToString(reader["secureSessionID"]), out tmp); retval.SecureSessionID = tmp; // Agent Who? retval.AgentIP = (string)reader["agentIP"]; retval.AgentPort = Convert.ToUInt32(reader["agentPort"].ToString()); retval.AgentOnline = Convert.ToBoolean(Convert.ToInt16(reader["agentOnline"].ToString())); // Login/Logout times (UNIX Epoch) retval.LoginTime = Convert.ToInt32(reader["loginTime"].ToString()); retval.LogoutTime = Convert.ToInt32(reader["logoutTime"].ToString()); // Current position retval.Region = new UUID(Convert.ToString(reader["currentRegion"])); retval.Handle = Convert.ToUInt64(reader["currentHandle"].ToString()); Vector3 tmp_v; Vector3.TryParse((string)reader["currentPos"], out tmp_v); retval.Position = tmp_v; Vector3.TryParse((string)reader["currentLookAt"], out tmp_v); retval.LookAt = tmp_v; } else { return null; } return retval; } /// <summary> /// Reads a user profile from an active data reader /// </summary> /// <param name="reader">An active database reader</param> /// <returns>A user profile</returns> public UserProfileData readUserRow(IDataReader reader) { UserProfileData retval = new UserProfileData(); if (reader.Read()) { UUID id; if (!UUID.TryParse(Convert.ToString(reader["UUID"]), out id)) return null; retval.ID = id; retval.FirstName = (string)reader["username"]; retval.SurName = (string)reader["lastname"]; retval.Email = (reader.IsDBNull(reader.GetOrdinal("email"))) ? "" : (string)reader["email"]; retval.PasswordHash = (string)reader["passwordHash"]; retval.PasswordSalt = (string)reader["passwordSalt"]; retval.HomeRegion = Convert.ToUInt64(reader["homeRegion"].ToString()); retval.HomeLocation = new Vector3( Convert.ToSingle(reader["homeLocationX"].ToString()), Convert.ToSingle(reader["homeLocationY"].ToString()), Convert.ToSingle(reader["homeLocationZ"].ToString())); retval.HomeLookAt = new Vector3( Convert.ToSingle(reader["homeLookAtX"].ToString()), Convert.ToSingle(reader["homeLookAtY"].ToString()), Convert.ToSingle(reader["homeLookAtZ"].ToString())); UUID regionID = UUID.Zero; UUID.TryParse(reader["homeRegionID"].ToString(), out regionID); // it's ok if it doesn't work; just use UUID.Zero retval.HomeRegionID = regionID; retval.Created = Convert.ToInt32(reader["created"].ToString()); retval.LastLogin = Convert.ToInt32(reader["lastLogin"].ToString()); retval.UserInventoryURI = (string)reader["userInventoryURI"]; retval.UserAssetURI = (string)reader["userAssetURI"]; if (reader.IsDBNull(reader.GetOrdinal("profileAboutText"))) retval.AboutText = ""; else retval.AboutText = (string)reader["profileAboutText"]; if (reader.IsDBNull(reader.GetOrdinal("profileFirstText"))) retval.FirstLifeAboutText = ""; else retval.FirstLifeAboutText = (string)reader["profileFirstText"]; if (reader.IsDBNull(reader.GetOrdinal("profileImage"))) retval.Image = UUID.Zero; else { UUID tmp; UUID.TryParse(Convert.ToString(reader["profileImage"]), out tmp); retval.Image = tmp; } if (reader.IsDBNull(reader.GetOrdinal("profileFirstImage"))) retval.FirstLifeImage = UUID.Zero; else { UUID tmp; UUID.TryParse(Convert.ToString(reader["profileFirstImage"]), out tmp); retval.FirstLifeImage = tmp; } if (reader.IsDBNull(reader.GetOrdinal("webLoginKey"))) { retval.WebLoginKey = UUID.Zero; } else { UUID tmp; UUID.TryParse(Convert.ToString(reader["webLoginKey"]), out tmp); retval.WebLoginKey = tmp; } retval.UserFlags = Convert.ToInt32(reader["userFlags"].ToString()); retval.GodLevel = Convert.ToInt32(reader["godLevel"].ToString()); if (reader.IsDBNull(reader.GetOrdinal("customType"))) retval.CustomType = ""; else retval.CustomType = reader["customType"].ToString(); if (reader.IsDBNull(reader.GetOrdinal("partner"))) { retval.Partner = UUID.Zero; } else { UUID tmp; UUID.TryParse(Convert.ToString(reader["partner"]), out tmp); retval.Partner = tmp; } if (reader.IsDBNull(reader.GetOrdinal("profileURL"))) retval.ProfileURL = ""; else retval.ProfileURL = (string)reader["profileURL"]; } else { return null; } return retval; } /// Inserts a new row into the log database /// </summary> /// <param name="serverDaemon">The daemon which triggered this event</param> /// <param name="target">Who were we operating on when this occured (region UUID, user UUID, etc)</param> /// <param name="methodCall">The method call where the problem occured</param> /// <param name="arguments">The arguments passed to the method</param> /// <param name="priority">How critical is this?</param> /// <param name="logMessage">Extra message info</param> /// <returns>Saved successfully?</returns> public bool insertLogRow(string serverDaemon, string target, string methodCall, string arguments, int priority, string logMessage) { string sql = "INSERT INTO logs (`target`, `server`, `method`, `arguments`, `priority`, `message`) VALUES "; sql += "(?target, ?server, ?method, ?arguments, ?priority, ?message)"; Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["?server"] = serverDaemon; parameters["?target"] = target; parameters["?method"] = methodCall; parameters["?arguments"] = arguments; parameters["?priority"] = priority.ToString(); parameters["?message"] = logMessage; bool returnval = false; try { IDbCommand result = Query(sql, parameters); if (result.ExecuteNonQuery() == 1) returnval = true; result.Dispose(); } catch (Exception e) { m_log.Error(e.ToString()); return false; } return returnval; } /// <summary> /// Creates a new user and inserts it into the database /// </summary> /// <param name="uuid">User ID</param> /// <param name="username">First part of the login</param> /// <param name="lastname">Second part of the login</param> /// <param name="passwordHash">A salted hash of the users password</param> /// <param name="passwordSalt">The salt used for the password hash</param> /// <param name="homeRegion">A regionHandle of the users home region</param> /// <param name="homeRegionID"> The UUID of the user's home region</param> /// <param name="homeLocX">Home region position vector</param> /// <param name="homeLocY">Home region position vector</param> /// <param name="homeLocZ">Home region position vector</param> /// <param name="homeLookAtX">Home region 'look at' vector</param> /// <param name="homeLookAtY">Home region 'look at' vector</param> /// <param name="homeLookAtZ">Home region 'look at' vector</param> /// <param name="created">Account created (unix timestamp)</param> /// <param name="lastlogin">Last login (unix timestamp)</param> /// <param name="inventoryURI">Users inventory URI</param> /// <param name="assetURI">Users asset URI</param> /// <param name="canDoMask">I can do mask</param> /// <param name="wantDoMask">I want to do mask</param> /// <param name="aboutText">Profile text</param> /// <param name="firstText">Firstlife text</param> /// <param name="profileImage">UUID for profile image</param> /// <param name="firstImage">UUID for firstlife image</param> /// <param name="webLoginKey">Ignored</param> /// <param name="profileURL">ProfileURL</param> /// <returns>Success?</returns> public bool insertUserRow(UUID uuid, string username, string lastname, string email, string passwordHash, string passwordSalt, UInt64 homeRegion, UUID homeRegionID, float homeLocX, float homeLocY, float homeLocZ, float homeLookAtX, float homeLookAtY, float homeLookAtZ, int created, int lastlogin, string inventoryURI, string assetURI, string aboutText, string firstText, UUID profileImage, UUID firstImage, UUID webLoginKey, int userFlags, int godLevel, string customType, UUID partner, string ProfileURL) { m_log.Debug("[MySQLManager]: Fetching profile for " + uuid.ToString()); string sql = "INSERT INTO users (`UUID`, `username`, `lastname`, `email`, `passwordHash`, `passwordSalt`, `homeRegion`, `homeRegionID`, "; sql += "`homeLocationX`, `homeLocationY`, `homeLocationZ`, `homeLookAtX`, `homeLookAtY`, `homeLookAtZ`, `created`, "; sql += "`lastLogin`, `userInventoryURI`, `userAssetURI`, "; sql += "`profileFirstText`, `profileImage`, `profileFirstImage`, `webLoginKey`, `userFlags`, `godLevel`, `customType`, `partner`, `profileURL`) VALUES "; sql += "(?UUID, ?username, ?lastname, ?email, ?passwordHash, ?passwordSalt, ?homeRegion, ?homeRegionID, "; sql += "?homeLocationX, ?homeLocationY, ?homeLocationZ, ?homeLookAtX, ?homeLookAtY, ?homeLookAtZ, ?created, "; sql += "?lastLogin, ?userInventoryURI, ?userAssetURI, "; sql += "?profileFirstText, ?profileImage, ?profileFirstImage, ?webLoginKey, ?userFlags, ?godLevel, ?customType, ?partner, ?profileURL)"; Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["?UUID"] = uuid.ToString(); parameters["?username"] = username; parameters["?lastname"] = lastname; parameters["?email"] = email; parameters["?passwordHash"] = passwordHash; parameters["?passwordSalt"] = passwordSalt; parameters["?homeRegion"] = homeRegion; parameters["?homeRegionID"] = homeRegionID.ToString(); parameters["?homeLocationX"] = homeLocX; parameters["?homeLocationY"] = homeLocY; parameters["?homeLocationZ"] = homeLocZ; parameters["?homeLookAtX"] = homeLookAtX; parameters["?homeLookAtY"] = homeLookAtY; parameters["?homeLookAtZ"] = homeLookAtZ; parameters["?created"] = created; parameters["?lastLogin"] = lastlogin; parameters["?userInventoryURI"] = inventoryURI; parameters["?userAssetURI"] = assetURI; parameters["?profileAboutText"] = aboutText; parameters["?profileFirstText"] = firstText; parameters["?profileImage"] = profileImage.ToString(); parameters["?profileFirstImage"] = firstImage.ToString(); parameters["?webLoginKey"] = webLoginKey.ToString(); parameters["?userFlags"] = userFlags; parameters["?godLevel"] = godLevel; parameters["?customType"] = customType == null ? "" : customType; parameters["?partner"] = partner.ToString(); parameters["?profileURL"] = ProfileURL; bool returnval = false; try { IDbCommand result = Query(sql, parameters); if (result.ExecuteNonQuery() == 1) returnval = true; result.Dispose(); } catch (Exception e) { m_log.Error(e.ToString()); return false; } //m_log.Debug("[MySQLManager]: Fetch user retval == " + returnval.ToString()); return returnval; } /// <summary> /// Update user data into the database where User ID = uuid /// </summary> /// <param name="uuid">User ID</param> /// <param name="username">First part of the login</param> /// <param name="lastname">Second part of the login</param> /// <param name="passwordHash">A salted hash of the users password</param> /// <param name="passwordSalt">The salt used for the password hash</param> /// <param name="homeRegion">A regionHandle of the users home region</param> /// <param name="homeLocX">Home region position vector</param> /// <param name="homeLocY">Home region position vector</param> /// <param name="homeLocZ">Home region position vector</param> /// <param name="homeLookAtX">Home region 'look at' vector</param> /// <param name="homeLookAtY">Home region 'look at' vector</param> /// <param name="homeLookAtZ">Home region 'look at' vector</param> /// <param name="created">Account created (unix timestamp)</param> /// <param name="lastlogin">Last login (unix timestamp)</param> /// <param name="inventoryURI">Users inventory URI</param> /// <param name="assetURI">Users asset URI</param> /// <param name="canDoMask">I can do mask</param> /// <param name="wantDoMask">I want to do mask</param> /// <param name="aboutText">Profile text</param> /// <param name="firstText">Firstlife text</param> /// <param name="profileImage">UUID for profile image</param> /// <param name="firstImage">UUID for firstlife image</param> /// <param name="webLoginKey">UUID for weblogin Key</param> /// <param name="profileURL">Profile URL text</param> /// <returns>Success?</returns> public bool updateUserRow(UUID uuid, string username, string lastname, string email, string passwordHash, string passwordSalt, UInt64 homeRegion, UUID homeRegionID, float homeLocX, float homeLocY, float homeLocZ, float homeLookAtX, float homeLookAtY, float homeLookAtZ, int created, int lastlogin, string inventoryURI, string assetURI, string profileURL, string aboutText, string firstText, UUID profileImage, UUID firstImage, UUID webLoginKey, int userFlags, int godLevel, string customType, UUID partner) { string sql = "UPDATE users SET `username` = ?username , `lastname` = ?lastname, `email` = ?email "; sql += ", `passwordHash` = ?passwordHash , `passwordSalt` = ?passwordSalt , "; sql += "`homeRegion` = ?homeRegion , `homeRegionID` = ?homeRegionID, `homeLocationX` = ?homeLocationX , "; sql += "`homeLocationY` = ?homeLocationY , `homeLocationZ` = ?homeLocationZ , "; sql += "`homeLookAtX` = ?homeLookAtX , `homeLookAtY` = ?homeLookAtY , "; sql += "`homeLookAtZ` = ?homeLookAtZ , `created` = ?created , `lastLogin` = ?lastLogin , "; sql += "`userInventoryURI` = ?userInventoryURI , `userAssetURI` = ?userAssetURI , "; sql += "`profileURL` =?profileURL , "; sql += "`profileAboutText` = ?profileAboutText , `profileFirstText` = ?profileFirstText, "; sql += "`profileImage` = ?profileImage , `profileFirstImage` = ?profileFirstImage , "; sql += "`userFlags` = ?userFlags , `godLevel` = ?godLevel , "; sql += "`customType` = ?customType , `partner` = ?partner , "; sql += "`webLoginKey` = ?webLoginKey WHERE UUID = ?UUID"; Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["?UUID"] = uuid.ToString(); parameters["?username"] = username; parameters["?lastname"] = lastname; parameters["?email"] = email; parameters["?passwordHash"] = passwordHash; parameters["?passwordSalt"] = passwordSalt; parameters["?homeRegion"] = homeRegion; parameters["?homeRegionID"] = homeRegionID.ToString(); parameters["?homeLocationX"] = homeLocX; parameters["?homeLocationY"] = homeLocY; parameters["?homeLocationZ"] = homeLocZ; parameters["?homeLookAtX"] = homeLookAtX; parameters["?homeLookAtY"] = homeLookAtY; parameters["?homeLookAtZ"] = homeLookAtZ; parameters["?created"] = created; parameters["?lastLogin"] = lastlogin; parameters["?userInventoryURI"] = inventoryURI; parameters["?userAssetURI"] = assetURI; parameters["?profileURL"] = profileURL; parameters["?profileAboutText"] = aboutText; parameters["?profileFirstText"] = firstText; parameters["?profileImage"] = profileImage.ToString(); parameters["?profileFirstImage"] = firstImage.ToString(); parameters["?webLoginKey"] = webLoginKey.ToString(); parameters["?userFlags"] = userFlags; parameters["?godLevel"] = godLevel; parameters["?customType"] = customType == null ? "" : customType; parameters["?partner"] = partner.ToString(); bool returnval = false; try { IDbCommand result = Query(sql, parameters); if (result.ExecuteNonQuery() == 1) returnval = true; result.Dispose(); } catch (Exception e) { m_log.Error(e.ToString()); return false; } //m_log.Debug("[MySQLManager]: update user retval == " + returnval.ToString()); return returnval; } /// <summary> /// Inserts a new region into the database /// </summary> /// <param name="regiondata">The region to insert</param> /// <returns>Success?</returns> public bool insertRegion(RegionProfileData regiondata) { bool GRID_ONLY_UPDATE_NECESSARY_DATA = false; string sql = String.Empty; if (GRID_ONLY_UPDATE_NECESSARY_DATA) { sql += "INSERT INTO "; } else { sql += "REPLACE INTO "; } sql += "regions (regionHandle, regionName, uuid, regionRecvKey, regionSecret, regionSendKey, regionDataURI, "; sql += "serverIP, serverPort, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, "; // part of an initial brutish effort to provide accurate information (as per the xml region spec) // wrt the ownership of a given region // the (very bad) assumption is that this value is being read and handled inconsistently or // not at all. Current strategy is to put the code in place to support the validity of this information // and to roll forward debugging any issues from that point // // this particular section of the mod attempts to implement the commit of a supplied value // server for the UUID of the region's owner (master avatar). It consists of the addition of the column and value to the relevant sql, // as well as the related parameterization sql += "regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture, serverHttpPort, serverRemotingPort, owner_uuid, originUUID, access) VALUES "; sql += "(?regionHandle, ?regionName, ?uuid, ?regionRecvKey, ?regionSecret, ?regionSendKey, ?regionDataURI, "; sql += "?serverIP, ?serverPort, ?locX, ?locY, ?locZ, ?eastOverrideHandle, ?westOverrideHandle, ?southOverrideHandle, ?northOverrideHandle, ?regionAssetURI, ?regionAssetRecvKey, "; sql += "?regionAssetSendKey, ?regionUserURI, ?regionUserRecvKey, ?regionUserSendKey, ?regionMapTexture, ?serverHttpPort, ?serverRemotingPort, ?owner_uuid, ?originUUID, ?access)"; if (GRID_ONLY_UPDATE_NECESSARY_DATA) { sql += "ON DUPLICATE KEY UPDATE serverIP = ?serverIP, serverPort = ?serverPort, owner_uuid - ?owner_uuid;"; } else { sql += ";"; } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["?regionHandle"] = regiondata.regionHandle.ToString(); parameters["?regionName"] = regiondata.regionName.ToString(); parameters["?uuid"] = regiondata.UUID.ToString(); parameters["?regionRecvKey"] = regiondata.regionRecvKey.ToString(); parameters["?regionSecret"] = regiondata.regionSecret.ToString(); parameters["?regionSendKey"] = regiondata.regionSendKey.ToString(); parameters["?regionDataURI"] = regiondata.regionDataURI.ToString(); parameters["?serverIP"] = regiondata.serverHostName.ToString(); parameters["?serverPort"] = regiondata.serverPort.ToString(); parameters["?locX"] = regiondata.regionLocX.ToString(); parameters["?locY"] = regiondata.regionLocY.ToString(); parameters["?locZ"] = regiondata.regionLocZ.ToString(); parameters["?eastOverrideHandle"] = regiondata.regionEastOverrideHandle.ToString(); parameters["?westOverrideHandle"] = regiondata.regionWestOverrideHandle.ToString(); parameters["?northOverrideHandle"] = regiondata.regionNorthOverrideHandle.ToString(); parameters["?southOverrideHandle"] = regiondata.regionSouthOverrideHandle.ToString(); parameters["?regionAssetURI"] = regiondata.regionAssetURI.ToString(); parameters["?regionAssetRecvKey"] = regiondata.regionAssetRecvKey.ToString(); parameters["?regionAssetSendKey"] = regiondata.regionAssetSendKey.ToString(); parameters["?regionUserURI"] = regiondata.regionUserURI.ToString(); parameters["?regionUserRecvKey"] = regiondata.regionUserRecvKey.ToString(); parameters["?regionUserSendKey"] = regiondata.regionUserSendKey.ToString(); parameters["?regionMapTexture"] = regiondata.regionMapTextureID.ToString(); parameters["?serverHttpPort"] = regiondata.httpPort.ToString(); parameters["?serverRemotingPort"] = regiondata.remotingPort.ToString(); parameters["?owner_uuid"] = regiondata.owner_uuid.ToString(); parameters["?originUUID"] = regiondata.originUUID.ToString(); parameters["?access"] = regiondata.maturity.ToString(); bool returnval = false; try { IDbCommand result = Query(sql, parameters); // int x; // if ((x = result.ExecuteNonQuery()) > 0) // { // returnval = true; // } if (result.ExecuteNonQuery() > 0) { returnval = true; } result.Dispose(); } catch (Exception e) { m_log.Error(e.ToString()); return false; } return returnval; } /// <summary> /// Delete a region from the database /// </summary> /// <param name="uuid">The region to delete</param> /// <returns>Success?</returns> //public bool deleteRegion(RegionProfileData regiondata) public bool deleteRegion(string uuid) { bool returnval = false; string sql = "DELETE FROM regions WHERE uuid = ?uuid;"; Dictionary<string, object> parameters = new Dictionary<string, object>(); try { parameters["?uuid"] = uuid; IDbCommand result = Query(sql, parameters); // int x; // if ((x = result.ExecuteNonQuery()) > 0) // { // returnval = true; // } if (result.ExecuteNonQuery() > 0) { returnval = true; } result.Dispose(); } catch (Exception e) { m_log.Error(e.ToString()); return false; } return returnval; } /// <summary> /// Creates a new agent and inserts it into the database /// </summary> /// <param name="agentdata">The agent data to be inserted</param> /// <returns>Success?</returns> public bool insertAgentRow(UserAgentData agentdata) { string sql = String.Empty; sql += "REPLACE INTO "; sql += "agents (UUID, sessionID, secureSessionID, agentIP, agentPort, agentOnline, loginTime, logoutTime, currentRegion, currentHandle, currentPos, currentLookAt) VALUES "; sql += "(?UUID, ?sessionID, ?secureSessionID, ?agentIP, ?agentPort, ?agentOnline, ?loginTime, ?logoutTime, ?currentRegion, ?currentHandle, ?currentPos, ?currentLookAt);"; Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["?UUID"] = agentdata.ProfileID.ToString(); parameters["?sessionID"] = agentdata.SessionID.ToString(); parameters["?secureSessionID"] = agentdata.SecureSessionID.ToString(); parameters["?agentIP"] = agentdata.AgentIP.ToString(); parameters["?agentPort"] = agentdata.AgentPort.ToString(); parameters["?agentOnline"] = (agentdata.AgentOnline == true) ? "1" : "0"; parameters["?loginTime"] = agentdata.LoginTime.ToString(); parameters["?logoutTime"] = agentdata.LogoutTime.ToString(); parameters["?currentRegion"] = agentdata.Region.ToString(); parameters["?currentHandle"] = agentdata.Handle.ToString(); parameters["?currentPos"] = "<" + (agentdata.Position.X).ToString().Replace(",", ".") + "," + (agentdata.Position.Y).ToString().Replace(",", ".") + "," + (agentdata.Position.Z).ToString().Replace(",", ".") + ">"; parameters["?currentLookAt"] = "<" + (agentdata.LookAt.X).ToString().Replace(",", ".") + "," + (agentdata.LookAt.Y).ToString().Replace(",", ".") + "," + (agentdata.LookAt.Z).ToString().Replace(",", ".") + ">"; bool returnval = false; try { IDbCommand result = Query(sql, parameters); // int x; // if ((x = result.ExecuteNonQuery()) > 0) // { // returnval = true; // } if (result.ExecuteNonQuery() > 0) { returnval = true; } result.Dispose(); } catch (Exception e) { m_log.Error(e.ToString()); return false; } return returnval; } } }
// 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 Microsoft.Protocols.TestTools.StackSdk.Messages.Marshaling; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2 { /// <summary> /// File information classes are numerical values (specified by the Level column in the following table) /// that specify what information for a file is to be queried or set /// </summary> public enum FileInformationClasses { /// <summary> /// This information class is used to query the access rights of a file. /// </summary> FileAccessInformation = 8, /// <summary> /// The buffer alignment required by the underlying device. /// </summary> FileAlignmentInformation = 17, /// <summary> /// This information class is used to query a collection of file information structures. /// </summary> FileAllInformation = 18, /// <summary> /// This information class is used to query alternate name information for a file. /// </summary> FileAlternateNameInformation = 21, /// <summary> /// This information class is used to query for attribute and reparse tag information for a file. /// </summary> FileAttributeTagInformation = 35, /// <summary> /// This information class is used to query or set file information. /// </summary> FileBasicInformation = 4, /// <summary> /// This information class is used to query compression information for a file /// </summary> FileCompressionInformation = 28, /// <summary> /// This information class is used to mark a file for deletion. /// </summary> FileDispositionInformation = 13, /// <summary> /// This information class is used to query for the size of the extended attributes (EA) for a file. /// </summary> FileEaInformation = 7, /// <summary> /// This information class is used to query or set extended attribute (EA) information for a file. /// </summary> FileFullEaInformation = 15, /// <summary> /// This information class is used to query NTFS hard links to an existing file. /// </summary> FileHardLinkInformation = 46, /// <summary> /// This information class is used to query transactional visibility information for the files in a directory /// </summary> FileIdGlobalTxDirectoryInformation = 50, /// <summary> /// This information class is used to query for the file system's 8-byte file reference number for a file. /// </summary> FileInternalInformation = 6, /// <summary> /// This information class is used to query or set the mode of the file. /// </summary> FileModeInformation = 16, /// <summary> /// This information class is used to query for information on a network file open. /// </summary> FileNetworkOpenInformation = 34, /// <summary> /// Windows file systems do not implement this file information class; /// the server will fail it with STATUS_NOT_SUPPORTED. /// </summary> FileNormalizedNameInformation = 48, /// <summary> /// This information class is used to query or set information on a named pipe that is not /// specific to one end of the pipe or another. /// </summary> FilePipeInformation = 23, /// <summary> /// This information class is used to query information on a named pipe /// that is associated with the end of the pipe that is being queried. /// </summary> FilePipeLocalInformation = 24, /// <summary> /// This information class is used to query or set information on a named pipe /// that is associated with the client end of the pipe that is being queried. /// </summary> FilePipeRemoteInformation = 25, /// <summary> /// This information class is used to query or set the position of the file pointer within a file. /// </summary> FilePositionInformation = 14, /// <summary> /// The information class is used to query quota information. /// </summary> FileQuotaInformation = 32, /// <summary> /// This information class is used to rename a file /// </summary> FileRenameInformation = 10, /// <summary> /// This information class is used to query or set reserved bandwidth for a file handle. /// </summary> FileSfioReserveInformation = 44, /// <summary> /// This information class is used to query file information /// </summary> FileStandardInformation = 5, /// <summary> /// This information class is used to query file link information /// </summary> FileStandardLinkInformation = 54, /// <summary> /// This information class is used to enumerate the data streams for a file. /// </summary> FileStreamInformation = 22, /// <summary> /// This information class is used to set end-of-file information for a file. /// </summary> FileEndOfFileInformation = 20, } /// <summary> /// File system information classes are numerical values /// (specified by the Level column in the following table) that specify what information /// on a particular instance of a file system on a volume is to be queried. /// </summary> public enum FileSystemInformationClasses { /// <summary> /// This information class is used to query attribute information for a file system. /// </summary> FileFsAttributeInformation = 5, /// <summary> /// This information class is used to query device information associated with a file system volume. /// </summary> FileFsDeviceInformation = 4, /// <summary> /// This information class is used to query sector size information for a file system volume. /// </summary> FileFsFullSizeInformation = 7, /// <summary> /// This information class is used to query or set the object ID for a file system data element. /// </summary> FileFsObjectIdInformation = 8, /// <summary> /// This information class is used to query sector size information for a file system volume. /// </summary> FileFsSizeInformation = 3, /// <summary> /// This information class is used to query information on a volume on which a file system is mounted. /// </summary> FileFsVolumeInformation = 1 } /// <summary> /// This information class is used to query or set information on a named pipe /// that is associated with the client end of the pipe that is being queried /// </summary> public struct FilePipeRemoteInformation { /// <summary> /// A LARGE_INTEGER that MUST contain the maximum amount of time counted /// in 100-nanosecond intervals that will elapse before transmission of /// data from the client machine to the server. /// </summary> public ulong CollectDataTime; /// <summary> /// A ULONG that MUST contain the maximum size in bytes of data that will /// be collected on the client machine before transmission to the server. /// </summary> public uint MaximumCollectionCount; } /// <summary> /// A 32-bit unsigned integer referring to the current state of the pipe /// </summary> public enum Named_Pipe_State_Value { /// <summary> /// The specified named pipe is in the disconnected state /// </summary> FILE_PIPE_DISCONNECTED_STATE = 0x01, /// <summary> /// The specified named pipe is in the listening state /// </summary> FILE_PIPE_LISTENING_STATE = 0x02, /// <summary> /// The specified named pipe is in the connected state. /// </summary> FILE_PIPE_CONNECTED_STATE = 0x03, /// <summary> /// The specified named pipe is in the closing state. /// </summary> FILE_PIPE_CLOSING_STATE = 0x04 } /// <summary> /// The FSCTL_PIPE_PEEK response returns data from the pipe server's output buffer in the FSCTL output buffer /// </summary> public struct FSCTL_PIPE_PEEK_Reply { /// <summary> /// A 32-bit unsigned integer referring to the current state of the pipe /// </summary> public Named_Pipe_State_Value NamedPipeState; /// <summary> /// A 32-bit unsigned integer that specifies the size, in bytes, of the data available to read from the pipe /// </summary> public uint ReadDataAvailable; /// <summary> /// A 32-bit unsigned integer that specifies the number of messages available /// in the pipe if the pipe has been created as a message-type pipe /// </summary> public uint NumberOfMessages; /// <summary> /// A 32-bit unsigned integer that specifies the length of the first message /// available in the pipe if the pipe has been created as a message-type pipe. /// Otherwise, this field is 0 /// </summary> public uint MessageLength; /// <summary> /// A byte buffer of preview data from the pipe. /// The length of the buffer is indicated by the value of the ReadDataAvailable field /// </summary> public byte[] Data; } /// <summary> /// The FSCTL_FILE_LEVEL_TRIM operation informs the underlying storage medium that the contents /// of the given range of the file no longer needs to be maintained. This message allows the storage /// medium to manage its space more efficiently. /// </summary> public struct FSCTL_FILE_LEVEL_TRIM_INPUT { /// <summary> /// This field is used for byte range locks to uniquely identify different consumers of byte range /// locks on the same thread. Typically, this field is used only by remote protocols such as SMB or SMB2 /// </summary> public uint Key; /// <summary> /// A count of how many Offset, Length pairs follow in the data item /// </summary> public uint NumRanges; /// <summary> /// An array of zero or more FILE_LEVEL_TRIM_RANGE (section 2.3.69.1) data elements. /// The NumRanges field contains the number of FILE_LEVEL_TRIM_RANGE data elements in the array /// </summary> [Size("NumRanges")] public FSCTL_FILE_LEVEL_TRIM_RANGE[] Ranges; } /// <summary> /// /// </summary> public struct FSCTL_FILE_LEVEL_TRIM_RANGE { /// <summary> /// A 64-bit unsigned integer that contains a byte offset /// into the given file at which to start the trim request /// </summary> public ulong Offset; /// <summary> /// A 64-bit unsigned integer that contains the length, /// in bytes, of how much of the file to trim, starting at Offset /// </summary> public ulong Length; } public struct FSCTL_FILE_LEVEL_TRIM_OUTPUT { /// <summary> /// A 32-bit unsigned integer identifying the number of input ranges that were processed /// </summary> public uint NumRangesProcessed; } public struct FSCTL_GET_INTEGRITY_INFO_OUTPUT { public FSCTL_GET_INTEGRITY_INFO_OUTPUT_CHECKSUMALGORITHM ChecksumAlgorithm; public FSCTL_GET_INTEGRITY_INFO_OUTPUT_RESERVED Reserved; public FSCTL_GET_INTEGRITY_INFO_OUTPUT_FLAGS Flags; public uint ChecksumChunkSizeInBytes; public uint ClusterSizeInBytes; } public enum FSCTL_GET_INTEGRITY_INFO_OUTPUT_CHECKSUMALGORITHM : ushort { /// <summary> /// The file or directory is not configured to use integrity. /// </summary> CHECKSUM_TYPE_NONE = 0, /// <summary> /// The file or directory is configured to use a CRC64 checksum to provide integrity. /// </summary> CHECKSUM_TYPE_CRC64 = 0x0002, } public enum FSCTL_GET_INTEGRITY_INFO_OUTPUT_RESERVED : ushort { V1 = 0 } [Flags] public enum FSCTL_GET_INTEGRITY_INFO_OUTPUT_FLAGS : uint { /// <summary> /// Indicates that checksum enforcement is not currently enabled on the target file /// </summary> FSCTL_INTEGRITY_FLAG_CHECKSUM_ENFORCEMENT_OFF = 0x00000001 } /// <summary> /// The FSCTL_SET_INTEGRITY_INFORMATION Request message requests that the server /// set the integrity state of the file or directory associated with the handle on which this FSCTL was invoked /// </summary> public struct FSCTL_SET_INTEGRIY_INFO_INPUT { public FSCTL_SET_INTEGRITY_INFO_INPUT_CHECKSUMALGORITHM ChecksumAlgorithm; public FSCTL_SET_INTEGRITY_INFO_INPUT_RESERVED Reserved; public FSCTL_SET_INTEGRITY_INFO_INPUT_FLAGS Flags; } public enum FSCTL_SET_INTEGRITY_INFO_INPUT_CHECKSUMALGORITHM : ushort { /// <summary> /// The file or directory should be set to not use integrity /// </summary> CHECKSUM_TYPE_NONE = 0, /// <summary> /// The file or directory should be set to provide integrity using a CRC64 checksum. /// </summary> CHECKSUM_TYPE_CRC64 = 0x0002, /// <summary> /// The integrity status of the file or directory should be unchanged. /// </summary> CHECKSUM_TYPE_UNCHANGED = 0xFFFF, } public enum FSCTL_SET_INTEGRITY_INFO_INPUT_RESERVED : ushort { V1 = 0 } [Flags] public enum FSCTL_SET_INTEGRITY_INFO_INPUT_FLAGS : uint { /// <summary> /// When set, if a checksum does not match, the associated I/O operation will not be failed. /// </summary> FSCTL_INTEGRITY_FLAG_CHECKSUM_ENFORCEMENT_OFF = 0x00000001 } public struct FSCTL_OFFLOAD_READ_INPUT { public uint Size; public FSCTL_OFFLOAD_READ_INPUT_FLAGS Flags; public uint TokenTimeToLive; public uint Reserved; public ulong FileOffset; public ulong CopyLength; } [Flags] public enum FSCTL_OFFLOAD_READ_INPUT_FLAGS : uint { NONE = 0, } public struct FSCTL_OFFLOAD_READ_OUTPUT { public uint Size; public FSCTL_OFFLOAD_READ_INPUT_FLAGS Flag; public ulong TransferLength; public STORAGE_OFFLOAD_TOKEN Token; } [Flags] public enum FSCTL_OFFLOAD_READ_OUTPUT_FLAGS : uint { NONE = 0, OFFLOAD_READ_FLAG_ALL_ZERO_BEYOND_CURRENT_RANGE = 0x00000001, } public struct STORAGE_OFFLOAD_TOKEN { [ByteOrder(EndianType.BigEndian)] public FSCTL_OFFLOAD_WRITE_INPUT_TOKEN_TYPE TokenType; [ByteOrder(EndianType.BigEndian)] public ushort Reserved; [ByteOrder(EndianType.BigEndian)] public ushort TokenIdLength; [StaticSize(504)] public byte[] TokenId; } public enum FSCTL_OFFLOAD_WRITE_INPUT_TOKEN_TYPE : uint { STORAGE_OFFLOAD_TOKEN_TYPE_ZERO_DATA = 0xFFFF0001, } public struct FSCTL_OFFLOAD_WRITE_INPUT { public uint Size; public FSCTL_OFFLOAD_WRITE_INPUT_FLAGS Flags; public ulong FileOffset; public ulong CopyLength; public ulong TransferOffset; public STORAGE_OFFLOAD_TOKEN Token; } [Flags] public enum FSCTL_OFFLOAD_WRITE_INPUT_FLAGS : uint { NONE = 0, } public struct FSCTL_OFFLOAD_WRITE_OUTPUT { public uint Size; public FSCTL_OFFLOAD_WRITE_OUTPUT_FLAGS Flags; public ulong LengthWritten; } [Flags] public enum FSCTL_OFFLOAD_WRITE_OUTPUT_FLAGS : uint { NONE = 0, } public struct FSCTL_DUPLICATE_EXTENTS_TO_FILE_Request { public FILEID SourceFileId; public long SourceFileOffset; public long TargetFileOffset; public long ByteCount; } public struct FSCTL_DUPLICATE_EXTENTS_TO_FILE_Response { } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond { using System; using System.Linq; using System.Threading; using Bond.Expressions; using Bond.IO; using Bond.Protocols; using Bond.Internal.Reflection; /// <summary> /// Transcode payload from one protocol into another /// </summary> public static class Transcode { static class Cache<R, W> { public static readonly Transcoder<R, W> Instance = new Transcoder<R, W>(); } /// <summary> /// Transcode data from protocol reader <typeparamref name="R"/> to protocol writer <typeparamref name="W"/> /// </summary> /// <typeparam name="R">Protocol reader</typeparam> /// <typeparam name="W">Protocol writer</typeparam> /// <param name="reader">Reader instance representing source payload</param> /// <param name="writer">Writer instance</param> public static void FromTo<R, W>(R reader, W writer) { Cache<R, W>.Instance.Transcode(reader, writer); } } /// <summary> /// Transcode payload from one protocol into another using compile-time schema <typeparamref name="T"/> /// </summary> /// <typeparam name="T">Type representing a Bond schema</typeparam> public static class Transcode<T> { static class Cache<R, W> { public static readonly Transcoder<R, W> Instance = new Transcoder<R, W>(typeof(T)); } /// <summary> /// Transcode data from protocol reader <typeparamref name="R"/> to protocol writer <typeparamref name="W"/> /// </summary> /// <typeparam name="R">Protocol reader</typeparam> /// <typeparam name="W">Protocol writer</typeparam> /// <param name="reader">Reader instance representing source payload</param> /// <param name="writer">Writer instance</param> public static void FromTo<R, W>(R reader, W writer) { Cache<R, W>.Instance.Transcode(reader, writer); } } /// <summary> /// Transcoder from protocol reader <typeparamref name="R"/> to protocol writer <typeparamref name="W"/> /// </summary> /// <typeparam name="R">Protocol reader</typeparam> /// <typeparam name="W">Protocol writer</typeparam> public class Transcoder<R, W> { static readonly Type helperType; readonly TranscoderHelper helper; static Transcoder() { var firstPassAttribute = typeof(W).GetAttribute<FirstPassWriterAttribute>(); if (firstPassAttribute != null) { if (!typeof(ITwoPassProtocolWriter).IsAssignableFrom(typeof(W))) { throw new ArgumentException("Writers with FirstPassWriterAttribute must implement ITwoPassProtocolWriter"); } helperType = typeof(TwoPassTranscoderHelper<>).MakeGenericType(typeof(R), typeof(W), firstPassAttribute.Type); } else { helperType = typeof(TranscoderHelper); } } /// <summary> /// Create a transcoder for payloads with specified runtime schema /// </summary> /// <param name="schema">Payload schema, required for transcoding from untagged protocols</param> public Transcoder(RuntimeSchema schema) : this(schema, null) {} /// <summary> /// Create a transcoder for payloads with specified compile-time schema /// </summary> /// <param name="type">Type representing a Bond schema</param> public Transcoder(Type type) : this(type, null) {} /// <summary> /// Create a transcoder for payloads with specified runtime schema /// </summary> /// <param name="schema">Payload schema, required for transcoding from untagged protocols</param> /// <param name="parser">Custom <see cref="IParser"/> instance</param> public Transcoder(RuntimeSchema schema, IParser parser) { helper = (TranscoderHelper)Activator.CreateInstance(helperType, schema, parser); } /// <summary> /// Create a transcoder for payloads with specified compile-time schema /// </summary> /// <param name="type">Type representing a Bond schema</param> /// <param name="parser">Custom <see cref="IParser"/> instance</param> public Transcoder(Type type, IParser parser) { helper = (TranscoderHelper)Activator.CreateInstance(helperType, type, parser); } // Create a transcoder public Transcoder() : this(RuntimeSchema.Empty) {} /// <summary> /// Transcode payload /// </summary> /// <param name="reader">Reader instance representing source payload</param> /// <param name="writer">Writer instance</param> public void Transcode(R reader, W writer) { helper.Transcode(reader, writer); } class TranscoderHelper { readonly Action<R, W>[] transcode; public TranscoderHelper(RuntimeSchema schema, IParser parser) { transcode = Generate(schema, parser); } public TranscoderHelper(Type type, IParser parser) { transcode = Generate(type, parser); } public virtual void Transcode(R reader, W writer) { transcode[0](reader, writer); } Action<R, W>[] Generate<S>(S schema, IParser parser) { parser = parser ?? ParserFactory<R>.Create(schema); return SerializerGeneratorFactory<R, W>.Create( (r, w, i) => transcode[i](r, w), schema) .Generate(parser) .Select(lambda => lambda.Compile()).ToArray(); } } class TwoPassTranscoderHelper<FPW> : TranscoderHelper { readonly Lazy<Action<R, FPW>[]> firstPassTranscode; public TwoPassTranscoderHelper(RuntimeSchema schema, IParser parser): base(schema, parser) { firstPassTranscode = new Lazy<Action<R, FPW>[]>(() => GenerateFirstPass(schema, parser), LazyThreadSafetyMode.PublicationOnly); } public TwoPassTranscoderHelper(Type type, IParser parser): base(type, parser) { firstPassTranscode = new Lazy<Action<R, FPW>[]>(() => GenerateFirstPass(type, parser), LazyThreadSafetyMode.PublicationOnly); } public override void Transcode(R reader, W writer) { var firstPassWriter = ((ITwoPassProtocolWriter)writer).GetFirstPassWriter(); if (firstPassWriter != null) { if (!typeof(ICloneable<R>).IsAssignableFrom(typeof(R))) { throw new ArgumentException("Two-pass transcoding requires a reader that implements ICloneable"); } R clonedReader = ((ICloneable<R>)reader).Clone(); firstPassTranscode.Value[0](clonedReader, (FPW)firstPassWriter); } base.Transcode(reader, writer); } Action<R, FPW>[] GenerateFirstPass<S>(S schema, IParser parser) { parser = parser ?? ParserFactory<R>.Create(schema); return SerializerGeneratorFactory<R, FPW>.Create( (r, w, i) => firstPassTranscode.Value[i](r, w), schema) .Generate(parser) .Select(lambda => lambda.Compile()).ToArray(); } } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using SharpGen.Config; using SharpGen.CppModel; namespace SharpGen.Generator { /// <summary> /// This class handles renaming according to conventions. Pascal case (NamingRulesManager) for global types, /// Camel case (namingRulesManager) for parameters. /// </summary> public class NamingRulesManager { private readonly List<ShortNameMapper> _expandShortName = new List<ShortNameMapper>(); /// <summary> /// The recorded names, a list of previous name and new name. /// </summary> public readonly List<Tuple<CppElement, string>> RecordNames = new List<Tuple<CppElement, string>>(); /// <summary> /// Adds the short name rule. /// </summary> /// <param name="regexShortName">Short name of the regex.</param> /// <param name="expandedName">Name of the expanded.</param> public void AddShortNameRule(string regexShortName, string expandedName) { _expandShortName.Add(new ShortNameMapper(regexShortName, expandedName)); // Not efficient, but we order from longest to shortest regex _expandShortName.Sort((left, right) => -left.Regex.ToString().Length.CompareTo(right.Regex.ToString().Length)); } /// <summary> /// Renames a C++++ element /// </summary> /// <param name="cppElement">The C++ element.</param> /// <param name="rootName">Name of the root.</param> /// <returns>The new name</returns> private string RenameCore(CppElement cppElement, string rootName = null) { string originalName = cppElement.Name; string name = cppElement.Name; var namingFlags = NamingFlags.Default; bool nameModifiedByTag = false; // Handle Tag var tag = cppElement.GetTagOrDefault<MappingRule>(); if (tag != null) { if (!string.IsNullOrEmpty(tag.MappingName)) { nameModifiedByTag = true; name = tag.MappingName; // If Final Mapping name then don't proceed further if (tag.IsFinalMappingName.HasValue && tag.IsFinalMappingName.Value) return name; } if (tag.NamingFlags.HasValue) namingFlags = tag.NamingFlags.Value; } // Rename is tagged as final, then return the string // If the string still contains some "_" then continue while processing if (!name.Contains("_") && name.ToUpper() != name && char.IsUpper(name[0])) return name; // Remove Prefix (for enums). Don't modify names that are modified by tag if (!nameModifiedByTag && rootName != null && originalName.StartsWith(rootName)) name = originalName.Substring(rootName.Length, originalName.Length - rootName.Length); // Remove leading '_' name = name.TrimStart('_'); // Convert rest of the string in CamelCase name = ConvertToPascalCase(name, namingFlags); return name; } /// <summary> /// Renames the specified C++ element. /// </summary> /// <param name="cppElement">The C++ element.</param> /// <returns>The C# name</returns> public string Rename(CppElement cppElement) { return RecordRename(cppElement, UnKeyword(RenameCore(cppElement))); } /// <summary> /// Renames the specified C++ enum item. /// </summary> /// <param name="cppEnumItem">The C++ enum item.</param> /// <param name="rootEnumName">Name of the root C++ enum.</param> /// <returns>The C# name of this enum item</returns> public string Rename(CppEnumItem cppEnumItem, string rootEnumName) { return RecordRename(cppEnumItem, UnKeyword(RenameCore(cppEnumItem, rootEnumName))); } /// <summary> /// Renames the specified C++ parameter. /// </summary> /// <param name="cppParameter">The C++ parameter.</param> /// <returns>The C# name of this parameter.</returns> public string Rename(CppParameter cppParameter) { string oldName = cppParameter.Name; string name = RenameCore(cppParameter, null); bool hasPointer = !string.IsNullOrEmpty(cppParameter.Pointer) && (cppParameter.Pointer.Contains("*") || cppParameter.Pointer.Contains("&")); if (hasPointer) { if (oldName.StartsWith("pp")) name = name.Substring(2) + "Out"; else if (oldName.StartsWith("p")) name = name.Substring(1) + "Ref"; } if (char.IsDigit(name[0])) name = "arg" + name; name = new string(name[0], 1).ToLower() + name.Substring(1); return RecordRename(cppParameter, UnKeyword(name)); } /// <summary> /// Dump the names changes as a comma separated list of [FromName,ToName] /// </summary> /// <param name="writer">Text output of the dump</param> public void DumpRenames(TextWriter writer) { foreach (var recordName in RecordNames) { writer.WriteLine("{0},{1}", recordName.Item1.FullName, recordName.Item2); } } /// <summary> /// Record the name source and the modified name. /// </summary> /// <param name="fromElement">The element to rename</param> /// <param name="toName">The new name</param> /// <returns>The new name</returns> private string RecordRename(CppElement fromElement, string toName) { RecordNames.Add(new Tuple<CppElement, string>(fromElement, toName)); return toName; } /// <summary> /// Protect the name from all C# reserved words. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> private static string UnKeyword(string name) { if (IsKeyword(name)) { if (name == "string") return "text"; name = "@" + name; } return name; } /// <summary> /// Determines whether the specified string is a valid Pascal case. /// </summary> /// <param name="str">The string to validate.</param> /// <param name="lowerCount">The lower count.</param> /// <returns> /// <c>true</c> if the specified string is a valid Pascal case; otherwise, <c>false</c>. /// </returns> private static bool IsPascalCase(string str, out int lowerCount) { // Count the number of char in lower case lowerCount = str.Count(charInStr => char.IsLower(charInStr)); if (str.Length == 0) return false; // First char must be a letter if (!char.IsLetter(str[0])) return false; // First letter must be upper if (!char.IsUpper(str[0])) return false; // Second letter must be lower if (str.Length > 1 && char.IsUpper(str[1])) return false; // other chars must be letter or numbers //foreach (char charInStr in str) //{ // if (!char.IsLetterOrDigit(charInStr)) // return false; //} return str.All(charInStr => char.IsLetterOrDigit(charInStr)); } /// <summary> /// Converts a string to PascalCase.. /// </summary> /// <param name="text">The text to convert.</param> /// <param name="namingFlags">The naming options to apply to the given string to convert.</param> /// <returns>The given string in PascalCase.</returns> public string ConvertToPascalCase(string text, NamingFlags namingFlags) { string[] splittedPhrase = text.Split('_'); var sb = new StringBuilder(); for (int i = 0; i < splittedPhrase.Length; i++) { string subPart = splittedPhrase[i]; // Don't perform expansion when asked if ((namingFlags & NamingFlags.NoShortNameExpand) == 0) { while (subPart.Length > 0) { bool continueReplace = false; foreach (var regExp in _expandShortName) { var regex = regExp.Regex; var newText = regExp.Replace; if (regex.Match(subPart).Success) { if (regExp.HasRegexReplace) { subPart = regex.Replace(subPart, regExp.Replace); sb.Append(subPart); subPart = string.Empty; } else { subPart = regex.Replace(subPart, string.Empty); sb.Append(newText); continueReplace = true; } break; } } if (!continueReplace) { break; } } } // Else, perform a standard conversion if (subPart.Length > 0) { int numberOfCharLowercase; // If string is not Pascal Case, then Pascal Case it if (IsPascalCase(subPart, out numberOfCharLowercase)) { sb.Append(subPart); } else { char[] splittedPhraseChars = (numberOfCharLowercase > 0) ? subPart.ToCharArray() : subPart.ToLower().ToCharArray(); if (splittedPhraseChars.Length > 0) splittedPhraseChars[0] = char.ToUpper(splittedPhraseChars[0]); sb.Append(new String(splittedPhraseChars)); } } if ( (namingFlags & NamingFlags.KeepUnderscore) != 0 && (i + 1) < splittedPhrase.Length) sb.Append("_"); } return sb.ToString(); } /// <summary> /// Checks if a given string is a C# keyword. /// </summary> /// <param name="name">The name to check.</param> /// <returns>true if the name is a C# keyword; false otherwise.</returns> private static bool IsKeyword(string name) { return CSharpKeywords.Contains(name); } private class ShortNameMapper { public ShortNameMapper(string regex, string replace) { Regex = new Regex("^" + regex); Replace = replace; HasRegexReplace = replace.Contains("$"); } public Regex Regex; public string Replace; public bool HasRegexReplace; } /// <summary> /// Reserved C# keywords. /// </summary> private static readonly string[] CSharpKeywords = new[] { "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "volatile", "void", "while", }; } }
#region Namespace Declarations using Axiom.Graphics; using Axiom.Scripting.Compiler.AST; #endregion Namespace Declarations namespace Axiom.Scripting.Compiler { public partial class ScriptCompiler { #region HELPER class PragmaTokenizer { string[] pragmaList; int idx = -1; public PragmaTokenizer(string pragma) { pragmaList = pragma.Split(' '); } public string Next() { idx++; while (pragmaList[idx].Trim() == "" && idx < pragmaList.Length-1) idx++; if (idx < pragmaList.Length-1) { return pragmaList[idx]; } else return null; } } protected static bool _getReal(string value, out UnityEngine.Real result) { result = 0.0f; if (value == null) { return false; } double num = 0; if (double.TryParse(value,out num)) { result = num; return true; } else return false; } protected static bool _getFloat(string value, out float result) { result = 0f; UnityEngine.Real rResult; if (value == null) { return false; } if (_getReal(value, out rResult)) { result = rResult; return true; } return false; } protected static bool _getInt(string value, out int result) { result = 0; UnityEngine.Real rResult; if (value == null) { return false; } if (_getReal(value, out rResult)) { result = (int)rResult; return true; } return false; } #endregion public class UnityCGPROGRAMTranslator : Translator { static GpuProgramParameters unityAutoParams = null; protected Technique technique; protected Pass pass; //TODO // static string includeRelativePath = "./media/Shaders/CGIncludes/"; // general params; string fragEntryPoint = "frag"; string vertexEntryPoint = "vert"; string file = ""; uint line = 0; public UnityCGPROGRAMTranslator() : base() { technique = null; pass = null; } #region Translator Implementation /// <see cref="Translator.CheckFor"/> internal override bool CheckFor( Keywords nodeId, Keywords parentId ) { return ((nodeId == Keywords.ID_CGPROGRAM && parentId == Keywords.ID_SUBSHADER) || nodeId == Keywords.ID_CGPROGRAM && parentId == Keywords.ID_UPASS); } private void ProcessPragma(string pragma) { PragmaTokenizer tokenizer = new PragmaTokenizer(pragma); string token=null; do { token = tokenizer.Next(); if (token != null) { switch (token) { case "vertex": vertexEntryPoint = tokenizer.Next(); break; case "fragment": fragEntryPoint = tokenizer.Next(); break; } } } while (token != null); } private void ProcessAutoParam(ScriptCompiler compiler, GpuProgramParameters parameters, string paramID, bool paramNamed, string autoParamTarget, string value2, string value3) { #region PROCESS_PARAM int animParametricsCount = 0; string name = ""; int index = 0; if (paramNamed) { name = paramID; } else { index = int.Parse(paramID); } // Look up the auto constant autoParamTarget = autoParamTarget.ToLower(); GpuProgramParameters.AutoConstantDefinition def; bool defFound = GpuProgramParameters.GetAutoConstantDefinition(autoParamTarget, out def); if( defFound ) { switch( def.DataType ) { #region None case GpuProgramParameters.AutoConstantDataType.None: // Set the auto constant try { if (paramNamed) { parameters.SetNamedAutoConstant( name, def.AutoConstantType ); } else { parameters.SetAutoConstant( index, def.AutoConstantType ); } } catch { compiler.AddError( CompileErrorCode.InvalidParameters, file, line, "setting of constant failed" ); } break; #endregion None #region Int case GpuProgramParameters.AutoConstantDataType.Int: if( def.AutoConstantType == GpuProgramParameters.AutoConstantType.AnimationParametric ) { try { if (paramNamed) { parameters.SetNamedAutoConstant( name, def.AutoConstantType, animParametricsCount++ ); } else { parameters.SetAutoConstant( index, def.AutoConstantType, animParametricsCount++ ); } } catch { compiler.AddError( CompileErrorCode.InvalidParameters, file, line, "setting of constant failed" ); } } else { // Only certain texture projection auto params will assume 0 // Otherwise we will expect that 3rd parameter if( value2 == null ) { if( def.AutoConstantType == GpuProgramParameters.AutoConstantType.TextureViewProjMatrix || def.AutoConstantType == GpuProgramParameters.AutoConstantType.TextureWorldViewProjMatrix || def.AutoConstantType == GpuProgramParameters.AutoConstantType.SpotLightViewProjMatrix || def.AutoConstantType == GpuProgramParameters.AutoConstantType.SpotLightWorldViewProjMatrix ) { try { if (paramNamed) { parameters.SetNamedAutoConstant( name, def.AutoConstantType, 0 ); } else { parameters.SetAutoConstant( index, def.AutoConstantType, 0 ); } } catch { compiler.AddError( CompileErrorCode.InvalidParameters,file,line, "setting of constant failed" ); } } else { compiler.AddError( CompileErrorCode.NumberExpected,file,line, "extra parameters required by constant definition " + autoParamTarget); } } else { bool success = false; int extraInfo = 0; if( value3 == null ) { // Handle only one extra value if (_getInt(value2, out extraInfo)) { success = true; } } else { // Handle two extra values int extraInfo1 = 0, extraInfo2 = 0; if (_getInt(value2, out extraInfo1) && _getInt(value3, out extraInfo2)) { extraInfo = extraInfo1 | ( extraInfo2 << 16 ); success = true; } } if( success ) { try { if (paramNamed) { parameters.SetNamedAutoConstant( name, def.AutoConstantType, extraInfo ); } else { parameters.SetAutoConstant( index, def.AutoConstantType, extraInfo ); } } catch { compiler.AddError( CompileErrorCode.InvalidParameters, file,line, "setting of constant failed" ); } } else { compiler.AddError( CompileErrorCode.InvalidParameters, file,line, "invalid auto constant extra info parameter" ); } } } break; #endregion Int #region Real case GpuProgramParameters.AutoConstantDataType.Real: if( def.AutoConstantType == GpuProgramParameters.AutoConstantType.Time || def.AutoConstantType == GpuProgramParameters.AutoConstantType.FrameTime ) { UnityEngine.Real f = 1.0f; if( value2 != null ) { _getReal( value2, out f ); } try { //TODO if (paramNamed) { /*parameters->setNamedAutoConstantReal(name, def->acType, f);*/ } else { parameters.SetAutoConstant( index, def.AutoConstantType, f ); } } catch { compiler.AddError( CompileErrorCode.InvalidParameters,file,line, "setting of constant failed" ); } } else { if( value2 != null ) { UnityEngine.Real extraInfo = 0.0f; if( _getReal( value2, out extraInfo ) ) { try { //TODO if (paramNamed) { /*parameters->setNamedAutoConstantReal(name, def->acType, extraInfo);*/ } else { parameters.SetAutoConstant( index, def.AutoConstantType, extraInfo ); } } catch { compiler.AddError( CompileErrorCode.InvalidParameters,file,line, "setting of constant failed" ); } } else { compiler.AddError( CompileErrorCode.InvalidParameters,file,line, "incorrect float argument definition in extra parameters" ); } } else { compiler.AddError( CompileErrorCode.NumberExpected,file,line, "extra parameters required by constant definition " + autoParamTarget); } } break; #endregion Real } } else { compiler.AddError( CompileErrorCode.InvalidParameters,file,line ); } #endregion } private void ProcessAutoParams(ScriptCompiler compiler,GpuProgramParameters parameters) { parameters.AutoAddParamName = false; // prevent bad params parameters.IgnoreMissingParameters = true; //if (unityAutoParams == null) //{ // unityAutoParams = GpuProgramManager.Instance.CreateParameters(); // ProcessAutoParam(compiler, parameters, "UNITY_MATRIX_MVP", true, "worldviewproj_matrix", null, null); //} // UNITY_MATRIX_MVP ProcessAutoParam(compiler, parameters, "glstate_matrix_mvp", true, "worldviewproj_matrix", null, null); // UNITY_MATRIX_MV ProcessAutoParam(compiler, parameters, "glstate_matrix_modelview0", true, "worldview_matrix", null, null); // UNITY_MATRIX_IT_MV ProcessAutoParam(compiler, parameters, "glstate_matrix_invtrans_modelview0", true, "inverse_transpose_worldview_matrix", null, null); ProcessAutoParam(compiler, parameters, "_Object2World", true, "world_matrix", null, null); ProcessAutoParam(compiler, parameters, "_World2Object", true, "inverse_world_matrix", null, null); //// // x is the fade value ranging within [0,1]. y is x quantized into 16 levels //ProcessAutoParam(compiler, parameters, "unity_LODFade", true, "worldviewproj_matrix", null, null); //// // w is usually 1.0, or -1.0 for odd-negative scale transforms //ProcessAutoParam(compiler, parameters, "unity_WorldTransformParams", true, "worldviewproj_matrix", null, null); // parameters.CopyConstantsFrom(unityAutoParams); } /// <see cref="Translator.Translate"/> public override void Translate(ScriptCompiler compiler, AbstractNode node) { ObjectAbstractNode obj = (ObjectAbstractNode)node; // Create the technique from the materia Pass pass = null; if (obj.Parent.Context is Technique) { technique = (Technique)obj.Parent.Context; if (technique.PassCount == 0) { pass = technique.CreatePass(); } } else { //TODO pass pass = (Pass)obj.Parent.Context; } // Allocate the program object progObj; Axiom.CgPrograms.CgProgram prog = null; // ------------------------------------------- // GEST DATAS Axiom.Collections.NameValuePairList customParameters = new Axiom.Collections.NameValuePairList(); string syntax = string.Empty, source = string.Empty; source = ((ObjectAbstractNode)node).Children[0].Value; string language = "cg"; string passName = System.IO.Path.GetFileNameWithoutExtension(node.File); //syntax ="ps_2_0"; syntax = "arbvp1"; System.Text.StringBuilder builder = new System.Text.StringBuilder(); // EXTRACT PROGRAM pragmas, resolve includes using (System.IO.StringReader reader = new System.IO.StringReader(source)) { string lineTrimmed; string line = null; do{ line = reader.ReadLine(); if (line != null) { lineTrimmed = line.TrimStart(); if (lineTrimmed.StartsWith("#pragma")) { ScriptCompilerEvent evnt = new CreateHighLevelGpuProgramScriptCompilerEvent(obj.File, passName, compiler.ResourceGroup, source, language, GpuProgramType.Vertex); bool processed = compiler._fireEvent(ref evnt, out progObj); ProcessPragma(lineTrimmed.Substring(7)); } //else if (lineTrimmed.StartsWith("#include")) //{ // int ii = line.IndexOf("\""); // if (ii != -1) // { // line = line.Substring(0, ii+1) + includeRelativePath + line.Substring(ii+1); // } // builder.Append(line); // builder.Append("\n"); //} else { builder.Append(line); builder.Append("\n"); } } } while(line != null); } source = builder.ToString(); // ALLOCATE THE PROGRAM // VERTEX E FRAGMENT string name; GpuProgramType type; for (int i = 0; i < 2; i++) { if (i == 0) { name = passName + "_vs"; type = GpuProgramType.Vertex; syntax = "arbvp1"; } else { name = passName + "_fs"; type = GpuProgramType.Fragment; syntax = "arbfp1"; } ScriptCompilerEvent evnt = new CreateHighLevelGpuProgramScriptCompilerEvent(obj.File, name, compiler.ResourceGroup, source, language, type); bool processed = compiler._fireEvent(ref evnt, out progObj); // CHECK VERSION if (!GpuProgramManager.Instance.IsSyntaxSupported(syntax)) { compiler.AddError(CompileErrorCode.UnsupportedByRenderSystem, obj.File, obj.Line); //Register the unsupported program so that materials that use it know that //it exists but is unsupported GpuProgram unsupportedProg = GpuProgramManager.Instance.Create(obj.Name, compiler.ResourceGroup, type, syntax); return; } if (!processed) { prog = (Axiom.CgPrograms.CgProgram)(HighLevelGpuProgramManager.Instance.CreateProgram(name, compiler.ResourceGroup, language, type)); prog.SourceFile = source; } else { prog = (Axiom.CgPrograms.CgProgram)progObj; } // Check that allocation worked if (prog == null) { compiler.AddError(CompileErrorCode.ObjectAllocationError, obj.File, obj.Line, "gpu program \"" + name + "\" could not be created"); return; } obj.Context = prog; prog.IsMorphAnimationIncluded = false; prog.PoseAnimationCount = 0; prog.IsSkeletalAnimationIncluded = false; prog.IsVertexTextureFetchRequired = false; prog.Origin = obj.File; prog.Source = source; // PASS LINK if (i == 0) { prog.entry = vertexEntryPoint; prog.profiles = new string[] { syntax }; pass.SetVertexProgram(name); ProcessAutoParams(compiler,pass.VertexProgramParameters); } else { prog.entry = fragEntryPoint; prog.profiles = new string[] { syntax }; pass.SetFragmentProgram(name); ProcessAutoParams(compiler,pass.FragmentProgramParameters); } } // Set the custom parameters // prog.SetParameters(customParameters); // Set the custom parameters //foreach (KeyValuePair<string, string> currentParam in customParameters) //{ // string param = currentParam.Key; // string val = currentParam.Value; // if (!prog.SetParam(param, val)) // { // UnityEngine.Debug.LogError("Error in program {0} parameter {1} is not valid.", source, param); // } //} // Set up default parameters // if (prog.IsSupported && parameters != null) // { //#warning this need GpuProgramParametersShared implementation // //GpuProgramParametersSharedPtr ptr = prog->getDefaultParameters(); // //GpuProgramTranslator::translateProgramParameters(compiler, ptr, reinterpret_cast<ObjectAbstractNode*>(params.get())); // } } #endregion Translator Implementation } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace LCAToolAPI.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; /// <summary> /// Constructor to initialize self as an IModelDocumentationProvider. /// </summary> /// <param name="config">HttpConfiguration object (required)</param> public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// the models /// </summary> public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } /// <summary> /// if a type doesn't have doc already it can be created? /// </summary> /// <param name="modelType">a Type</param> /// <returns>ModelDescription</returns> public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// *********************************************************************** // Copyright (c) 2010 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using NUnit.Framework.Api; namespace NUnit.Framework.Internal { /// <summary> /// The TestResult class represents the result of a test. /// </summary> public abstract class TestResult : ITestResult { #region Fields /// <summary> /// Indicates the result of the test /// </summary> [CLSCompliant(false)] protected ResultState resultState; /// <summary> /// The elapsed time for executing this test /// </summary> private TimeSpan time = TimeSpan.Zero; /// <summary> /// The test that this result pertains to /// </summary> [CLSCompliant(false)] protected readonly ITest test; /// <summary> /// The stacktrace at the point of failure /// </summary> private string stackTrace; /// <summary> /// Message giving the reason for failure, error or skipping the test /// </summary> [CLSCompliant(false)] protected string message; /// <summary> /// Number of asserts executed by this test /// </summary> [CLSCompliant(false)] protected int assertCount = 0; /// <summary> /// List of child results /// </summary> #if CLR_2_0 || CLR_4_0 private System.Collections.Generic.List<ITestResult> children; #else private System.Collections.ArrayList children; #endif #endregion #region Constructor /// <summary> /// Construct a test result given a Test /// </summary> /// <param name="test">The test to be used</param> public TestResult(ITest test) { this.test = test; this.resultState = ResultState.Inconclusive; } #endregion #region ITestResult Members /// <summary> /// Gets the test with which this result is associated. /// </summary> public ITest Test { get { return test; } } /// <summary> /// Gets the ResultState of the test result, which /// indicates the success or failure of the test. /// </summary> public ResultState ResultState { get { return resultState; } } /// <summary> /// Gets the name of the test result /// </summary> public virtual string Name { get { return test.Name; } } /// <summary> /// Gets the full name of the test result /// </summary> public virtual string FullName { get { return test.FullName; } } /// <summary> /// Gets or sets the elapsed time for running the test /// </summary> public TimeSpan Duration { get { return time; } set { time = value; } } /// <summary> /// Gets the message associated with a test /// failure or with not running the test /// </summary> public string Message { get { return message; } } /// <summary> /// Gets any stacktrace associated with an /// error or failure. Not available in /// the Compact Framework 1.0. /// </summary> public virtual string StackTrace { get { return stackTrace; } } /// <summary> /// Gets or sets the count of asserts executed /// when running the test. /// </summary> public int AssertCount { get { return assertCount; } set { assertCount = value; } } /// <summary> /// Gets the number of test cases that failed /// when running the test and all its children. /// </summary> public abstract int FailCount { get; } /// <summary> /// Gets the number of test cases that passed /// when running the test and all its children. /// </summary> public abstract int PassCount { get; } /// <summary> /// Gets the number of test cases that were skipped /// when running the test and all its children. /// </summary> public abstract int SkipCount { get; } /// <summary> /// Gets the number of test cases that were inconclusive /// when running the test and all its children. /// </summary> public abstract int InconclusiveCount { get; } /// <summary> /// Indicates whether this result has any child results. /// Test HasChildren before accessing Children to avoid /// the creation of an empty collection. /// </summary> public bool HasChildren { get { return children != null && children.Count > 0; } } /// <summary> /// Gets the collection of child results. /// </summary> #if CLR_2_0 || CLR_4_0 public System.Collections.Generic.IList<ITestResult> Children { get { if (children == null) children = new System.Collections.Generic.List<ITestResult>(); return children; } } #else public System.Collections.IList Children { get { if (children == null) children = new System.Collections.ArrayList(); return children; } } #endif #endregion #region IXmlNodeBuilder Members /// <summary> /// Returns the Xml representation of the result. /// </summary> /// <param name="recursive">If true, descendant results are included</param> /// <returns>An XmlNode representing the result</returns> public XmlNode ToXml(bool recursive) { XmlNode topNode = XmlNode.CreateTopLevelElement("dummy"); AddToXml(topNode, recursive); return topNode.FirstChild; } /// <summary> /// Adds the XML representation of the result as a child of the /// supplied parent node.. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="recursive">If true, descendant results are included</param> /// <returns></returns> public virtual XmlNode AddToXml(XmlNode parentNode, bool recursive) { // A result node looks like a test node with extra info added XmlNode thisNode = this.test.AddToXml(parentNode, false); thisNode.AddAttribute("result", ResultState.Status.ToString()); if (ResultState.Label != string.Empty) // && ResultState.Label != ResultState.Status.ToString()) thisNode.AddAttribute("label", ResultState.Label); thisNode.AddAttribute("time", this.Duration.ToString()); if (this.test is TestSuite) { thisNode.AddAttribute("total", (PassCount + FailCount + SkipCount + InconclusiveCount).ToString()); thisNode.AddAttribute("passed", PassCount.ToString()); thisNode.AddAttribute("failed", FailCount.ToString()); thisNode.AddAttribute("inconclusive", InconclusiveCount.ToString()); thisNode.AddAttribute("skipped", SkipCount.ToString()); } thisNode.AddAttribute("asserts", this.AssertCount.ToString()); switch (ResultState.Status) { case TestStatus.Failed: AddFailureElement(thisNode); break; case TestStatus.Skipped: AddReasonElement(thisNode); break; case TestStatus.Passed: case TestStatus.Inconclusive: if (this.Message != null) AddReasonElement(thisNode); break; } if (recursive && HasChildren) foreach (TestResult child in Children) child.AddToXml(thisNode, recursive); return thisNode; } #endregion #region Other Public Methods /// <summary> /// Add a child result /// </summary> /// <param name="result">The child result to be added</param> public virtual void AddResult(TestResult result) { this.Children.Add(result); this.assertCount += result.AssertCount; switch (result.ResultState.Status) { case TestStatus.Passed: if (this.resultState.Status == TestStatus.Inconclusive) SetResult(ResultState.Success); break; case TestStatus.Failed: if (this.resultState.Status != TestStatus.Failed) SetResult(ResultState.Failure, "One or more child tests had errors"); break; case TestStatus.Skipped: switch (result.ResultState.Label) { case "Invalid": if (this.ResultState != ResultState.NotRunnable && this.ResultState.Status != TestStatus.Failed) SetResult(ResultState.Failure, "One or more child tests had errors"); break; case "Ignored": if (this.ResultState.Status == TestStatus.Inconclusive || this.ResultState.Status == TestStatus.Passed) SetResult(ResultState.Ignored, "One or more child tests were ignored"); break; default: // Tests skipped for other reasons do not change the outcome // of the containing suite when added. break; } break; case TestStatus.Inconclusive: // An inconclusive result does not change the outcome // of the containing suite when added. break; } } /// <summary> /// Set the result of the test /// </summary> /// <param name="resultState">The ResultState to use in the result</param> public void SetResult(ResultState resultState) { SetResult(resultState, null, null); } /// <summary> /// Set the result of the test /// </summary> /// <param name="resultState">The ResultState to use in the result</param> /// <param name="message">A message associated with the result state</param> public void SetResult(ResultState resultState, string message) { SetResult(resultState, message, null); } /// <summary> /// Set the result of the test /// </summary> /// <param name="resultState">The ResultState to use in the result</param> /// <param name="message">A message associated with the result state</param> /// <param name="stackTrace">Stack trace giving the location of the command</param> public void SetResult(ResultState resultState, string message, string stackTrace) { this.resultState = resultState; this.message = message; this.stackTrace = stackTrace; } /// <summary> /// Set the test result based on the type of exception thrown /// </summary> /// <param name="ex">The exception that was thrown</param> public void RecordException(Exception ex) { if (ex is NUnitException) ex = ex.InnerException; if (ex is System.Threading.ThreadAbortException) SetResult(ResultState.Cancelled, "Test cancelled by user", ex.StackTrace); else if (ex is AssertionException) SetResult(ResultState.Failure, ex.Message, StackFilter.Filter(ex.StackTrace)); else if (ex is IgnoreException) SetResult(ResultState.Ignored, ex.Message, StackFilter.Filter(ex.StackTrace)); else if (ex is InconclusiveException) SetResult(ResultState.Inconclusive, ex.Message, StackFilter.Filter(ex.StackTrace)); else if (ex is SuccessException) SetResult(ResultState.Success, ex.Message, StackFilter.Filter(ex.StackTrace)); else SetResult(ResultState.Error, ExceptionHelper.BuildMessage(ex), ExceptionHelper.BuildStackTrace(ex)); } #endregion #region Helper Methods /// <summary> /// Adds a reason element to a node and returns it. /// </summary> /// <param name="targetNode">The target node.</param> /// <returns>The new reason element.</returns> private XmlNode AddReasonElement(XmlNode targetNode) { XmlNode reasonNode = targetNode.AddElement("reason"); reasonNode.AddElement("message").TextContent = this.Message; return reasonNode; } /// <summary> /// Adds a failure element to a node and returns it. /// </summary> /// <param name="targetNode">The target node.</param> /// <returns>The new failure element.</returns> private XmlNode AddFailureElement(XmlNode targetNode) { XmlNode failureNode = targetNode.AddElement("failure"); if (this.Message != null) { failureNode.AddElement("message").TextContent = this.Message; } if (this.StackTrace != null) { failureNode.AddElement("stack-trace").TextContent = this.StackTrace; } return failureNode; } //private static bool IsTestCase(ITest test) //{ // return !(test is TestSuite); //} #endregion } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.IO; using System.Management.Automation; using System.Management.Automation.Provider; using System.Net; using System.Text; using DiscUtils.Complete; using DiscUtils.Ntfs; namespace DiscUtils.PowerShell.VirtualDiskProvider { [CmdletProvider("VirtualDisk", ProviderCapabilities.Credentials)] public sealed class Provider : NavigationCmdletProvider, IContentCmdletProvider { #region Drive manipulation protected override PSDriveInfo NewDrive(PSDriveInfo drive) { SetupHelper.SetupComplete(); NewDriveParameters dynParams = DynamicParameters as NewDriveParameters; if (drive == null) { WriteError(new ErrorRecord( new ArgumentNullException(nameof(drive)), "NullDrive", ErrorCategory.InvalidArgument, null)); return null; } if (string.IsNullOrEmpty(drive.Root)) { WriteError(new ErrorRecord( new ArgumentException("drive"), "NoRoot", ErrorCategory.InvalidArgument, drive)); return null; } string[] mountPaths = Utilities.NormalizePath(drive.Root).Split('!'); if (mountPaths.Length < 1 || mountPaths.Length > 2) { WriteError(new ErrorRecord( new ArgumentException("drive"), "InvalidRoot", ErrorCategory.InvalidArgument, drive)); //return null; } string diskPath = mountPaths[0]; string relPath = mountPaths.Length > 1 ? mountPaths[1] : ""; string user = null; string password = null; if (drive.Credential != null && drive.Credential.UserName != null) { NetworkCredential netCred = drive.Credential.GetNetworkCredential(); user = netCred.UserName; password = netCred.Password; } try { string fullPath = Utilities.DenormalizePath(diskPath); var resolvedPath = SessionState.Path.GetResolvedPSPathFromPSPath(fullPath)[0]; if (resolvedPath.Provider.Name == "FileSystem") { fullPath = resolvedPath.ProviderPath; } FileAccess access = dynParams.ReadWrite.IsPresent ? FileAccess.ReadWrite : FileAccess.Read; VirtualDisk disk = VirtualDisk.OpenDisk(fullPath, dynParams.DiskType, access, user, password); return new VirtualDiskPSDriveInfo(drive, MakePath(Utilities.NormalizePath(fullPath) + "!", relPath), disk); } catch (IOException ioe) { WriteError(new ErrorRecord( ioe, "DiskAccess", ErrorCategory.ResourceUnavailable, drive.Root)); return null; } } protected override object NewDriveDynamicParameters() { return new NewDriveParameters(); } protected override PSDriveInfo RemoveDrive(PSDriveInfo drive) { if (drive == null) { WriteError(new ErrorRecord( new ArgumentNullException(nameof(drive)), "NullDrive", ErrorCategory.InvalidArgument, null)); return null; } VirtualDiskPSDriveInfo vdDrive = drive as VirtualDiskPSDriveInfo; if (vdDrive == null) { WriteError(new ErrorRecord( new ArgumentException("invalid type of drive"), "BadDrive", ErrorCategory.InvalidArgument, null)); return null; } vdDrive.Disk.Dispose(); return vdDrive; } #endregion #region Item methods protected override void GetItem(string path) { GetItemParameters dynParams = DynamicParameters as GetItemParameters; bool readOnly = !(dynParams != null && dynParams.ReadWrite.IsPresent); Object obj = FindItemByPath(Utilities.NormalizePath(path), false, readOnly); if (obj != null) { WriteItemObject(obj, path.Trim('\\'), true); } } protected override object GetItemDynamicParameters(string path) { return new GetItemParameters(); } protected override void SetItem(string path, object value) { throw new NotImplementedException(); } protected override bool ItemExists(string path) { bool result = FindItemByPath(Utilities.NormalizePath(path), false, true) != null; return result; } protected override bool IsValidPath(string path) { return !string.IsNullOrEmpty(path); } #endregion #region Container methods protected override void GetChildItems(string path, bool recurse) { GetChildren(Utilities.NormalizePath(path), recurse, false); } protected override void GetChildNames(string path, ReturnContainers returnContainers) { // TODO: returnContainers GetChildren(Utilities.NormalizePath(path), false, true); } protected override bool HasChildItems(string path) { object obj = FindItemByPath(Utilities.NormalizePath(path), true, true); if (obj is DiscFileInfo) { return false; } else if (obj is DiscDirectoryInfo) { return ((DiscDirectoryInfo)obj).GetFileSystemInfos().Length > 0; } else { return true; } } protected override void RemoveItem(string path, bool recurse) { object obj = FindItemByPath(Utilities.NormalizePath(path), false, false); if (obj is DiscDirectoryInfo) { ((DiscDirectoryInfo)obj).Delete(true); } else if (obj is DiscFileInfo) { ((DiscFileInfo)obj).Delete(); } else { WriteError(new ErrorRecord( new InvalidOperationException("Cannot delete items of this type: " + (obj != null ? obj.GetType() : null)), "UnknownObjectTypeToRemove", ErrorCategory.InvalidOperation, obj)); } } protected override void NewItem(string path, string itemTypeName, object newItemValue) { string parentPath = GetParentPath(path, null); if (string.IsNullOrEmpty(itemTypeName)) { WriteError(new ErrorRecord( new InvalidOperationException("No type specified. Specify \"file\" or \"directory\" as the type."), "NoTypeForNewItem", ErrorCategory.InvalidArgument, itemTypeName)); return; } string itemTypeUpper = itemTypeName.ToUpperInvariant(); object obj = FindItemByPath(Utilities.NormalizePath(parentPath), true, false); if (obj is DiscDirectoryInfo) { DiscDirectoryInfo dirInfo = (DiscDirectoryInfo)obj; if (itemTypeUpper == "FILE") { using (dirInfo.FileSystem.OpenFile(Path.Combine(dirInfo.FullName, GetChildName(path)), FileMode.Create)) { } } else if (itemTypeUpper == "DIRECTORY") { dirInfo.FileSystem.CreateDirectory(Path.Combine(dirInfo.FullName, GetChildName(path))); } else if (itemTypeUpper == "HARDLINK") { NtfsFileSystem ntfs = dirInfo.FileSystem as NtfsFileSystem; if(ntfs != null) { NewHardLinkDynamicParameters hlParams = (NewHardLinkDynamicParameters)DynamicParameters; var srcItems = SessionState.InvokeProvider.Item.Get(hlParams.SourcePath); if (srcItems.Count != 1) { WriteError(new ErrorRecord( new InvalidOperationException("The type is unknown for this provider. Only \"file\" and \"directory\" can be specified."), "UnknownTypeForNewItem", ErrorCategory.InvalidArgument, itemTypeName)); return; } DiscFileSystemInfo srcFsi = srcItems[0].BaseObject as DiscFileSystemInfo; ntfs.CreateHardLink(srcFsi.FullName, Path.Combine(dirInfo.FullName, GetChildName(path))); } } else { WriteError(new ErrorRecord( new InvalidOperationException("The type is unknown for this provider. Only \"file\" and \"directory\" can be specified."), "UnknownTypeForNewItem", ErrorCategory.InvalidArgument, itemTypeName)); return; } } else { WriteError(new ErrorRecord( new InvalidOperationException("Cannot create items in an object of this type: " + (obj != null ? obj.GetType() : null)), "UnknownObjectTypeForNewItemParent", ErrorCategory.InvalidOperation, obj)); return; } } protected override object NewItemDynamicParameters(string path, string itemTypeName, object newItemValue) { if (string.IsNullOrEmpty(itemTypeName)) { return null; } string itemTypeUpper = itemTypeName.ToUpperInvariant(); if (itemTypeUpper == "HARDLINK") { return new NewHardLinkDynamicParameters(); } return null; } protected override void RenameItem(string path, string newName) { object obj = FindItemByPath(Utilities.NormalizePath(path), true, false); DiscFileSystemInfo fsiObj = obj as DiscFileSystemInfo; if (fsiObj == null) { WriteError(new ErrorRecord( new InvalidOperationException("Cannot move items to this location"), "BadParentForNewItem", ErrorCategory.InvalidArgument, newName)); return; } string newFullName = Path.Combine(Path.GetDirectoryName(fsiObj.FullName.TrimEnd('\\')), newName); if (obj is DiscDirectoryInfo) { DiscDirectoryInfo dirObj = (DiscDirectoryInfo)obj; dirObj.MoveTo(newFullName); } else { DiscFileInfo fileObj = (DiscFileInfo)obj; fileObj.MoveTo(newFullName); } } protected override void CopyItem(string path, string copyPath, bool recurse) { DiscDirectoryInfo destDir; string destFileName = null; object destObj = FindItemByPath(Utilities.NormalizePath(copyPath), true, false); destDir = destObj as DiscDirectoryInfo; if (destDir != null) { destFileName = GetChildName(path); } else if (destObj == null || destObj is DiscFileInfo) { destObj = FindItemByPath(Utilities.NormalizePath(GetParentPath(copyPath, null)), true, false); destDir = destObj as DiscDirectoryInfo; destFileName = GetChildName(copyPath); } if (destDir == null) { WriteError(new ErrorRecord( new InvalidOperationException("Cannot copy items to this location"), "BadParentForNewItem", ErrorCategory.InvalidArgument, copyPath)); return; } object srcDirObj = FindItemByPath(Utilities.NormalizePath(GetParentPath(path, null)), true, true); DiscDirectoryInfo srcDir = srcDirObj as DiscDirectoryInfo; string srcFileName = GetChildName(path); if (srcDir == null) { WriteError(new ErrorRecord( new InvalidOperationException("Cannot copy items from this location"), "BadParentForNewItem", ErrorCategory.InvalidArgument, copyPath)); return; } DoCopy(srcDir, srcFileName, destDir, destFileName, recurse); } #endregion #region Navigation methods protected override bool IsItemContainer(string path) { object obj = FindItemByPath(Utilities.NormalizePath(path), false, true); bool result = false; if (obj is VirtualDisk) { result = true; } else if (obj is LogicalVolumeInfo) { result = true; } else if (obj is DiscDirectoryInfo) { result = true; } return result; } protected override string MakePath(string parent, string child) { return Utilities.NormalizePath(base.MakePath(Utilities.DenormalizePath(parent), Utilities.DenormalizePath(child))); } #endregion #region IContentCmdletProvider Members public void ClearContent(string path) { object destObj = FindItemByPath(Utilities.NormalizePath(path), true, false); if (destObj is DiscFileInfo) { using (Stream s = ((DiscFileInfo)destObj).Open(FileMode.Open, FileAccess.ReadWrite)) { s.SetLength(0); } } else { WriteError(new ErrorRecord( new IOException("Cannot write to this item"), "BadContentDestination", ErrorCategory.InvalidOperation, destObj)); } } public object ClearContentDynamicParameters(string path) { return null; } public IContentReader GetContentReader(string path) { object destObj = FindItemByPath(Utilities.NormalizePath(path), true, false); if (destObj is DiscFileInfo) { return new FileContentReaderWriter( this, ((DiscFileInfo)destObj).Open(FileMode.Open, FileAccess.Read), DynamicParameters as ContentParameters); } else { WriteError(new ErrorRecord( new IOException("Cannot read from this item"), "BadContentSource", ErrorCategory.InvalidOperation, destObj)); return null; } } public object GetContentReaderDynamicParameters(string path) { return new ContentParameters(); } public IContentWriter GetContentWriter(string path) { object destObj = FindItemByPath(Utilities.NormalizePath(path), true, false); if (destObj is DiscFileInfo) { return new FileContentReaderWriter( this, ((DiscFileInfo)destObj).Open(FileMode.Open, FileAccess.ReadWrite), DynamicParameters as ContentParameters); } else { WriteError(new ErrorRecord( new IOException("Cannot write to this item"), "BadContentDestination", ErrorCategory.InvalidOperation, destObj)); return null; } } public object GetContentWriterDynamicParameters(string path) { return new ContentParameters(); } #endregion #region Type Extensions public static string Mode(PSObject instance) { if (instance == null) { return ""; } DiscFileSystemInfo fsi = instance.BaseObject as DiscFileSystemInfo; if (fsi == null) { return ""; } StringBuilder result = new StringBuilder(5); result.Append(((fsi.Attributes & FileAttributes.Directory) != 0) ? "d" : "-"); result.Append(((fsi.Attributes & FileAttributes.Archive) != 0) ? "a" : "-"); result.Append(((fsi.Attributes & FileAttributes.ReadOnly) != 0) ? "r" : "-"); result.Append(((fsi.Attributes & FileAttributes.Hidden) != 0) ? "h" : "-"); result.Append(((fsi.Attributes & FileAttributes.System) != 0) ? "s" : "-"); return result.ToString(); } #endregion private VirtualDiskPSDriveInfo DriveInfo { get { return PSDriveInfo as VirtualDiskPSDriveInfo; } } private VirtualDisk Disk { get { VirtualDiskPSDriveInfo driveInfo = DriveInfo; return (driveInfo != null) ? driveInfo.Disk : null; } } private object FindItemByPath(string path, bool preferFs, bool readOnly) { FileAccess fileAccess = readOnly ? FileAccess.Read : FileAccess.ReadWrite; string diskPath; string relPath; int mountSepIdx = path.IndexOf('!'); if (mountSepIdx < 0) { diskPath = path; relPath = ""; } else { diskPath = path.Substring(0, mountSepIdx); relPath = path.Substring(mountSepIdx + 1); } VirtualDisk disk = Disk; if( disk == null ) { OnDemandVirtualDisk odvd = new OnDemandVirtualDisk(Utilities.DenormalizePath(diskPath), fileAccess); if (odvd.IsValid) { disk = odvd; ShowSlowDiskWarning(); } else { return null; } } List<string> pathElems = new List<string>(relPath.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries)); if (pathElems.Count == 0) { return disk; } VolumeInfo volInfo = null; VolumeManager volMgr = DriveInfo != null ? DriveInfo.VolumeManager : new VolumeManager(disk); LogicalVolumeInfo[] volumes = volMgr.GetLogicalVolumes(); string volNumStr = pathElems[0].StartsWith("Volume", StringComparison.OrdinalIgnoreCase) ? pathElems[0].Substring(6) : null; int volNum; if (int.TryParse(volNumStr, out volNum) || volNum < 0 || volNum >= volumes.Length) { volInfo = volumes[volNum]; } else { volInfo = volMgr.GetVolume(Utilities.DenormalizePath(pathElems[0])); } pathElems.RemoveAt(0); if (volInfo == null || (pathElems.Count == 0 && !preferFs)) { return volInfo; } bool disposeFs; DiscFileSystem fs = GetFileSystem(volInfo, out disposeFs); try { if (fs == null) { return null; } // Special marker in the path - disambiguates the root folder from the volume // containing it. By this point it's done it's job (we didn't return volInfo), // so we just remove it. if (pathElems.Count > 0 && pathElems[0] == "$Root") { pathElems.RemoveAt(0); } string fsPath = string.Join(@"\", pathElems.ToArray()); if (fs.DirectoryExists(fsPath)) { return fs.GetDirectoryInfo(fsPath); } else if (fs.FileExists(fsPath)) { return fs.GetFileInfo(fsPath); } } finally { if (disposeFs && fs != null) { fs.Dispose(); } } return null; } private void ShowSlowDiskWarning() { const string varName = "DiscUtils_HideSlowDiskWarning"; PSVariable psVar = this.SessionState.PSVariable.Get(varName); if (psVar != null && psVar.Value != null) { bool warningHidden; string valStr = psVar.Value.ToString(); if (bool.TryParse(valStr, out warningHidden) && warningHidden) { return; } } WriteWarning("Slow disk access. Mount the disk using New-PSDrive to improve performance. This message will not show again."); this.SessionState.PSVariable.Set(varName, true.ToString()); } private DiscFileSystem GetFileSystem(VolumeInfo volInfo, out bool dispose) { if (DriveInfo != null) { dispose = false; return DriveInfo.GetFileSystem(volInfo); } else { // TODO: proper file system detection if (volInfo.BiosType == 7) { dispose = true; return new NtfsFileSystem(volInfo.Open()); } } dispose = false; return null; } private void GetChildren(string path, bool recurse, bool namesOnly) { if (string.IsNullOrEmpty(path)) { return; } object obj = FindItemByPath(path, false, true); if (obj is VirtualDisk) { VirtualDisk vd = (VirtualDisk)obj; EnumerateDisk(vd, path, recurse, namesOnly); } else if (obj is LogicalVolumeInfo) { LogicalVolumeInfo lvi = (LogicalVolumeInfo)obj; bool dispose; DiscFileSystem fs = GetFileSystem(lvi, out dispose); try { if (fs != null) { EnumerateDirectory(fs.Root, path, recurse, namesOnly); } } finally { if (dispose && fs != null) { fs.Dispose(); } } } else if (obj is DiscDirectoryInfo) { DiscDirectoryInfo ddi = (DiscDirectoryInfo)obj; EnumerateDirectory(ddi, path, recurse, namesOnly); } else { WriteError(new ErrorRecord( new InvalidOperationException("Unrecognized object type: " + (obj != null ? obj.GetType() : null)), "UnknownObjectType", ErrorCategory.ParserError, obj)); } } private void EnumerateDisk(VirtualDisk vd, string path, bool recurse, bool namesOnly) { if (!path.TrimEnd('\\').EndsWith("!")) { path += "!"; } VolumeManager volMgr = DriveInfo != null ? DriveInfo.VolumeManager : new VolumeManager(vd); LogicalVolumeInfo[] volumes = volMgr.GetLogicalVolumes(); for (int i = 0; i < volumes.Length; ++i) { string name = "Volume" + i; string volPath = MakePath(path, name);// new PathInfo(PathInfo.Parse(path, true).MountParts, "" + i).ToString(); WriteItemObject(namesOnly ? name : (object)volumes[i], volPath, true); if (recurse) { GetChildren(volPath, recurse, namesOnly); } } } private void EnumerateDirectory(DiscDirectoryInfo parent, string basePath, bool recurse, bool namesOnly) { foreach (var dir in parent.GetDirectories()) { WriteItemObject(namesOnly ? dir.Name : (object)dir, MakePath(basePath, dir.Name), true); if (recurse) { EnumerateDirectory(dir, MakePath(basePath, dir.Name), recurse, namesOnly); } } foreach (var file in parent.GetFiles()) { WriteItemObject(namesOnly ? file.Name : (object)file, MakePath(basePath, file.Name), false); } } private void DoCopy(DiscDirectoryInfo srcDir, string srcFileName, DiscDirectoryInfo destDir, string destFileName, bool recurse) { string srcPath = Path.Combine(srcDir.FullName, srcFileName); string destPath = Path.Combine(destDir.FullName, destFileName); if ((srcDir.FileSystem.GetAttributes(srcPath) & FileAttributes.Directory) == 0) { DoCopyFile(srcDir.FileSystem, srcPath, destDir.FileSystem, destPath); } else { DoCopyDirectory(srcDir.FileSystem, srcPath, destDir.FileSystem, destPath); if (recurse) { DoRecursiveCopy(srcDir.FileSystem, srcPath, destDir.FileSystem, destPath); } } } private void DoRecursiveCopy(DiscFileSystem srcFs, string srcPath, DiscFileSystem destFs, string destPath) { foreach (var dir in srcFs.GetDirectories(srcPath)) { string srcDirPath = Path.Combine(srcPath, dir); string destDirPath = Path.Combine(destPath, dir); DoCopyDirectory(srcFs, srcDirPath, destFs, destDirPath); DoRecursiveCopy(srcFs, srcDirPath, destFs, destDirPath); } foreach (var file in srcFs.GetFiles(srcPath)) { string srcFilePath = Path.Combine(srcPath, file); string destFilePath = Path.Combine(destPath, file); DoCopyFile(srcFs, srcFilePath, destFs, destFilePath); } } private void DoCopyDirectory(DiscFileSystem srcFs, string srcPath, DiscFileSystem destFs, string destPath) { IWindowsFileSystem destWindowsFs = destFs as IWindowsFileSystem; IWindowsFileSystem srcWindowsFs = srcFs as IWindowsFileSystem; destFs.CreateDirectory(destPath); if (srcWindowsFs != null && destWindowsFs != null) { if ((srcWindowsFs.GetAttributes(srcPath) & FileAttributes.ReparsePoint) != 0) { destWindowsFs.SetReparsePoint(destPath, srcWindowsFs.GetReparsePoint(srcPath)); } destWindowsFs.SetSecurity(destPath, srcWindowsFs.GetSecurity(srcPath)); } destFs.SetAttributes(destPath, srcFs.GetAttributes(srcPath)); } private void DoCopyFile(DiscFileSystem srcFs, string srcPath, DiscFileSystem destFs, string destPath) { IWindowsFileSystem destWindowsFs = destFs as IWindowsFileSystem; IWindowsFileSystem srcWindowsFs = srcFs as IWindowsFileSystem; using (Stream src = srcFs.OpenFile(srcPath, FileMode.Open, FileAccess.Read)) using (Stream dest = destFs.OpenFile(destPath, FileMode.Create, FileAccess.ReadWrite)) { dest.SetLength(src.Length); byte[] buffer = new byte[1024 * 1024]; int numRead = src.Read(buffer, 0, buffer.Length); while (numRead > 0) { dest.Write(buffer, 0, numRead); numRead = src.Read(buffer, 0, buffer.Length); } } if (srcWindowsFs != null && destWindowsFs != null) { if ((srcWindowsFs.GetAttributes(srcPath) & FileAttributes.ReparsePoint) != 0) { destWindowsFs.SetReparsePoint(destPath, srcWindowsFs.GetReparsePoint(srcPath)); } var sd = srcWindowsFs.GetSecurity(srcPath); if(sd != null) { destWindowsFs.SetSecurity(destPath, sd); } } destFs.SetAttributes(destPath, srcFs.GetAttributes(srcPath)); destFs.SetCreationTimeUtc(destPath, srcFs.GetCreationTimeUtc(srcPath)); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Dumps commands in QueryStatus and Exec. // #define DUMP_COMMANDS using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.InteractiveWindow.Shell { internal sealed class VsInteractiveWindowCommandFilter : IOleCommandTarget { // // Command filter chain: // *window* -> VsTextView -> ... -> *pre-language + the current language service's filter* -> editor services -> *preEditor* -> editor // private IOleCommandTarget _preLanguageCommandFilter; private IOleCommandTarget _editorServicesCommandFilter; private IOleCommandTarget _preEditorCommandFilter; private IOleCommandTarget _editorCommandFilter; // we route undo/redo commands to this target: internal IOleCommandTarget currentBufferCommandHandler; internal IOleCommandTarget firstLanguageServiceCommandFilter; private readonly IInteractiveWindow _window; internal readonly IVsTextView textViewAdapter; private readonly IWpfTextViewHost _textViewHost; internal readonly IEnumerable<Lazy<IVsInteractiveWindowOleCommandTargetProvider, ContentTypeMetadata>> _oleCommandTargetProviders; internal readonly IContentTypeRegistryService _contentTypeRegistry; public VsInteractiveWindowCommandFilter(IVsEditorAdaptersFactoryService adapterFactory, IInteractiveWindow window, IVsTextView textViewAdapter, IVsTextBuffer bufferAdapter, IEnumerable<Lazy<IVsInteractiveWindowOleCommandTargetProvider, ContentTypeMetadata>> oleCommandTargetProviders, IContentTypeRegistryService contentTypeRegistry) { _window = window; _oleCommandTargetProviders = oleCommandTargetProviders; _contentTypeRegistry = contentTypeRegistry; this.textViewAdapter = textViewAdapter; // make us a code window so we'll have the same colors as a normal code window. IVsTextEditorPropertyContainer propContainer; ErrorHandler.ThrowOnFailure(((IVsTextEditorPropertyCategoryContainer)textViewAdapter).GetPropertyCategory(Microsoft.VisualStudio.Editor.DefGuidList.guidEditPropCategoryViewMasterSettings, out propContainer)); propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewComposite_AllCodeWindowDefaults, true); propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewGlobalOpt_AutoScrollCaretOnTextEntry, true); // editor services are initialized in textViewAdapter.Initialize - hook underneath them: _preEditorCommandFilter = new CommandFilter(this, CommandFilterLayer.PreEditor); ErrorHandler.ThrowOnFailure(textViewAdapter.AddCommandFilter(_preEditorCommandFilter, out _editorCommandFilter)); textViewAdapter.Initialize( (IVsTextLines)bufferAdapter, IntPtr.Zero, (uint)TextViewInitFlags.VIF_HSCROLL | (uint)TextViewInitFlags.VIF_VSCROLL | (uint)TextViewInitFlags3.VIF_NO_HWND_SUPPORT, new[] { new INITVIEW { fSelectionMargin = 0, fWidgetMargin = 0, fVirtualSpace = 0, fDragDropMove = 1 } }); // disable change tracking because everything will be changed var textViewHost = adapterFactory.GetWpfTextViewHost(textViewAdapter); _preLanguageCommandFilter = new CommandFilter(this, CommandFilterLayer.PreLanguage); ErrorHandler.ThrowOnFailure(textViewAdapter.AddCommandFilter(_preLanguageCommandFilter, out _editorServicesCommandFilter)); _textViewHost = textViewHost; } private IOleCommandTarget TextViewCommandFilterChain { get { // Non-character command processing starts with WindowFrame which calls ReplWindow.Exec. // We need to invoke the view's Exec method in order to invoke its full command chain // (features add their filters to the view). return (IOleCommandTarget)textViewAdapter; } } #region IOleCommandTarget public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { var nextTarget = TextViewCommandFilterChain; return nextTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { var nextTarget = TextViewCommandFilterChain; return nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } #endregion public IWpfTextViewHost TextViewHost { get { return _textViewHost; } } private enum CommandFilterLayer { PreLanguage, PreEditor } private sealed class CommandFilter : IOleCommandTarget { private readonly VsInteractiveWindowCommandFilter _window; private readonly CommandFilterLayer _layer; public CommandFilter(VsInteractiveWindowCommandFilter window, CommandFilterLayer layer) { _window = window; _layer = layer; } public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { try { switch (_layer) { case CommandFilterLayer.PreLanguage: return _window.PreLanguageCommandFilterQueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); case CommandFilterLayer.PreEditor: return _window.PreEditorCommandFilterQueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); default: throw Roslyn.Utilities.ExceptionUtilities.UnexpectedValue(_layer); } } catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) { // Exceptions should not escape from command filters. return _window._editorCommandFilter.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } } public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { try { switch (_layer) { case CommandFilterLayer.PreLanguage: return _window.PreLanguageCommandFilterExec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); case CommandFilterLayer.PreEditor: return _window.PreEditorCommandFilterExec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); default: throw Roslyn.Utilities.ExceptionUtilities.UnexpectedValue(_layer); } } catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) { // Exceptions should not escape from command filters. return _window._editorCommandFilter.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } } } private int PreEditorCommandFilterQueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { if (pguidCmdGroup == Guids.InteractiveCommandSetId) { switch ((CommandIds)prgCmds[0].cmdID) { case CommandIds.BreakLine: prgCmds[0].cmdf = _window.CurrentLanguageBuffer != null ? CommandEnabled : CommandDisabled; prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU; return VSConstants.S_OK; } } return _editorCommandFilter.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } private int PreEditorCommandFilterExec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { var nextTarget = _editorCommandFilter; if (pguidCmdGroup == Guids.InteractiveCommandSetId) { switch ((CommandIds)nCmdID) { case CommandIds.BreakLine: if (_window.Operations.BreakLine()) { return VSConstants.S_OK; } break; } } else if (pguidCmdGroup == VSConstants.VSStd2K) { switch ((VSConstants.VSStd2KCmdID)nCmdID) { case VSConstants.VSStd2KCmdID.RETURN: if (_window.Operations.Return()) { return VSConstants.S_OK; } break; // TODO: //case VSConstants.VSStd2KCmdID.DELETEWORDLEFT: //case VSConstants.VSStd2KCmdID.DELETEWORDRIGHT: // break; case VSConstants.VSStd2KCmdID.BACKSPACE: if (_window.Operations.Backspace()) { return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.UP: if (_window.CurrentLanguageBuffer != null && !_window.IsRunning && CaretAtEnd && UseSmartUpDown) { _window.Operations.HistoryPrevious(); return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.DOWN: if (_window.CurrentLanguageBuffer != null && !_window.IsRunning && CaretAtEnd && UseSmartUpDown) { _window.Operations.HistoryNext(); return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.CANCEL: if (_window.TextView.Selection.IsEmpty) { _window.Operations.Cancel(); } break; case VSConstants.VSStd2KCmdID.BOL: _window.Operations.Home(false); return VSConstants.S_OK; case VSConstants.VSStd2KCmdID.BOL_EXT: _window.Operations.Home(true); return VSConstants.S_OK; case VSConstants.VSStd2KCmdID.EOL: _window.Operations.End(false); return VSConstants.S_OK; case VSConstants.VSStd2KCmdID.EOL_EXT: _window.Operations.End(true); return VSConstants.S_OK; } } else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) { switch ((VSConstants.VSStd97CmdID)nCmdID) { case VSConstants.VSStd97CmdID.Paste: _window.Operations.Paste(); return VSConstants.S_OK; case VSConstants.VSStd97CmdID.Cut: _window.Operations.Cut(); return VSConstants.S_OK; case VSConstants.VSStd97CmdID.Copy: var operations = _window.Operations as IInteractiveWindowOperations2; if (operations != null) { operations.Copy(); return VSConstants.S_OK; } break; case VSConstants.VSStd97CmdID.Delete: if (_window.Operations.Delete()) { return VSConstants.S_OK; } break; case VSConstants.VSStd97CmdID.SelectAll: _window.Operations.SelectAll(); return VSConstants.S_OK; } } return nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } private int PreLanguageCommandFilterQueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { var nextTarget = firstLanguageServiceCommandFilter ?? _editorServicesCommandFilter; if (pguidCmdGroup == Guids.InteractiveCommandSetId) { switch ((CommandIds)prgCmds[0].cmdID) { case CommandIds.HistoryNext: case CommandIds.HistoryPrevious: case CommandIds.SearchHistoryNext: case CommandIds.SearchHistoryPrevious: case CommandIds.SmartExecute: // TODO: Submit? prgCmds[0].cmdf = _window.CurrentLanguageBuffer != null ? CommandEnabled : CommandDisabled; prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU; return VSConstants.S_OK; case CommandIds.AbortExecution: prgCmds[0].cmdf = _window.IsRunning ? CommandEnabled : CommandDisabled; prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU; return VSConstants.S_OK; case CommandIds.Reset: prgCmds[0].cmdf = !_window.IsResetting ? CommandEnabled : CommandDisabled; prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU; return VSConstants.S_OK; default: prgCmds[0].cmdf = CommandEnabled; break; } prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU; } else if (currentBufferCommandHandler != null && pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) { // undo/redo support: switch ((VSConstants.VSStd97CmdID)prgCmds[0].cmdID) { case VSConstants.VSStd97CmdID.Undo: case VSConstants.VSStd97CmdID.MultiLevelUndo: case VSConstants.VSStd97CmdID.MultiLevelUndoList: case VSConstants.VSStd97CmdID.Redo: case VSConstants.VSStd97CmdID.MultiLevelRedo: case VSConstants.VSStd97CmdID.MultiLevelRedoList: return currentBufferCommandHandler.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } } if (nextTarget != null) { var result = nextTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); #if DUMP_COMMANDS //DumpCmd("QS", result, ref pguidCmdGroup, prgCmds[0].cmdID, prgCmds[0].cmdf); #endif return result; } return VSConstants.E_FAIL; } private int PreLanguageCommandFilterExec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { var nextTarget = firstLanguageServiceCommandFilter ?? _editorServicesCommandFilter; if (pguidCmdGroup == Guids.InteractiveCommandSetId) { switch ((CommandIds)nCmdID) { case CommandIds.AbortExecution: _window.Evaluator.AbortExecution(); return VSConstants.S_OK; case CommandIds.Reset: _window.Operations.ResetAsync(); return VSConstants.S_OK; case CommandIds.SmartExecute: _window.Operations.ExecuteInput(); return VSConstants.S_OK; case CommandIds.HistoryNext: _window.Operations.HistoryNext(); return VSConstants.S_OK; case CommandIds.HistoryPrevious: _window.Operations.HistoryPrevious(); return VSConstants.S_OK; case CommandIds.ClearScreen: _window.Operations.ClearView(); return VSConstants.S_OK; case CommandIds.SearchHistoryNext: _window.Operations.HistorySearchNext(); return VSConstants.S_OK; case CommandIds.SearchHistoryPrevious: _window.Operations.HistorySearchPrevious(); return VSConstants.S_OK; } } else if (pguidCmdGroup == VSConstants.VSStd2K) { switch ((VSConstants.VSStd2KCmdID)nCmdID) { case VSConstants.VSStd2KCmdID.TYPECHAR: _window.Operations.Delete(); break; case VSConstants.VSStd2KCmdID.RETURN: if (_window.Operations.TrySubmitStandardInput()) { return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.SHOWCONTEXTMENU: ShowContextMenu(); return VSConstants.S_OK; } } else if (currentBufferCommandHandler != null && pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) { // undo/redo support: switch ((VSConstants.VSStd97CmdID)nCmdID) { case VSConstants.VSStd97CmdID.Undo: case VSConstants.VSStd97CmdID.MultiLevelUndo: case VSConstants.VSStd97CmdID.MultiLevelUndoList: case VSConstants.VSStd97CmdID.Redo: case VSConstants.VSStd97CmdID.MultiLevelRedo: case VSConstants.VSStd97CmdID.MultiLevelRedoList: return currentBufferCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } } int res = nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); #if DUMP_COMMANDS DumpCmd("Exec", result, ref pguidCmdGroup, nCmdID, 0); #endif return res; } private void ShowContextMenu() { var uishell = (IVsUIShell)InteractiveWindowPackage.GetGlobalService(typeof(SVsUIShell)); if (uishell != null) { var pt = System.Windows.Forms.Cursor.Position; var position = new[] { new POINTS { x = (short)pt.X, y = (short)pt.Y } }; var guid = Guids.InteractiveCommandSetId; ErrorHandler.ThrowOnFailure(uishell.ShowContextMenu(0, ref guid, (int)MenuIds.InteractiveWindowContextMenu, position, this)); } } private const uint CommandEnabled = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); private const uint CommandDisabled = (uint)(OLECMDF.OLECMDF_SUPPORTED); private const uint CommandDisabledAndHidden = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED); private bool CaretAtEnd { get { var caret = _window.TextView.Caret; return caret.Position.BufferPosition.Position == caret.Position.BufferPosition.Snapshot.Length; } } private bool UseSmartUpDown { get { return _window.TextView.Options.GetOptionValue(InteractiveWindowOptions.SmartUpDown); } } public IOleCommandTarget EditorServicesCommandFilter { get { return _editorServicesCommandFilter; } } } }
/* * Copyright (c) 2006, Clutch, Inc. * Original Author: Jeff Cesnik * 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. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Net; using System.Net.Sockets; using System.Threading; using log4net; using OpenSim.Framework; using OpenSim.Framework.Monitoring; namespace OpenMetaverse { /// <summary> /// Base UDP server /// </summary> public abstract class OpenSimUDPBase { private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// This method is called when an incoming packet is received /// </summary> /// <param name="buffer">Incoming packet buffer</param> public abstract void PacketReceived(UDPPacketBuffer buffer); /// <summary>UDP port to bind to in server mode</summary> protected int m_udpPort; /// <summary>Local IP address to bind to in server mode</summary> protected IPAddress m_localBindAddress; /// <summary>UDP socket, used in either client or server mode</summary> private Socket m_udpSocket; /// <summary>Flag to process packets asynchronously or synchronously</summary> private bool m_asyncPacketHandling; /// <summary> /// Are we to use object pool(s) to reduce memory churn when receiving data? /// </summary> public bool UsePools { get; protected set; } /// <summary> /// Pool to use for handling data. May be null if UsePools = false; /// </summary> protected OpenSim.Framework.Pool<UDPPacketBuffer> Pool { get; private set; } /// <summary>Returns true if the server is currently listening for inbound packets, otherwise false</summary> public bool IsRunningInbound { get; private set; } /// <summary>Returns true if the server is currently sending outbound packets, otherwise false</summary> /// <remarks>If IsRunningOut = false, then any request to send a packet is simply dropped.</remarks> public bool IsRunningOutbound { get; private set; } /// <summary> /// Number of UDP receives. /// </summary> public int UdpReceives { get; private set; } /// <summary> /// Number of UDP sends /// </summary> public int UdpSends { get; private set; } /// <summary> /// Number of receives over which to establish a receive time average. /// </summary> private readonly static int s_receiveTimeSamples = 500; /// <summary> /// Current number of samples taken to establish a receive time average. /// </summary> private int m_currentReceiveTimeSamples; /// <summary> /// Cumulative receive time for the sample so far. /// </summary> private int m_receiveTicksInCurrentSamplePeriod; /// <summary> /// The average time taken for each require receive in the last sample. /// </summary> public float AverageReceiveTicksForLastSamplePeriod { get; private set; } #region PacketDropDebugging /// <summary> /// For debugging purposes only... random number generator for dropping /// outbound packets. /// </summary> private Random m_dropRandomGenerator = new Random(); /// <summary> /// For debugging purposes only... parameters for a simplified /// model of packet loss with bursts, overall drop rate should /// be roughly 1 - m_dropLengthProbability / (m_dropProbabiliy + m_dropLengthProbability) /// which is about 1% for parameters 0.0015 and 0.15 /// </summary> private double m_dropProbability = 0.0030; private double m_dropLengthProbability = 0.15; private bool m_dropState = false; /// <summary> /// For debugging purposes only... parameters to control the time /// duration over which packet loss bursts can occur, if no packets /// have been sent for m_dropResetTicks milliseconds, then reset the /// state of the packet dropper to its default. /// </summary> private int m_dropLastTick = 0; private int m_dropResetTicks = 500; /// <summary> /// Debugging code used to simulate dropped packets with bursts /// </summary> private bool DropOutgoingPacket() { double rnum = m_dropRandomGenerator.NextDouble(); // if the connection has been idle for awhile (more than m_dropResetTicks) then // reset the state to the default state, don't continue a burst int curtick = Util.EnvironmentTickCount(); if (Util.EnvironmentTickCountSubtract(curtick, m_dropLastTick) > m_dropResetTicks) m_dropState = false; m_dropLastTick = curtick; // if we are dropping packets, then the probability of dropping // this packet is the probability that we stay in the burst if (m_dropState) { m_dropState = (rnum < (1.0 - m_dropLengthProbability)) ? true : false; } else { m_dropState = (rnum < m_dropProbability) ? true : false; } return m_dropState; } #endregion PacketDropDebugging /// <summary> /// Default constructor /// </summary> /// <param name="bindAddress">Local IP address to bind the server to</param> /// <param name="port">Port to listening for incoming UDP packets on</param> /// /// <param name="usePool">Are we to use an object pool to get objects for handing inbound data?</param> public OpenSimUDPBase(IPAddress bindAddress, int port) { m_localBindAddress = bindAddress; m_udpPort = port; // for debugging purposes only, initializes the random number generator // used for simulating packet loss // m_dropRandomGenerator = new Random(); } /// <summary> /// Start inbound UDP packet handling. /// </summary> /// <param name="recvBufferSize">The size of the receive buffer for /// the UDP socket. This value is passed up to the operating system /// and used in the system networking stack. Use zero to leave this /// value as the default</param> /// <param name="asyncPacketHandling">Set this to true to start /// receiving more packets while current packet handler callbacks are /// still running. Setting this to false will complete each packet /// callback before the next packet is processed</param> /// <remarks>This method will attempt to set the SIO_UDP_CONNRESET flag /// on the socket to get newer versions of Windows to behave in a sane /// manner (not throwing an exception when the remote side resets the /// connection). This call is ignored on Mono where the flag is not /// necessary</remarks> public virtual void StartInbound(int recvBufferSize, bool asyncPacketHandling) { m_asyncPacketHandling = asyncPacketHandling; if (!IsRunningInbound) { m_log.DebugFormat("[UDPBASE]: Starting inbound UDP loop"); const int SIO_UDP_CONNRESET = -1744830452; IPEndPoint ipep = new IPEndPoint(m_localBindAddress, m_udpPort); m_udpSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // OpenSim may need this but in AVN, this messes up automated // sim restarts badly //m_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); try { if (m_udpSocket.Ttl < 128) { m_udpSocket.Ttl = 128; } } catch (SocketException) { m_log.Debug("[UDPBASE]: Failed to increase default TTL"); } try { // This udp socket flag is not supported under mono, // so we'll catch the exception and continue m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null); m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag set"); } catch (SocketException) { m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring"); } // On at least Mono 3.2.8, multiple UDP sockets can bind to the same port by default. At the moment // we never want two regions to listen on the same port as they cannot demultiplex each other's messages, // leading to a confusing bug. // By default, Windows does not allow two sockets to bind to the same port. m_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); if (recvBufferSize != 0) m_udpSocket.ReceiveBufferSize = recvBufferSize; m_udpSocket.Bind(ipep); IsRunningInbound = true; // kick off an async receive. The Start() method will return, the // actual receives will occur asynchronously and will be caught in // AsyncEndRecieve(). AsyncBeginReceive(); } } /// <summary> /// Start outbound UDP packet handling. /// </summary> public virtual void StartOutbound() { m_log.DebugFormat("[UDPBASE]: Starting outbound UDP loop"); IsRunningOutbound = true; } public virtual void StopInbound() { if (IsRunningInbound) { m_log.DebugFormat("[UDPBASE]: Stopping inbound UDP loop"); IsRunningInbound = false; m_udpSocket.Close(); } } public virtual void StopOutbound() { m_log.DebugFormat("[UDPBASE]: Stopping outbound UDP loop"); IsRunningOutbound = false; } public virtual bool EnablePools() { if (!UsePools) { Pool = new Pool<UDPPacketBuffer>(() => new UDPPacketBuffer(), 500); UsePools = true; return true; } return false; } public virtual bool DisablePools() { if (UsePools) { UsePools = false; // We won't null out the pool to avoid a race condition with code that may be in the middle of using it. return true; } return false; } private void AsyncBeginReceive() { UDPPacketBuffer buf; // FIXME: Disabled for now as this causes issues with reused packet objects interfering with each other // on Windows with m_asyncPacketHandling = true, though this has not been seen on Linux. // Possibly some unexpected issue with fetching UDP data concurrently with multiple threads. Requires more investigation. // if (UsePools) // buf = Pool.GetObject(); // else buf = new UDPPacketBuffer(); if (IsRunningInbound) { try { // kick off an async read m_udpSocket.BeginReceiveFrom( //wrappedBuffer.Instance.Data, buf.Data, 0, UDPPacketBuffer.BUFFER_SIZE, SocketFlags.None, ref buf.RemoteEndPoint, AsyncEndReceive, //wrappedBuffer); buf); } catch (SocketException e) { if (e.SocketErrorCode == SocketError.ConnectionReset) { m_log.Warn("[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + m_udpPort); bool salvaged = false; while (!salvaged) { try { m_udpSocket.BeginReceiveFrom( //wrappedBuffer.Instance.Data, buf.Data, 0, UDPPacketBuffer.BUFFER_SIZE, SocketFlags.None, ref buf.RemoteEndPoint, AsyncEndReceive, //wrappedBuffer); buf); salvaged = true; } catch (SocketException) { } catch (ObjectDisposedException) { return; } } m_log.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort); } } catch (ObjectDisposedException e) { m_log.Error( string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e); } catch (Exception e) { m_log.Error( string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e); } } } private void AsyncEndReceive(IAsyncResult iar) { // Asynchronous receive operations will complete here through the call // to AsyncBeginReceive if (IsRunningInbound) { UdpReceives++; // Asynchronous mode will start another receive before the // callback for this packet is even fired. Very parallel :-) if (m_asyncPacketHandling) AsyncBeginReceive(); try { // get the buffer that was created in AsyncBeginReceive // this is the received data UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState; int startTick = Util.EnvironmentTickCount(); // get the length of data actually read from the socket, store it with the // buffer buffer.DataLength = m_udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint); // call the abstract method PacketReceived(), passing the buffer that // has just been filled from the socket read. PacketReceived(buffer); // If more than one thread can be calling AsyncEndReceive() at once (e.g. if m_asyncPacketHandler) // then a particular stat may be inaccurate due to a race condition. We won't worry about this // since this should be rare and won't cause a runtime problem. if (m_currentReceiveTimeSamples >= s_receiveTimeSamples) { AverageReceiveTicksForLastSamplePeriod = (float)m_receiveTicksInCurrentSamplePeriod / s_receiveTimeSamples; m_receiveTicksInCurrentSamplePeriod = 0; m_currentReceiveTimeSamples = 0; } else { m_receiveTicksInCurrentSamplePeriod += Util.EnvironmentTickCountSubtract(startTick); m_currentReceiveTimeSamples++; } } catch (SocketException se) { m_log.Error( string.Format( "[UDPBASE]: Error processing UDP end receive {0}, socket error code {1}. Exception ", UdpReceives, se.ErrorCode), se); } catch (ObjectDisposedException e) { m_log.Error( string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e); } catch (Exception e) { m_log.Error( string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e); } finally { // if (UsePools) // Pool.ReturnObject(buffer); // Synchronous mode waits until the packet callback completes // before starting the receive to fetch another packet if (!m_asyncPacketHandling) AsyncBeginReceive(); } } } public void AsyncBeginSend(UDPPacketBuffer buf) { // if (IsRunningOutbound) // { // This is strictly for debugging purposes to simulate dropped // packets when testing throttles & retransmission code // if (DropOutgoingPacket()) // return; try { m_udpSocket.BeginSendTo( buf.Data, 0, buf.DataLength, SocketFlags.None, buf.RemoteEndPoint, AsyncEndSend, buf); } catch (SocketException) { } catch (ObjectDisposedException) { } // } } void AsyncEndSend(IAsyncResult result) { try { // UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState; m_udpSocket.EndSendTo(result); UdpSends++; } catch (SocketException) { } catch (ObjectDisposedException) { } } } }
// 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; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace System.Net.Sockets { // Note on asynchronous behavior here: // The asynchronous socket operations here generally do the following: // (1) If the operation queue is empty, try to perform the operation immediately, non-blocking. // If this completes (i.e. does not return EWOULDBLOCK), then we return the results immediately // for both success (SocketError.Success) or failure. // No callback will happen; callers are expected to handle these synchronous completions themselves. // (2) If EWOULDBLOCK is returned, or the queue is not empty, then we enqueue an operation to the // appropriate queue and return SocketError.IOPending. // Enqueuing itself may fail because the socket is closed before the operation can be enqueued; // in this case, we return SocketError.OperationAborted (which matches what Winsock would return in this case). // (3) When the queue completes the operation, it will post a work item to the threadpool // to call the callback with results (either success or failure). // Synchronous operations generally do the same, except that instead of returning IOPending, // they block on an event handle until the operation is processed by the queue. // Also, synchronous methods return SocketError.Interrupted when enqueuing fails // (which again matches Winsock behavior). internal sealed class SocketAsyncContext { private abstract class AsyncOperation { private enum State { Waiting = 0, Running = 1, Complete = 2, Cancelled = 3 } private int _state; // Actually AsyncOperation.State. #if DEBUG private int _callbackQueued; // When non-zero, the callback has been queued. #endif public AsyncOperation Next; protected object CallbackOrEvent; public SocketError ErrorCode; public byte[] SocketAddress; public int SocketAddressLen; public ManualResetEventSlim Event { private get { return (ManualResetEventSlim)CallbackOrEvent; } set { CallbackOrEvent = value; } } public AsyncOperation() { _state = (int)State.Waiting; Next = this; } public bool TryComplete(SocketAsyncContext context) { Debug.Assert(_state == (int)State.Waiting, $"Unexpected _state: {_state}"); return DoTryComplete(context); } public bool TryCompleteAsync(SocketAsyncContext context) { return TryCompleteOrAbortAsync(context, abort: false); } public void AbortAsync() { bool completed = TryCompleteOrAbortAsync(null, abort: true); Debug.Assert(completed, $"Expected TryCompleteOrAbortAsync to return true"); } private bool TryCompleteOrAbortAsync(SocketAsyncContext context, bool abort) { Debug.Assert(context != null || abort, $"Unexpected values: context={context}, abort={abort}"); State oldState = (State)Interlocked.CompareExchange(ref _state, (int)State.Running, (int)State.Waiting); if (oldState == State.Cancelled) { // This operation has been cancelled. The canceller is responsible for // correctly updating any state that would have been handled by // AsyncOperation.Abort. return true; } Debug.Assert(oldState != State.Complete && oldState != State.Running, $"Unexpected oldState: {oldState}"); bool completed; if (abort) { Abort(); ErrorCode = SocketError.OperationAborted; completed = true; } else { completed = DoTryComplete(context); } if (completed) { var @event = CallbackOrEvent as ManualResetEventSlim; if (@event != null) { @event.Set(); } else { Debug.Assert(_state != (int)State.Cancelled, $"Unexpected _state: {_state}"); #if DEBUG Debug.Assert(Interlocked.CompareExchange(ref _callbackQueued, 1, 0) == 0, $"Unexpected _callbackQueued: {_callbackQueued}"); #endif ThreadPool.QueueUserWorkItem(o => ((AsyncOperation)o).InvokeCallback(), this); } Volatile.Write(ref _state, (int)State.Complete); return true; } Volatile.Write(ref _state, (int)State.Waiting); return false; } public bool Wait(int timeout) { if (Event.Wait(timeout)) { return true; } var spinWait = new SpinWait(); for (;;) { int state = Interlocked.CompareExchange(ref _state, (int)State.Cancelled, (int)State.Waiting); switch ((State)state) { case State.Running: // A completion attempt is in progress. Keep busy-waiting. spinWait.SpinOnce(); break; case State.Complete: // A completion attempt succeeded. Consider this operation as having completed within the timeout. return true; case State.Waiting: // This operation was successfully cancelled. return false; } } } protected abstract void Abort(); protected abstract bool DoTryComplete(SocketAsyncContext context); protected abstract void InvokeCallback(); } // These two abstract classes differentiate the operations that go in the // read queue vs the ones that go in the write queue. private abstract class ReadOperation : AsyncOperation { } private abstract class WriteOperation : AsyncOperation { } private sealed class SendOperation : WriteOperation { public byte[] Buffer; public int Offset; public int Count; public SocketFlags Flags; public int BytesTransferred; public IList<ArraySegment<byte>> Buffers; public int BufferIndex; protected sealed override void Abort() { } public Action<int, byte[], int, SocketFlags, SocketError> Callback { private get { return (Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent; } set { CallbackOrEvent = value; } } protected sealed override void InvokeCallback() { Callback(BytesTransferred, SocketAddress, SocketAddressLen, SocketFlags.None, ErrorCode); } protected override bool DoTryComplete(SocketAsyncContext context) { return SocketPal.TryCompleteSendTo(context._socket, Buffer, Buffers, ref BufferIndex, ref Offset, ref Count, Flags, SocketAddress, SocketAddressLen, ref BytesTransferred, out ErrorCode); } } private sealed class ReceiveOperation : ReadOperation { public byte[] Buffer; public int Offset; public int Count; public SocketFlags Flags; public int BytesTransferred; public SocketFlags ReceivedFlags; public IList<ArraySegment<byte>> Buffers; protected sealed override void Abort() { } public Action<int, byte[], int, SocketFlags, SocketError> Callback { private get { return (Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent; } set { CallbackOrEvent = value; } } protected sealed override void InvokeCallback() { Callback(BytesTransferred, SocketAddress, SocketAddressLen, ReceivedFlags, ErrorCode); } protected override bool DoTryComplete(SocketAsyncContext context) { return SocketPal.TryCompleteReceiveFrom(context._socket, Buffer, Buffers, Offset, Count, Flags, SocketAddress, ref SocketAddressLen, out BytesTransferred, out ReceivedFlags, out ErrorCode); } } private sealed class ReceiveMessageFromOperation : ReadOperation { public byte[] Buffer; public int Offset; public int Count; public SocketFlags Flags; public int BytesTransferred; public SocketFlags ReceivedFlags; public bool IsIPv4; public bool IsIPv6; public IPPacketInformation IPPacketInformation; protected sealed override void Abort() { } public Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError> Callback { private get { return (Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError>)CallbackOrEvent; } set { CallbackOrEvent = value; } } protected override bool DoTryComplete(SocketAsyncContext context) { return SocketPal.TryCompleteReceiveMessageFrom(context._socket, Buffer, Offset, Count, Flags, SocketAddress, ref SocketAddressLen, IsIPv4, IsIPv6, out BytesTransferred, out ReceivedFlags, out IPPacketInformation, out ErrorCode); } protected override void InvokeCallback() { Callback(BytesTransferred, SocketAddress, SocketAddressLen, ReceivedFlags, IPPacketInformation, ErrorCode); } } private sealed class AcceptOperation : ReadOperation { public IntPtr AcceptedFileDescriptor; public Action<IntPtr, byte[], int, SocketError> Callback { private get { return (Action<IntPtr, byte[], int, SocketError>)CallbackOrEvent; } set { CallbackOrEvent = value; } } protected override void Abort() { AcceptedFileDescriptor = (IntPtr)(-1); } protected override bool DoTryComplete(SocketAsyncContext context) { bool completed = SocketPal.TryCompleteAccept(context._socket, SocketAddress, ref SocketAddressLen, out AcceptedFileDescriptor, out ErrorCode); Debug.Assert(ErrorCode == SocketError.Success || AcceptedFileDescriptor == (IntPtr)(-1), $"Unexpected values: ErrorCode={ErrorCode}, AcceptedFileDescriptor={AcceptedFileDescriptor}"); return completed; } protected override void InvokeCallback() { Callback(AcceptedFileDescriptor, SocketAddress, SocketAddressLen, ErrorCode); } } private sealed class ConnectOperation : WriteOperation { public Action<SocketError> Callback { private get { return (Action<SocketError>)CallbackOrEvent; } set { CallbackOrEvent = value; } } protected override void Abort() { } protected override bool DoTryComplete(SocketAsyncContext context) { bool result = SocketPal.TryCompleteConnect(context._socket, SocketAddressLen, out ErrorCode); context._socket.RegisterConnectResult(ErrorCode); return result; } protected override void InvokeCallback() { Callback(ErrorCode); } } private sealed class SendFileOperation : WriteOperation { public SafeFileHandle FileHandle; public long Offset; public long Count; public long BytesTransferred; protected override void Abort() { } public Action<long, SocketError> Callback { private get { return (Action<long, SocketError>)CallbackOrEvent; } set { CallbackOrEvent = value; } } protected override void InvokeCallback() { Callback(BytesTransferred, ErrorCode); } protected override bool DoTryComplete(SocketAsyncContext context) { return SocketPal.TryCompleteSendFile(context._socket, FileHandle, ref Offset, ref Count, ref BytesTransferred, out ErrorCode); } } private enum QueueState { Clear = 0, Set = 1, Stopped = 2, } private struct OperationQueue<TOperation> where TOperation : AsyncOperation { private object _queueLock; private AsyncOperation _tail; public QueueState State { get; set; } public bool IsStopped { get { return State == QueueState.Stopped; } } public bool IsEmpty { get { return _tail == null; } } public object QueueLock { get { return _queueLock; } } public void Init() { Debug.Assert(_queueLock == null); _queueLock = new object(); } public void Enqueue(TOperation operation) { Debug.Assert(!IsStopped, "Expected !IsStopped"); Debug.Assert(operation.Next == operation, "Expected operation.Next == operation"); if (!IsEmpty) { operation.Next = _tail.Next; _tail.Next = operation; } _tail = operation; } private bool TryDequeue(out TOperation operation) { if (_tail == null) { operation = null; return false; } AsyncOperation head = _tail.Next; if (head == _tail) { _tail = null; } else { _tail.Next = head.Next; } head.Next = null; operation = (TOperation)head; return true; } private void Requeue(TOperation operation) { // Insert at the head of the queue Debug.Assert(!IsStopped, "Expected !IsStopped"); Debug.Assert(operation.Next == null, "Operation already in queue"); if (IsEmpty) { operation.Next = operation; _tail = operation; } else { operation.Next = _tail.Next; _tail.Next = operation; } } public void Complete(SocketAsyncContext context) { lock (_queueLock) { if (IsStopped) return; State = QueueState.Set; TOperation op; while (TryDequeue(out op)) { if (!op.TryCompleteAsync(context)) { Requeue(op); return; } } } } public void StopAndAbort() { lock (_queueLock) { State = QueueState.Stopped; TOperation op; while (TryDequeue(out op)) { op.AbortAsync(); } } } } private readonly SafeCloseSocket _socket; private OperationQueue<ReadOperation> _receiveQueue; private OperationQueue<WriteOperation> _sendQueue; private SocketAsyncEngine.Token _asyncEngineToken; private Interop.Sys.SocketEvents _registeredEvents; private bool _nonBlockingSet; private readonly object _registerLock = new object(); public SocketAsyncContext(SafeCloseSocket socket) { _socket = socket; _receiveQueue.Init(); _sendQueue.Init(); } private void Register(Interop.Sys.SocketEvents events) { lock (_registerLock) { Debug.Assert((_registeredEvents & events) == Interop.Sys.SocketEvents.None, $"Unexpected values: _registeredEvents={_registeredEvents}, events={events}"); if (!_asyncEngineToken.WasAllocated) { _asyncEngineToken = new SocketAsyncEngine.Token(this); } events |= _registeredEvents; Interop.Error errorCode; if (!_asyncEngineToken.TryRegister(_socket, _registeredEvents, events, out errorCode)) { if (errorCode == Interop.Error.ENOMEM || errorCode == Interop.Error.ENOSPC) { throw new OutOfMemoryException(); } else { throw new InternalException(); } } _registeredEvents = events; } } public void Close() { // Drain queues _sendQueue.StopAndAbort(); _receiveQueue.StopAndAbort(); lock (_registerLock) { // Freeing the token will prevent any future event delivery. This socket will be unregistered // from the event port automatically by the OS when it's closed. _asyncEngineToken.Free(); } } public void SetNonBlocking() { // // Our sockets may start as blocking, and later transition to non-blocking, either because the user // explicitly requested non-blocking mode, or because we need non-blocking mode to support async // operations. We never transition back to blocking mode, to avoid problems synchronizing that // transition with the async infrastructure. // // Note that there's no synchronization here, so we may set the non-blocking option multiple times // in a race. This should be fine. // if (!_nonBlockingSet) { if (Interop.Sys.Fcntl.SetIsNonBlocking(_socket, 1) != 0) { throw new SocketException((int)SocketPal.GetSocketErrorForErrorCode(Interop.Sys.GetLastError())); } _nonBlockingSet = true; } } private bool TryBeginOperation<TOperation>(ref OperationQueue<TOperation> queue, TOperation operation, Interop.Sys.SocketEvents events, bool maintainOrder, out bool isStopped) where TOperation : AsyncOperation { // Exactly one of the two queue locks must be held by the caller Debug.Assert(Monitor.IsEntered(_sendQueue.QueueLock) ^ Monitor.IsEntered(_receiveQueue.QueueLock)); switch (queue.State) { case QueueState.Stopped: isStopped = true; return false; case QueueState.Clear: break; case QueueState.Set: if (queue.IsEmpty || !maintainOrder) { isStopped = false; queue.State = QueueState.Clear; return false; } break; } if ((_registeredEvents & events) == Interop.Sys.SocketEvents.None) { Register(events); } queue.Enqueue(operation); isStopped = false; return true; } public SocketError Accept(byte[] socketAddress, ref int socketAddressLen, int timeout, out IntPtr acceptedFd) { Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}"); Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); SocketError errorCode; if (SocketPal.TryCompleteAccept(_socket, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode)) { Debug.Assert(errorCode == SocketError.Success || acceptedFd == (IntPtr)(-1), $"Unexpected values: errorCode={errorCode}, acceptedFd={acceptedFd}"); return errorCode; } using (var @event = new ManualResetEventSlim(false, 0)) { var operation = new AcceptOperation { Event = @event, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen }; bool isStopped; while (true) { lock (_receiveQueue.QueueLock) { if (TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: false, isStopped: out isStopped)) { break; } } if (isStopped) { acceptedFd = (IntPtr)(-1); return SocketError.Interrupted; } if (operation.TryComplete(this)) { socketAddressLen = operation.SocketAddressLen; acceptedFd = operation.AcceptedFileDescriptor; return operation.ErrorCode; } } if (!operation.Wait(timeout)) { acceptedFd = (IntPtr)(-1); return SocketError.TimedOut; } socketAddressLen = operation.SocketAddressLen; acceptedFd = operation.AcceptedFileDescriptor; return operation.ErrorCode; } } public SocketError AcceptAsync(byte[] socketAddress, ref int socketAddressLen, out IntPtr acceptedFd, Action<IntPtr, byte[], int, SocketError> callback) { Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}"); Debug.Assert(callback != null, "Expected non-null callback"); SetNonBlocking(); SocketError errorCode; if (SocketPal.TryCompleteAccept(_socket, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode)) { Debug.Assert(errorCode == SocketError.Success || acceptedFd == (IntPtr)(-1), $"Unexpected values: errorCode={errorCode}, acceptedFd={acceptedFd}"); return errorCode; } var operation = new AcceptOperation { Callback = callback, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen }; bool isStopped; while (true) { lock (_receiveQueue.QueueLock) { if (TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: false, isStopped: out isStopped)) { break; } } if (isStopped) { return SocketError.OperationAborted; } if (operation.TryComplete(this)) { socketAddressLen = operation.SocketAddressLen; acceptedFd = operation.AcceptedFileDescriptor; return operation.ErrorCode; } } return SocketError.IOPending; } public SocketError Connect(byte[] socketAddress, int socketAddressLen, int timeout) { Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}"); Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); SocketError errorCode; if (SocketPal.TryStartConnect(_socket, socketAddress, socketAddressLen, out errorCode)) { _socket.RegisterConnectResult(errorCode); return errorCode; } using (var @event = new ManualResetEventSlim(false, 0)) { var operation = new ConnectOperation { Event = @event, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen }; bool isStopped; while (true) { lock (_sendQueue.QueueLock) { if (TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: false, isStopped: out isStopped)) { break; } } if (isStopped) { return SocketError.Interrupted; } if (operation.TryComplete(this)) { return operation.ErrorCode; } } return operation.Wait(timeout) ? operation.ErrorCode : SocketError.TimedOut; } } public SocketError ConnectAsync(byte[] socketAddress, int socketAddressLen, Action<SocketError> callback) { Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}"); Debug.Assert(callback != null, "Expected non-null callback"); SetNonBlocking(); SocketError errorCode; if (SocketPal.TryStartConnect(_socket, socketAddress, socketAddressLen, out errorCode)) { _socket.RegisterConnectResult(errorCode); return errorCode; } var operation = new ConnectOperation { Callback = callback, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen }; bool isStopped; while (true) { lock (_sendQueue.QueueLock) { if (TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: false, isStopped: out isStopped)) { break; } } if (isStopped) { return SocketError.OperationAborted; } if (operation.TryComplete(this)) { return operation.ErrorCode; } } return SocketError.IOPending; } public SocketError Receive(byte[] buffer, int offset, int count, ref SocketFlags flags, int timeout, out int bytesReceived) { int socketAddressLen = 0; return ReceiveFrom(buffer, offset, count, ref flags, null, ref socketAddressLen, timeout, out bytesReceived); } public SocketError ReceiveAsync(byte[] buffer, int offset, int count, SocketFlags flags, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[], int, SocketFlags, SocketError> callback) { int socketAddressLen = 0; return ReceiveFromAsync(buffer, offset, count, flags, null, ref socketAddressLen, out bytesReceived, out receivedFlags, callback); } public SocketError ReceiveFrom(byte[] buffer, int offset, int count, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, int timeout, out int bytesReceived) { Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); ManualResetEventSlim @event = null; try { ReceiveOperation operation; lock (_receiveQueue.QueueLock) { SocketFlags receivedFlags; SocketError errorCode; if (_receiveQueue.IsEmpty && SocketPal.TryCompleteReceiveFrom(_socket, buffer, offset, count, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode)) { flags = receivedFlags; return errorCode; } @event = new ManualResetEventSlim(false, 0); operation = new ReceiveOperation { Event = @event, Buffer = buffer, Offset = offset, Count = count, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, }; bool isStopped; while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { flags = operation.ReceivedFlags; bytesReceived = operation.BytesTransferred; return SocketError.Interrupted; } if (operation.TryComplete(this)) { socketAddressLen = operation.SocketAddressLen; flags = operation.ReceivedFlags; bytesReceived = operation.BytesTransferred; return operation.ErrorCode; } } } bool signaled = operation.Wait(timeout); socketAddressLen = operation.SocketAddressLen; flags = operation.ReceivedFlags; bytesReceived = operation.BytesTransferred; return signaled ? operation.ErrorCode : SocketError.TimedOut; } finally { if (@event != null) @event.Dispose(); } } public SocketError ReceiveFromAsync(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[], int, SocketFlags, SocketError> callback) { SetNonBlocking(); lock (_receiveQueue.QueueLock) { SocketError errorCode; if (_receiveQueue.IsEmpty && SocketPal.TryCompleteReceiveFrom(_socket, buffer, offset, count, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode)) { // Synchronous success or failure return errorCode; } var operation = new ReceiveOperation { Callback = callback, Buffer = buffer, Offset = offset, Count = count, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, }; bool isStopped; while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { bytesReceived = 0; receivedFlags = SocketFlags.None; return SocketError.OperationAborted; } if (operation.TryComplete(this)) { socketAddressLen = operation.SocketAddressLen; receivedFlags = operation.ReceivedFlags; bytesReceived = operation.BytesTransferred; return operation.ErrorCode; } } bytesReceived = 0; receivedFlags = SocketFlags.None; return SocketError.IOPending; } } public SocketError Receive(IList<ArraySegment<byte>> buffers, ref SocketFlags flags, int timeout, out int bytesReceived) { return ReceiveFrom(buffers, ref flags, null, 0, timeout, out bytesReceived); } public SocketError ReceiveAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[], int, SocketFlags, SocketError> callback) { int socketAddressLen = 0; return ReceiveFromAsync(buffers, flags, null, ref socketAddressLen, out bytesReceived, out receivedFlags, callback); } public SocketError ReceiveFrom(IList<ArraySegment<byte>> buffers, ref SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesReceived) { Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); ManualResetEventSlim @event = null; try { ReceiveOperation operation; lock (_receiveQueue.QueueLock) { SocketFlags receivedFlags; SocketError errorCode; if (_receiveQueue.IsEmpty && SocketPal.TryCompleteReceiveFrom(_socket, buffers, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode)) { flags = receivedFlags; return errorCode; } @event = new ManualResetEventSlim(false, 0); operation = new ReceiveOperation { Event = @event, Buffers = buffers, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, }; bool isStopped; while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { flags = operation.ReceivedFlags; bytesReceived = operation.BytesTransferred; return SocketError.Interrupted; } if (operation.TryComplete(this)) { socketAddressLen = operation.SocketAddressLen; flags = operation.ReceivedFlags; bytesReceived = operation.BytesTransferred; return operation.ErrorCode; } } } bool signaled = operation.Wait(timeout); socketAddressLen = operation.SocketAddressLen; flags = operation.ReceivedFlags; bytesReceived = operation.BytesTransferred; return signaled ? operation.ErrorCode : SocketError.TimedOut; } finally { if (@event != null) @event.Dispose(); } } public SocketError ReceiveFromAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[], int, SocketFlags, SocketError> callback) { SetNonBlocking(); ReceiveOperation operation; lock (_receiveQueue.QueueLock) { SocketError errorCode; if (_receiveQueue.IsEmpty && SocketPal.TryCompleteReceiveFrom(_socket, buffers, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode)) { // Synchronous success or failure return errorCode; } operation = new ReceiveOperation { Callback = callback, Buffers = buffers, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, }; bool isStopped; while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { bytesReceived = 0; receivedFlags = SocketFlags.None; return SocketError.OperationAborted; } if (operation.TryComplete(this)) { socketAddressLen = operation.SocketAddressLen; receivedFlags = operation.ReceivedFlags; bytesReceived = operation.BytesTransferred; return operation.ErrorCode; } } bytesReceived = 0; receivedFlags = SocketFlags.None; return SocketError.IOPending; } } public SocketError ReceiveMessageFrom(byte[] buffer, int offset, int count, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, int timeout, out IPPacketInformation ipPacketInformation, out int bytesReceived) { Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); ManualResetEventSlim @event = null; try { ReceiveMessageFromOperation operation; lock (_receiveQueue.QueueLock) { SocketFlags receivedFlags; SocketError errorCode; if (_receiveQueue.IsEmpty && SocketPal.TryCompleteReceiveMessageFrom(_socket, buffer, offset, count, flags, socketAddress, ref socketAddressLen, isIPv4, isIPv6, out bytesReceived, out receivedFlags, out ipPacketInformation, out errorCode)) { flags = receivedFlags; return errorCode; } @event = new ManualResetEventSlim(false, 0); operation = new ReceiveMessageFromOperation { Event = @event, Buffer = buffer, Offset = offset, Count = count, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, IsIPv4 = isIPv4, IsIPv6 = isIPv6, }; bool isStopped; while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { socketAddressLen = operation.SocketAddressLen; flags = operation.ReceivedFlags; ipPacketInformation = operation.IPPacketInformation; bytesReceived = operation.BytesTransferred; return SocketError.Interrupted; } if (operation.TryComplete(this)) { socketAddressLen = operation.SocketAddressLen; flags = operation.ReceivedFlags; ipPacketInformation = operation.IPPacketInformation; bytesReceived = operation.BytesTransferred; return operation.ErrorCode; } } } bool signaled = operation.Wait(timeout); socketAddressLen = operation.SocketAddressLen; flags = operation.ReceivedFlags; ipPacketInformation = operation.IPPacketInformation; bytesReceived = operation.BytesTransferred; return signaled ? operation.ErrorCode : SocketError.TimedOut; } finally { if (@event != null) @event.Dispose(); } } public SocketError ReceiveMessageFromAsync(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out int bytesReceived, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError> callback) { SetNonBlocking(); lock (_receiveQueue.QueueLock) { SocketError errorCode; if (_receiveQueue.IsEmpty && SocketPal.TryCompleteReceiveMessageFrom(_socket, buffer, offset, count, flags, socketAddress, ref socketAddressLen, isIPv4, isIPv6, out bytesReceived, out receivedFlags, out ipPacketInformation, out errorCode)) { // Synchronous success or failure return errorCode; } var operation = new ReceiveMessageFromOperation { Callback = callback, Buffer = buffer, Offset = offset, Count = count, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, IsIPv4 = isIPv4, IsIPv6 = isIPv6, }; bool isStopped; while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { ipPacketInformation = default(IPPacketInformation); bytesReceived = 0; receivedFlags = SocketFlags.None; return SocketError.OperationAborted; } if (operation.TryComplete(this)) { socketAddressLen = operation.SocketAddressLen; receivedFlags = operation.ReceivedFlags; ipPacketInformation = operation.IPPacketInformation; bytesReceived = operation.BytesTransferred; return operation.ErrorCode; } } ipPacketInformation = default(IPPacketInformation); bytesReceived = 0; receivedFlags = SocketFlags.None; return SocketError.IOPending; } } public SocketError Send(byte[] buffer, int offset, int count, SocketFlags flags, int timeout, out int bytesSent) { return SendTo(buffer, offset, count, flags, null, 0, timeout, out bytesSent); } public SocketError SendAsync(byte[] buffer, int offset, int count, SocketFlags flags, out int bytesSent, Action<int, byte[], int, SocketFlags, SocketError> callback) { int socketAddressLen = 0; return SendToAsync(buffer, offset, count, flags, null, ref socketAddressLen, out bytesSent, callback); } public SocketError SendTo(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent) { Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); ManualResetEventSlim @event = null; try { SendOperation operation; lock (_sendQueue.QueueLock) { bytesSent = 0; SocketError errorCode; if (_sendQueue.IsEmpty && SocketPal.TryCompleteSendTo(_socket, buffer, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode)) { return errorCode; } @event = new ManualResetEventSlim(false, 0); operation = new SendOperation { Event = @event, Buffer = buffer, Offset = offset, Count = count, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, BytesTransferred = bytesSent }; bool isStopped; while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { bytesSent = operation.BytesTransferred; return SocketError.Interrupted; } if (operation.TryComplete(this)) { bytesSent = operation.BytesTransferred; return operation.ErrorCode; } } } bool signaled = operation.Wait(timeout); bytesSent = operation.BytesTransferred; return signaled ? operation.ErrorCode : SocketError.TimedOut; } finally { if (@event != null) @event.Dispose(); } } public SocketError SendToAsync(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesSent, Action<int, byte[], int, SocketFlags, SocketError> callback) { SetNonBlocking(); lock (_sendQueue.QueueLock) { bytesSent = 0; SocketError errorCode; if (_sendQueue.IsEmpty && SocketPal.TryCompleteSendTo(_socket, buffer, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode)) { // Synchronous success or failure return errorCode; } var operation = new SendOperation { Callback = callback, Buffer = buffer, Offset = offset, Count = count, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, BytesTransferred = bytesSent }; bool isStopped; while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { return SocketError.OperationAborted; } if (operation.TryComplete(this)) { bytesSent = operation.BytesTransferred; return operation.ErrorCode; } } return SocketError.IOPending; } } public SocketError Send(IList<ArraySegment<byte>> buffers, SocketFlags flags, int timeout, out int bytesSent) { return SendTo(buffers, flags, null, 0, timeout, out bytesSent); } public SocketError SendAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, out int bytesSent, Action<int, byte[], int, SocketFlags, SocketError> callback) { int socketAddressLen = 0; return SendToAsync(buffers, flags, null, ref socketAddressLen, out bytesSent, callback); } public SocketError SendTo(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent) { Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); ManualResetEventSlim @event = null; try { SendOperation operation; lock (_sendQueue.QueueLock) { bytesSent = 0; int bufferIndex = 0; int offset = 0; SocketError errorCode; if (_sendQueue.IsEmpty && SocketPal.TryCompleteSendTo(_socket, buffers, ref bufferIndex, ref offset, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode)) { return errorCode; } @event = new ManualResetEventSlim(false, 0); operation = new SendOperation { Event = @event, Buffers = buffers, BufferIndex = bufferIndex, Offset = offset, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, BytesTransferred = bytesSent }; bool isStopped; while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { bytesSent = operation.BytesTransferred; return SocketError.Interrupted; } if (operation.TryComplete(this)) { bytesSent = operation.BytesTransferred; return operation.ErrorCode; } } } bool signaled = operation.Wait(timeout); bytesSent = operation.BytesTransferred; return signaled ? operation.ErrorCode : SocketError.TimedOut; } finally { if (@event != null) @event.Dispose(); } } public SocketError SendToAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesSent, Action<int, byte[], int, SocketFlags, SocketError> callback) { SetNonBlocking(); lock (_sendQueue.QueueLock) { bytesSent = 0; int bufferIndex = 0; int offset = 0; SocketError errorCode; if (_sendQueue.IsEmpty && SocketPal.TryCompleteSendTo(_socket, buffers, ref bufferIndex, ref offset, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode)) { // Synchronous success or failure return errorCode; } var operation = new SendOperation { Callback = callback, Buffers = buffers, BufferIndex = bufferIndex, Offset = offset, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, }; bool isStopped; while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { return SocketError.OperationAborted; } if (operation.TryComplete(this)) { bytesSent = operation.BytesTransferred; return operation.ErrorCode; } } return SocketError.IOPending; } } public SocketError SendFile(SafeFileHandle fileHandle, long offset, long count, int timeout, out long bytesSent) { Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); ManualResetEventSlim @event = null; try { SendFileOperation operation; lock (_sendQueue.QueueLock) { bytesSent = 0; SocketError errorCode; if (_sendQueue.IsEmpty && SocketPal.TryCompleteSendFile(_socket, fileHandle, ref offset, ref count, ref bytesSent, out errorCode)) { return errorCode; } @event = new ManualResetEventSlim(false, 0); operation = new SendFileOperation { Event = @event, FileHandle = fileHandle, Offset = offset, Count = count, BytesTransferred = bytesSent }; bool isStopped; while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { bytesSent = operation.BytesTransferred; return SocketError.Interrupted; } if (operation.TryComplete(this)) { bytesSent = operation.BytesTransferred; return operation.ErrorCode; } } } bool signaled = operation.Wait(timeout); bytesSent = operation.BytesTransferred; return signaled ? operation.ErrorCode : SocketError.TimedOut; } finally { if (@event != null) @event.Dispose(); } } public SocketError SendFileAsync(SafeFileHandle fileHandle, long offset, long count, out long bytesSent, Action<long, SocketError> callback) { SetNonBlocking(); lock (_sendQueue.QueueLock) { bytesSent = 0; SocketError errorCode; if (_sendQueue.IsEmpty && SocketPal.TryCompleteSendFile(_socket, fileHandle, ref offset, ref count, ref bytesSent, out errorCode)) { // Synchronous success or failure return errorCode; } var operation = new SendFileOperation { Callback = callback, FileHandle = fileHandle, Offset = offset, Count = count, BytesTransferred = bytesSent }; bool isStopped; while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { return SocketError.OperationAborted; } if (operation.TryComplete(this)) { bytesSent = operation.BytesTransferred; return operation.ErrorCode; } } return SocketError.IOPending; } } public unsafe void HandleEvents(Interop.Sys.SocketEvents events) { if ((events & Interop.Sys.SocketEvents.Error) != 0) { // Set the Read and Write flags as well; the processing for these events // will pick up the error. events |= Interop.Sys.SocketEvents.Read | Interop.Sys.SocketEvents.Write; } if ((events & Interop.Sys.SocketEvents.Read) != 0) { _receiveQueue.Complete(this); } if ((events & Interop.Sys.SocketEvents.Write) != 0) { _sendQueue.Complete(this); } } } }
namespace JoinerSplitter { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.Serialization.Json; using System.Threading.Tasks; using Newtonsoft.Json; using Properties; public class AppModel : INotifyPropertyChanged { private static readonly IList<EncodingPreset> DefaultEncoderPresets = Settings.Default.DefaultEncodingPresets .Cast<string>().SelectGroups(3).Select( i => new EncodingPreset { Name = i[0], OutputEncoding = i[1], ComplexFilter = i[2] }).ToList(); private VideoFile currentFile; private Job currentJob; public AppModel() { currentJob = new Job(); } public event PropertyChangedEventHandler PropertyChanged; public IEnumerable<EncodingPreset> ComboBoxEncoderPresets => CurrentJob.OriginalEncoding != null ? new[] { CurrentJob.OriginalEncoding }.Concat(EncoderPresets) : EncoderPresets; public VideoFile CurrentFile { get => currentFile; set { currentFile = value; OnPropertyChanged(nameof(CurrentFile)); OnPropertyChanged(nameof(HasCurrentFile)); } } public Uri CurrentFileUri => CurrentFile?.FileUri ?? new Uri(string.Empty); public Job CurrentJob { get => currentJob; set { currentJob = value; OnPropertyChanged(nameof(CurrentJob)); } } public ObservableCollection<EncodingPreset> EncoderPresets { get; set; } = new ObservableCollection<EncodingPreset>(Settings.Default?.EncodingPresets1 ?? DefaultEncoderPresets); public bool HasCurrentFile => CurrentFile != null; public string OutputFolder => SelectedOutputFolder ?? CurrentJob.OutputFolder; public string SelectedOutputFolder { get => Settings.Default?.OutputFolder; set { Settings.Default.OutputFolder = value; SaveSettings(); OnPropertyChanged(nameof(OutputFolder)); } } public async Task AddFiles(string[] files) { await AddFiles(files, null, -1); } public async Task AddFiles(string[] files, VideoFile before, int groupIndex) { var error = new List<string>(); var lastFile = CurrentJob.Files.LastOrDefault(); var beforeIndex = before != null ? CurrentJob.Files.IndexOf(before) : -1; if (groupIndex < 0) { groupIndex = lastFile?.GroupIndex ?? 0; } foreach (var filepath in files) { try { var file = await CreateVideoFileObject(filepath); file.GroupIndex = groupIndex; if (before == null) { CurrentJob.Files.Add(file); } else { CurrentJob.Files.Insert(beforeIndex++, file); } } catch (Exception) { error.Add(Path.GetFileName(filepath)); } } if (error.Any()) { if (files.Length == error.Count) { throw new InvalidOperationException("None of files can be exported by ffmpeg:\r\n" + string.Join("\r\n", error.Select(s => " " + s))); } throw new InvalidOperationException("Some files can not be exported by ffmpeg:\r\n" + string.Join("\r\n", error.Select(s => " " + s))); } if (string.IsNullOrEmpty(CurrentJob.OutputName) && (files.Length > 0)) { CurrentJob.OutputName = Path.GetFileNameWithoutExtension(files[0]) + ".out" + Path.GetExtension(files[0]); } } public void DeleteVideos(IList selectedItems) { var jobFiles = CurrentJob.Files; foreach (var file in selectedItems.Cast<VideoFile>().ToList()) { jobFiles.Remove(file); } NormalizeGroups(); } public void MoveFiles(VideoFile[] files, VideoFile before, int groupIndex) { if (files == null) { throw new ArgumentNullException(nameof(files)); } var jobFiles = CurrentJob.Files; if (before != null) { var ind = jobFiles.IndexOf(before); while ((before != null) && files.Contains(before)) { ind++; before = ind < jobFiles.Count ? jobFiles[ind] : null; } } foreach (var file in files) { jobFiles.Remove(file); } var insertIndex = before != null ? jobFiles.IndexOf(before) : jobFiles.Count; var lastFile = jobFiles.LastOrDefault(); if (groupIndex < 0) { groupIndex = lastFile?.GroupIndex ?? 0; } foreach (var file in files) { jobFiles.Insert(insertIndex++, file); file.GroupIndex = groupIndex; } NormalizeGroups(); } public void MoveVideosUp(IList selectedItems) { var jobFiles = CurrentJob.Files; var selected = selectedItems.Cast<VideoFile>().OrderBy(f => jobFiles.IndexOf(f)).ToList(); foreach (var file in selected) { var fileindex = jobFiles.IndexOf(file); if ((fileindex > 0) && !selected.Contains(jobFiles[fileindex - 1])) { if (jobFiles[fileindex - 1].GroupIndex < file.GroupIndex) { file.GroupIndex = jobFiles[fileindex - 1].GroupIndex; } else { jobFiles.Move(fileindex, fileindex - 1); } } } NormalizeGroups(); } public async Task OpenJob(string path) { CurrentJob = await Task.Run( () => { Environment.CurrentDirectory = Path.GetDirectoryName(path) ?? Environment.CurrentDirectory; var result = JsonConvert.DeserializeObject<Job>(File.ReadAllText(path)); result.JobFilePath = path; if (result.Encoding != null) { result.OriginalEncoding = new EncodingPreset { Name = result.Encoding.Name, OutputEncoding = result.Encoding.OutputEncoding, ComplexFilter = result.Encoding.ComplexFilter, DisplayName = $"{result.Encoding.Name.Trim()} (original)", }; result.Encoding = result.OriginalEncoding; result.Changed = false; } return result; }); OnPropertyChanged(nameof(ComboBoxEncoderPresets)); } public void SaveEncoders() { Settings.Default.EncodingPresets1 = new EncodingPresetsCollection(EncoderPresets); OnPropertyChanged(nameof(ComboBoxEncoderPresets)); SaveSettings(); } public async Task SaveJob(string path) { try { if (CurrentJob == null || !CurrentJob.Files.Any()) { throw new Exception("Wrong job"); } var tmpPath = path + ".tmp"; string contents = JsonConvert.SerializeObject(CurrentJob); File.WriteAllText(tmpPath, contents); var saveFileInfo = new FileInfo(tmpPath); if (saveFileInfo.Length == 0) { throw new Exception("Wrong job length"); } if (File.Exists(path)) { File.Delete(path); } File.Move(tmpPath, path); CurrentJob.JobFilePath = path; CurrentJob.Changed = false; } catch (Exception ex) { Debug.Fail(ex.Message); } } public void SaveSettings() { Settings.Default.Save(); } public void SplitCurrentVideo(double currentTime) { var currentIndex = CurrentJob.Files.IndexOf(CurrentFile); var splitTime = CurrentFile.KeyFrames?.Where(f => f > currentTime).DefaultIfEmpty(CurrentFile.Duration).First() ?? currentTime; if ((splitTime <= CurrentFile.Start) || (splitTime >= CurrentFile.End)) { return; } var newFile = new VideoFile(CurrentFile) { Start = splitTime, GroupIndex = CurrentFile.GroupIndex }; CurrentFile.End = splitTime; CurrentJob.Files.Insert(currentIndex + 1, newFile); } public void SplitGroup() { var currentIndex = CurrentJob.Files.IndexOf(CurrentFile); if (currentIndex == 0) { return; } for (var i = currentIndex; i < CurrentJob.Files.Count; i++) { CurrentJob.Files[i].GroupIndex += 1; } NormalizeGroups(); } internal void DuplicateVideos(IList selectedItems) { var selected = selectedItems.Cast<VideoFile>().ToList(); var insertIndex = selected.Select(v => CurrentJob.Files.IndexOf(v)).Max() + 1; foreach (var file in selected) { CurrentJob.Files.Insert(insertIndex++, new VideoFile(file)); } NormalizeGroups(); } internal void MoveVideosDown(IList selectedItems) { var jobFiles = CurrentJob.Files; var selected = selectedItems.Cast<VideoFile>().OrderBy(f => jobFiles.IndexOf(f)).ToList(); for (var i = selected.Count - 1; i >= 0; i--) { var file = selected[i]; var fileindex = jobFiles.IndexOf(file); if ((fileindex < jobFiles.Count - 1) && !selected.Contains(jobFiles[fileindex + 1])) { if (jobFiles[fileindex + 1].GroupIndex > file.GroupIndex) { file.GroupIndex = jobFiles[fileindex + 1].GroupIndex; } else { jobFiles.Move(fileindex, fileindex + 1); } } } NormalizeGroups(); } private async Task<VideoFile> CreateVideoFileObject(string path) { var duration = await FFMpeg.Instance.GetDuration(path); return new VideoFile(path, duration); } private void NormalizeGroups() { var jobFiles = CurrentJob.Files; if (jobFiles.Count == 0) { return; } var curindex = 0; var lastIndex = jobFiles[0].GroupIndex; foreach (var file in jobFiles) { if (file.GroupIndex != lastIndex) { lastIndex = file.GroupIndex; curindex++; } file.GroupIndex = curindex; } } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
using System; using System.Collections.Generic; using Vim25Api; using AppUtil; namespace DVSCreate { ///<summary> ///This sample is used to create DVS or add the port group ///</summary> ///<param name="itemType">Required: Type of the Opeartion to be performed</param> ///<param name="dcname">Required: Datacenter name</param> ///<param name="dvsname">Required: Name of dvs switch to add </param> ///<param name="dvsdesc">Optional: Description of dvs switch to add</param> ///<param name="dvsversion">Optional: Distributed Virtual Switch version</param> /// either 4.0, 4.1.0, 5.0.0 or 5.1.0 ///<param name="numports">Optional :Number of ports in the portgroup</param> ///<param name="portgroupname">Optional: Name of the port group </param> ///Create DVS ///--url [webserviceurl] ///--username [username] --password [password] --itemType [itemType] ///--dvsname [dvsname] --dcname [dcname] --dvsdesc [dvsdesc] --dvsversion [dvsversion] /// Add a port group ///--url [webserviceurl] ///--username [username] --password [password] --itemType [itemType] ///--dvsname [dvsname] /// --numports[numports] --portgroupname[portgroupname] ///</remarks> public class DVSCreate { private static AppUtil.AppUtil cb = null; private String GetItemType() { return cb.get_option("itemType"); } /// <summary> /// This method is used to create DVS or add port group according to user choice. /// </summary> private void DoCreate() { string dcname = cb.get_option("dcname"); string dvsname = cb.get_option("dvsname"); string dvsdesc = cb.get_option("dvsdesc"); string dvsversion = cb.get_option("dvsversion"); int numPorts = 0; if (cb.get_option("numports") != null) { numPorts = int.Parse(cb.get_option("numports")); } string portGroupName = cb.get_option("portgroupname"); try { if (GetItemType().Equals("createdvs")) { ManagedObjectReference dcmor = cb._svcUtil.getEntityByName("Datacenter", dcname); if (dcmor != null) { ManagedObjectReference networkmor = cb.getServiceUtil().GetMoRefProp(dcmor, "networkFolder"); DVSCreateSpec dvscreatespec = new DVSCreateSpec(); DistributedVirtualSwitchProductSpec dvsProdSpec = GetDVSProductSpec(dvsversion); dvscreatespec.productInfo = dvsProdSpec; DistributedVirtualSwitchHostProductSpec[] dvsHostProdSpec = cb.getConnection()._service.QueryDvsCompatibleHostSpec(cb.getConnection(). _sic.dvSwitchManager, dvsProdSpec); DVSCapability dvsCapability = new DVSCapability(); dvsCapability.compatibleHostComponentProductInfo = dvsHostProdSpec; dvscreatespec.capability = dvsCapability; DVSConfigSpec configSpec = GetConfigSpec(dvsname, dvsdesc); dvscreatespec.configSpec = configSpec; ManagedObjectReference taskmor = cb.getConnection()._service.CreateDVS_Task(networkmor, dvscreatespec); if (taskmor != null) { String status = cb.getServiceUtil().WaitForTask( taskmor); if (status.Equals("sucess")) { Console.WriteLine("Sucessfully created::" + dvsname); } else { Console.WriteLine("dvs switch" + dvsname + " not created::"); throw new Exception(status); } } } else { throw new Exception("Datacenter" + dcname + "not found"); } } else if (GetItemType().Equals("addportgroup")) { ManagedObjectReference dvsMor = cb._svcUtil.getEntityByName("VmwareDistributedVirtualSwitch", dvsname); if (dvsMor != null) { DVPortgroupConfigSpec portGroupConfigSpec = new DVPortgroupConfigSpec(); portGroupConfigSpec.name = portGroupName; portGroupConfigSpec.numPorts = numPorts; portGroupConfigSpec.type = "earlyBinding"; List<DVPortgroupConfigSpec> lst = new List<DVPortgroupConfigSpec>(); lst.Add(portGroupConfigSpec); ManagedObjectReference taskmor = cb.getConnection()._service.AddDVPortgroup_Task(dvsMor, lst.ToArray()); if (taskmor != null) { String status = cb.getServiceUtil().WaitForTask( taskmor); if (status.Equals("sucess")) { Console.WriteLine("Sucessfully added port group :" + portGroupName); } else { Console.WriteLine("port group" + portGroupName + " not added:"); throw new Exception(status); } } } else { throw new Exception("DvsSwitch " + dvsname + " not found"); } } else { Console.WriteLine("Unknown Type. Allowed types are:"); Console.WriteLine(" createdvs"); Console.WriteLine(" addportgroup"); } } catch (Exception e) { throw new Exception(e.Message); } } private static DVSConfigSpec GetConfigSpec(string dvsName, string dvsDesc) { DVSConfigSpec dvsConfigSpec = new DVSConfigSpec(); dvsConfigSpec.name = dvsName; if (dvsDesc != null) { dvsConfigSpec.description = dvsDesc; } DVSPolicy dvsPolicy = new DVSPolicy(); dvsPolicy.autoPreInstallAllowed = true; dvsPolicy.autoUpgradeAllowed = true; dvsPolicy.partialUpgradeAllowed = true; return dvsConfigSpec; } private static DistributedVirtualSwitchProductSpec GetDVSProductSpec(string version) { DistributedVirtualSwitchProductSpec[] dvsProdSpec = cb.getConnection()._service. QueryAvailableDvsSpec(cb.getConnection()._sic.dvSwitchManager); DistributedVirtualSwitchProductSpec dvsSpec = null; if (version != null) { for (int i = 0; i < dvsProdSpec.Length; i++) { if (version.Equals(dvsProdSpec[i].version)) { dvsSpec = dvsProdSpec[i]; } } if (dvsSpec == null) { Console.WriteLine("Dvs version" + version + "not supported"); } } else { dvsSpec = dvsProdSpec[dvsProdSpec.Length - 1]; } return dvsSpec; } private Boolean customValidation() { Boolean flag = true; if (cb.option_is_set("dvsversion")) { String dvsVersion = cb.get_option("dvsversion"); if (!dvsVersion.Equals("4.0") && !dvsVersion.Equals("4.1.0") && !dvsVersion.Equals("5.0.0") && !dvsVersion.Equals("5.1.0")) { Console.WriteLine("Must specify dvs version as 4.0 or 4.1.0\n" + "5.0.0 or 5.1.0 "); flag = false; } } return flag; } private static OptionSpec[] constructOptions() { OptionSpec[] useroptions = new OptionSpec[7]; useroptions[0] = new OptionSpec("itemType", "String", 1 , "createdvs|addportgroup" , null); useroptions[1] = new OptionSpec("dcname", "String", 1, "Datacenter name", null); useroptions[2] = new OptionSpec("dvsname", "String", 1, "Name of dvs switch to add ", null); useroptions[3] = new OptionSpec("dvsdesc", "String", 0, "Description of dvs switch to add", null); useroptions[4] = new OptionSpec("dvsversion", "String", 0, "Distributed Virtual Switch version" + "either 4.0, 4.1.0, 5.0.0 or 5.1.0", null); useroptions[5] = new OptionSpec("numports", "String", 0, "Required for addportgroup:Number of ports in the portgroup", null); useroptions[6] = new OptionSpec("portgroupname", "String", 0, "Required for addportgroup: Name of the port group", null); return useroptions; } public static void Main(String[] args) { DVSCreate app = new DVSCreate(); cb = AppUtil.AppUtil.initialize("DVSCreate", DVSCreate.constructOptions(), args); Boolean valid = app.customValidation(); if (valid) { try { cb.connect(); app.DoCreate(); cb.disConnect(); } catch (Exception e) { Console.WriteLine(e.Message); } } Console.WriteLine("Please enter to exit: "); Console.Read(); } } }
#region License /* SDL2# - C# Wrapper for SDL2 * * Copyright (c) 2013-2014 Ethan Lee. * * 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. * * Ethan "flibitijibibo" Lee <flibitijibibo@flibitijibibo.com> * */ #endregion #region Using Statements using System; using System.Runtime.InteropServices; #endregion namespace SDL2 { public static class SDL_ttf { #region SDL2# Variables /* Used by DllImport to load the native library. */ private const string nativeLibName = "SDL2_ttf.dll"; #endregion #region SDL_ttf.h /* Similar to the headers, this is the version we're expecting to be * running with. You will likely want to check this somewhere in your * program! */ public const int SDL_TTF_MAJOR_VERSION = 2; public const int SDL_TTF_MINOR_VERSION = 0; public const int SDL_TTF_PATCHLEVEL = 12; public const int UNICODE_BOM_NATIVE = 0xFEFF; public const int UNICODE_BOM_SWAPPED = 0xFFFE; public const int TTF_STYLE_NORMAL = 0x00; public const int TTF_STYLE_BOLD = 0x01; public const int TTF_STYLE_ITALIC = 0x02; public const int TTF_STYLE_UNDERLINE = 0x04; public const int TTF_STYLE_STRIKETHROUGH = 0x08; public const int TTF_HINTING_NORMAL = 0; public const int TTF_HINTING_LIGHT = 1; public const int TTF_HINTING_MONO = 2; public const int TTF_HINTING_NONE = 3; public static void SDL_TTF_VERSION(out SDL.SDL_version X) { X.major = SDL_TTF_MAJOR_VERSION; X.minor = SDL_TTF_MINOR_VERSION; X.patch = SDL_TTF_PATCHLEVEL; } [DllImport(nativeLibName, EntryPoint = "TTF_LinkedVersion", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr INTERNAL_TTF_LinkedVersion(); public static SDL.SDL_version TTF_LinkedVersion() { SDL.SDL_version result; IntPtr result_ptr = INTERNAL_TTF_LinkedVersion(); result = (SDL.SDL_version) Marshal.PtrToStructure( result_ptr, typeof(SDL.SDL_version) ); return result; } [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern void TTF_ByteSwappedUNICODE(int swapped); [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_Init(); /* IntPtr refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_OpenFont( [In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))] string file, int ptsize ); /* src refers to an SDL_RWops*, IntPtr to a TTF_Font* */ /* THIS IS A PUBLIC RWops FUNCTION! */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_OpenFontRW( IntPtr src, int freesrc, int ptsize ); /* IntPtr refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_OpenFontIndex( [In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))] string file, int ptsize, long index ); /* src refers to an SDL_RWops*, IntPtr to a TTF_Font* */ /* THIS IS A PUBLIC RWops FUNCTION! */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_OpenFontIndexRW( IntPtr src, int freesrc, int ptsize, long index ); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_GetFontStyle(IntPtr font); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern void TTF_SetFontStyle(IntPtr font, int style); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_GetFontOutline(IntPtr font); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern void TTF_SetFontOutline(IntPtr font, int outline); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_GetFontHinting(IntPtr font); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern void TTF_SetFontHinting(IntPtr font, int hinting); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_FontHeight(IntPtr font); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_FontAscent(IntPtr font); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_FontDescent(IntPtr font); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_FontLineSkip(IntPtr font); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_GetFontKerning(IntPtr font); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern void TTF_SetFontKerning(IntPtr font, int allowed); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern long TTF_FontFaces(IntPtr font); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_FontFaceIsFixedWidth(IntPtr font); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] [return : MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler), MarshalCookie = LPUtf8StrMarshaler.LeaveAllocated)] public static extern string TTF_FontFaceFamilyName( IntPtr font ); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] [return : MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler), MarshalCookie = LPUtf8StrMarshaler.LeaveAllocated)] public static extern string TTF_FontFaceStyleName( IntPtr font ); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_GlyphIsProvided(IntPtr font, ushort ch); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_GlyphMetrics( IntPtr font, ushort ch, out int minx, out int maxx, out int miny, out int maxy, out int advance ); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_SizeText( IntPtr font, [In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))] string text, out int w, out int h ); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_SizeUTF8( IntPtr font, [In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))] string text, out int w, out int h ); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_SizeUNICODE( IntPtr font, [In()] [MarshalAs(UnmanagedType.LPWStr)] string text, out int w, out int h ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderText_Solid( IntPtr font, [In()] [MarshalAs(UnmanagedType.LPStr)] string text, SDL.SDL_Color fg ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderUTF8_Solid( IntPtr font, [In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))] string text, SDL.SDL_Color fg ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderUNICODE_Solid( IntPtr font, [In()] [MarshalAs(UnmanagedType.LPWStr)] string text, SDL.SDL_Color fg ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderGlyph_Solid( IntPtr font, ushort ch, SDL.SDL_Color fg ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderText_Shaded( IntPtr font, [In()] [MarshalAs(UnmanagedType.LPStr)] string text, SDL.SDL_Color fg, SDL.SDL_Color bg ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderUTF8_Shaded( IntPtr font, [In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))] string text, SDL.SDL_Color fg, SDL.SDL_Color bg ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderUNICODE_Shaded( IntPtr font, [In()] [MarshalAs(UnmanagedType.LPWStr)] string text, SDL.SDL_Color fg, SDL.SDL_Color bg ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderGlyph_Shaded( IntPtr font, ushort ch, SDL.SDL_Color fg, SDL.SDL_Color bg ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderText_Blended( IntPtr font, [In()] [MarshalAs(UnmanagedType.LPStr)] string text, SDL.SDL_Color fg ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderUTF8_Blended( IntPtr font, [In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))] string text, SDL.SDL_Color fg ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderUNICODE_Blended( IntPtr font, [In()] [MarshalAs(UnmanagedType.LPWStr)] string text, SDL.SDL_Color fg ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderText_Blended_Wrapped( IntPtr font, [In()] [MarshalAs(UnmanagedType.LPStr)] string text, SDL.SDL_Color fg, uint wrapped ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderUTF8_Blended_Wrapped( IntPtr font, [In()] [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(LPUtf8StrMarshaler))] string text, SDL.SDL_Color fg, uint wrapped ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderUNICODE_Blended_Wrapped( IntPtr font, [In()] [MarshalAs(UnmanagedType.LPWStr)] string text, SDL.SDL_Color fg, uint wrapped ); /* IntPtr refers to an SDL_Surface*, font to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr TTF_RenderGlyph_Blended( IntPtr font, ushort ch, SDL.SDL_Color fg ); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern void TTF_CloseFont(IntPtr font); [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern void TTF_Quit(); [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int TTF_WasInit(); /* font refers to a TTF_Font* */ [DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)] public static extern int SDL_GetFontKerningSize( IntPtr font, int prev_index, int index ); #endregion } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; using Microsoft.PythonTools.Infrastructure; using Microsoft.VisualStudio.Shell; using Microsoft.Win32; namespace Microsoft.PythonTools.Interpreter { [InterpreterFactoryId(FactoryProviderName)] [Export(typeof(IPythonInterpreterFactoryProvider))] [Export(typeof(CPythonInterpreterFactoryProvider))] [PartCreationPolicy(CreationPolicy.Shared)] class CPythonInterpreterFactoryProvider : IPythonInterpreterFactoryProvider, IDisposable { private readonly IServiceProvider _site; private readonly Dictionary<string, PythonInterpreterInformation> _factories = new Dictionary<string, PythonInterpreterInformation>(); const string PythonPath = "Software\\Python"; internal const string FactoryProviderName = CPythonInterpreterFactoryConstants.FactoryProviderName; private readonly bool _watchRegistry; private readonly HashSet<object> _registryTags; private int _ignoreNotifications; private bool _initialized; private static readonly Version[] ExcludedVersions = new[] { new Version(2, 5), new Version(3, 0) }; [ImportingConstructor] public CPythonInterpreterFactoryProvider( [Import(typeof(SVsServiceProvider), AllowDefault = true)] IServiceProvider site = null, [Import("Microsoft.VisualStudioTools.MockVsTests.IsMockVs", AllowDefault = true)] object isMockVs = null ) : this(site, isMockVs == null) { } public CPythonInterpreterFactoryProvider(IServiceProvider site, bool watchRegistry) { _site = site; _watchRegistry = watchRegistry; _registryTags = _watchRegistry ? new HashSet<object>() : null; } protected void Dispose(bool disposing) { foreach(var tag in _registryTags.MaybeEnumerate()) { RegistryWatcher.Instance.Remove(tag); } _registryTags?.Clear(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~CPythonInterpreterFactoryProvider() { Dispose(false); } private void EnsureInitialized() { lock (this) { if (!_initialized) { _initialized = true; DiscoverInterpreterFactories(); if (_watchRegistry) { _registryTags.Add(StartWatching(RegistryHive.CurrentUser, RegistryView.Default)); _registryTags.Add(StartWatching(RegistryHive.LocalMachine, RegistryView.Registry32)); if (Environment.Is64BitOperatingSystem) { _registryTags.Add(StartWatching(RegistryHive.LocalMachine, RegistryView.Registry64)); } } } } } private object StartWatching(RegistryHive hive, RegistryView view, int retries = 5) { var tag = RegistryWatcher.Instance.TryAdd( hive, view, PythonPath, Registry_PythonPath_Changed, recursive: true, notifyValueChange: true, notifyKeyChange: true ) ?? RegistryWatcher.Instance.TryAdd( hive, view, "Software", Registry_Software_Changed, recursive: false, notifyValueChange: false, notifyKeyChange: true ); if (tag == null && retries > 0) { Trace.TraceWarning("Failed to watch registry. Retrying {0} more times", retries); Thread.Sleep(100); StartWatching(hive, view, retries - 1); } else if (tag == null) { Trace.TraceError("Failed to watch registry"); } return tag; } #region Registry Watching private static bool Exists(RegistryChangedEventArgs e) { using (var root = RegistryKey.OpenBaseKey(e.Hive, e.View)) using (var key = root.OpenSubKey(e.Key)) { return key != null; } } private void Registry_PythonPath_Changed(object sender, RegistryChangedEventArgs e) { if (!Exists(e)) { // Python key no longer exists, so go back to watching // Software. e.CancelWatcher = true; _registryTags.Remove(e.Tag); _registryTags.Add(StartWatching(e.Hive, e.View)); } else { DiscoverInterpreterFactories(); } } private void Registry_Software_Changed(object sender, RegistryChangedEventArgs e) { Registry_PythonPath_Changed(sender, e); if (e.CancelWatcher) { // Python key no longer exists, we're still watching Software return; } if (RegistryWatcher.Instance.TryAdd( e.Hive, e.View, PythonPath, Registry_PythonPath_Changed, recursive: true, notifyValueChange: true, notifyKeyChange: true ) != null) { // Python exists, we no longer need to watch Software e.CancelWatcher = true; } } #endregion public static InterpreterArchitecture ArchitectureFromExe(string path) { try { switch (NativeMethods.GetBinaryType(path)) { case ProcessorArchitecture.X86: return InterpreterArchitecture.x86; case ProcessorArchitecture.Amd64: return InterpreterArchitecture.x64; } } catch (Exception ex) { Debug.Fail(ex.ToUnhandledExceptionMessage(typeof(InterpreterArchitecture))); } return InterpreterArchitecture.Unknown; } public static Version VersionFromSysVersionInfo(string interpreterPath) { Version version = null; using (var output = ProcessOutput.RunHiddenAndCapture( interpreterPath, "-c", "import sys; print('%s.%s' % (sys.version_info[0], sys.version_info[1]))" )) { output.Wait(); if (output.ExitCode == 0) { var versionName = output.StandardOutputLines.FirstOrDefault() ?? ""; if (!Version.TryParse(versionName, out version)) { version = null; } } } return version; } internal void DiscoverInterpreterFactories() { if (Volatile.Read(ref _ignoreNotifications) > 0) { return; } // Discover the available interpreters... bool anyChanged = false; PythonRegistrySearch search = null; Dictionary<string, PythonInterpreterInformation> machineFactories = null; try { search = new PythonRegistrySearch(); using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default)) using (var root = baseKey.OpenSubKey(PythonPath)) { search.Search( root, Environment.Is64BitOperatingSystem ? InterpreterArchitecture.Unknown : InterpreterArchitecture.x86 ); } machineFactories = new Dictionary<string, PythonInterpreterInformation>(); using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) using (var root = baseKey.OpenSubKey(PythonPath)) { search.Search( root, InterpreterArchitecture.x86 ); } if (Environment.Is64BitOperatingSystem) { using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) using (var root = baseKey.OpenSubKey(PythonPath)) { search.Search( root, InterpreterArchitecture.x64 ); } } } catch (ObjectDisposedException) { // We are aborting, so silently return with no results. return; } var found = search.Interpreters .Where(i => !ExcludedVersions.Contains(i.Configuration.Version)) .ToList(); var uniqueIds = new HashSet<string>(found.Select(i => i.Configuration.Id)); // Then update our cached state with the lock held. lock (this) { foreach (var info in found) { PythonInterpreterInformation existingInfo; if (!_factories.TryGetValue(info.Configuration.Id, out existingInfo) || info.Configuration != existingInfo.Configuration) { _factories[info.Configuration.Id] = info; anyChanged = true; } } // Remove any factories we had before and no longer see... foreach (var unregistered in _factories.Keys.Except(uniqueIds).ToArray()) { _factories.Remove(unregistered); anyChanged = true; } } if (anyChanged) { OnInterpreterFactoriesChanged(); } } #region IPythonInterpreterProvider Members public IEnumerable<InterpreterConfiguration> GetInterpreterConfigurations() { EnsureInitialized(); lock (_factories) { return _factories.Values.Select(x => x.Configuration).ToArray(); } } public IPythonInterpreterFactory GetInterpreterFactory(string id) { EnsureInitialized(); PythonInterpreterInformation info; lock (_factories) { _factories.TryGetValue(id, out info); } return info?.GetOrCreateFactory(CreateFactory); } private IPythonInterpreterFactory CreateFactory(PythonInterpreterInformation info) { return InterpreterFactoryCreator.CreateInterpreterFactory( info.Configuration, new InterpreterFactoryCreationOptions { WatchFileSystem = true, } ); } private EventHandler _interpFactoriesChanged; public event EventHandler InterpreterFactoriesChanged { add { EnsureInitialized(); _interpFactoriesChanged += value; } remove { _interpFactoriesChanged -= value; } } private void OnInterpreterFactoriesChanged() { _interpFactoriesChanged?.Invoke(this, EventArgs.Empty); } public object GetProperty(string id, string propName) { PythonInterpreterInformation info; switch (propName) { case PythonRegistrySearch.CompanyPropertyKey: lock (_factories) { if (_factories.TryGetValue(id, out info)) { return info.Vendor; } } break; case PythonRegistrySearch.SupportUrlPropertyKey: lock (_factories) { if (_factories.TryGetValue(id, out info)) { return info.SupportUrl; } } break; case "PersistInteractive": return true; } return null; } #endregion private sealed class DiscoverOnDispose : IDisposable { private readonly CPythonInterpreterFactoryProvider _provider; public DiscoverOnDispose(CPythonInterpreterFactoryProvider provider) { _provider = provider; Interlocked.Increment(ref _provider._ignoreNotifications); } public void Dispose() { if (Interlocked.Decrement(ref _provider._ignoreNotifications) == 0) { _provider.DiscoverInterpreterFactories(); } } } internal IDisposable SuppressDiscoverFactories() { return new DiscoverOnDispose(this); } } }
#region license // Copyright (c) 2004, 2005, 2006, 2007 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using Boo.Lang.Compiler.Ast; using System.Collections.Generic; using System; using Boo.Lang.Compiler.TypeSystem.Core; namespace Boo.Lang.Compiler.TypeSystem.Generics { public class GenericsServices : AbstractCompilerComponent { public GenericsServices() : base(CompilerContext.Current) { } /// <summary> /// Constructs an entity from a generic definition and arguments, after ensuring the construction is valid. /// </summary> /// <param name="definition">The generic definition entity.</param> /// <param name="constructionNode">The node in which construction occurs.</param> /// <param name="typeArguments">The generic type arguments to substitute for generic parameters.</param> /// <returns>The constructed entity.</returns> public IEntity ConstructEntity(Node constructionNode, IEntity definition, IType[] typeArguments) { // Ensure definition is a valid entity if (definition == null || TypeSystemServices.IsError(definition)) { return TypeSystemServices.ErrorEntity; } // Ambiguous generic constructions are handled separately if (definition.IsAmbiguous()) { return ConstructAmbiguousEntity(constructionNode, (Ambiguous)definition, typeArguments); } // Check that the construction is valid if (!CheckGenericConstruction(constructionNode, definition, typeArguments, true)) { return TypeSystemServices.ErrorEntity; } return MakeGenericEntity(definition, typeArguments); } /// <summary> /// Validates and constructs generic entities out of an ambiguous generic definition entity. /// </summary> private IEntity ConstructAmbiguousEntity(Node constructionNode, Ambiguous ambiguousDefinition, IType[] typeArguments) { var checker = new GenericConstructionChecker(typeArguments, constructionNode); var matches = new List<IEntity>(ambiguousDefinition.Entities); bool reportErrors = false; foreach (Predicate<IEntity> check in checker.Checks) { matches = matches.Collect(check); if (matches.Count == 0) { Errors.Add(checker.Errors[0]); // only report first error, assuming the rest are superfluous return TypeSystemServices.ErrorEntity; } if (reportErrors) checker.ReportErrors(Errors); checker.DiscardErrors(); // We only want full error reporting once we get down to a single candidate if (matches.Count == 1) reportErrors = true; } IEntity[] constructedMatches = Array.ConvertAll<IEntity, IEntity>(matches.ToArray(), def => MakeGenericEntity(def, typeArguments)); return Entities.EntityFromList(constructedMatches); } private IEntity MakeGenericEntity(IEntity definition, IType[] typeArguments) { if (IsGenericType(definition)) return ((IType)definition).GenericInfo.ConstructType(typeArguments); if (IsGenericMethod(definition)) return ((IMethod)definition).GenericInfo.ConstructMethod(typeArguments); // Should never be reached return TypeSystemServices.ErrorEntity; } /// <summary> /// Checks whether a given set of arguments can be used to construct a generic type or method from a specified definition. /// </summary> public bool CheckGenericConstruction(IEntity definition, IType[] typeArguments) { return CheckGenericConstruction(null, definition, typeArguments, false); } /// <summary> /// Checks whether a given set of arguments can be used to construct a generic type or method from a specified definition. /// </summary> public bool CheckGenericConstruction(Node node, IEntity definition, IType[] typeArguments, bool reportErrors) { var checker = new GenericConstructionChecker(typeArguments, node); foreach (Predicate<IEntity> check in checker.Checks) { if (check(definition)) continue; if (reportErrors) checker.ReportErrors(Errors); return false; } return true; } /// <summary> /// Attempts to infer the generic parameters of a method from a set of arguments. /// </summary> /// <returns> /// An array consisting of inferred types for the method's generic arguments, /// or null if type inference failed. /// </returns> public IType[] InferMethodGenericArguments(IMethod method, ExpressionCollection arguments) { if (method.GenericInfo == null) return null; GenericParameterInferrer inferrerr = new GenericParameterInferrer(Context, method, arguments); if (inferrerr.Run()) { return inferrerr.GetInferredTypes(); } return null; } public static bool IsGenericMethod(IEntity entity) { IMethod method = entity as IMethod; return (method != null && method.GenericInfo != null); } public static bool IsGenericType(IEntity entity) { IType type = entity as IType; return (type != null && type.GenericInfo != null); } public static bool IsGenericParameter(IEntity entity) { return (entity is IGenericParameter); } public static bool AreOfSameGenerity(IMethod lhs, IMethod rhs) { return (GetMethodGenerity(lhs) == GetMethodGenerity(rhs)); } /// <summary> /// Yields the generic parameters used in a (bound) type. /// </summary> public static IEnumerable<IGenericParameter> FindGenericParameters(IType type) { IGenericParameter genericParameter = type as IGenericParameter; if (genericParameter != null) { yield return genericParameter; yield break; } if (type is IArrayType) { foreach (IGenericParameter gp in FindGenericParameters(type.ElementType)) yield return gp; yield break; } if (type.ConstructedInfo != null) { foreach (IType typeArgument in type.ConstructedInfo.GenericArguments) { foreach (IGenericParameter gp in FindGenericParameters(typeArgument)) yield return gp; } yield break; } ICallableType callableType = type as ICallableType; if (callableType != null) { CallableSignature signature = callableType.GetSignature(); foreach (IGenericParameter gp in FindGenericParameters(signature.ReturnType)) yield return gp; foreach (IParameter parameter in signature.Parameters) { foreach (IGenericParameter gp in FindGenericParameters(parameter.Type)) yield return gp; } yield break; } } /// <summary> /// Finds types constructed from the specified definition in the specified type's interfaces and base types. /// </summary> /// <param name="type">The type in whose hierarchy to search for constructed types.</param> /// <param name="definition">The generic type definition whose constructed versions to search for.</param> /// <returns>Yields the matching types.</returns> public static IEnumerable<IType> FindConstructedTypes(IType type, IType definition) { while (type != null) { if (type.ConstructedInfo != null && type.ConstructedInfo.GenericDefinition == definition) { yield return type; } IType[] interfaces = type.GetInterfaces(); if (interfaces != null) { foreach (IType interfaceType in interfaces) { foreach (IType match in FindConstructedTypes(interfaceType, definition)) { yield return match; } } } type = type.BaseType; } } /// <summary> /// Finds a single constructed occurance of a specified generic definition /// in the specified type's inheritence hierarchy. /// </summary> /// <param name="type">The type in whose hierarchy to search for constructed types.</param> /// <param name="definition">The generic type definition whose constructed versions to search for.</param> /// <returns> /// The single constructed occurance of the generic definition in the /// specified type, or null if there are none or more than one. /// </returns> public static IType FindConstructedType(IType type, IType definition) { IType result = null; foreach (IType candidate in FindConstructedTypes(type, definition)) { if (result == null) result = candidate; else if (result != candidate) return null; } return result; } /// <summary> /// Checks that at least one constructed occurence of a specified generic /// definition is present in the specified type's inheritance hierarchy. /// </summary> /// <param name="type">The type in whose hierarchy to search for constructed type.</param> /// <param name="definition">The generic type definition whose constructed versions to search for.</param> /// <returns> /// True if a occurence has been found, False otherwise. /// </returns> public static bool HasConstructedType(IType type, IType definition) { return FindConstructedTypes(type, definition).GetEnumerator().MoveNext(); } /// <summary> /// Determines whether a specified type is an open generic type - /// that is, if it contains generic parameters. /// </summary> public static bool IsOpenGenericType(IType type) { return (GetTypeGenerity(type) != 0); } /// <summary> /// Gets the generic parameters associated with a generic type or generic method definition. /// </summary> /// <returns>An array of IGenericParameter objects, or null if the specified entity isn't a generic definition.</returns> public static IGenericParameter[] GetGenericParameters(IEntity definition) { if (IsGenericType(definition)) return ((IType) definition).GenericInfo.GenericParameters; if (IsGenericMethod(definition)) return ((IMethod) definition).GenericInfo.GenericParameters; return null; } /// <summary> /// Determines the number of open generic parameters in the specified type. /// </summary> public static int GetTypeGenerity(IType type) { if (type.IsByRef || type.IsArray) return GetTypeGenerity(type.ElementType); if (type is IGenericParameter) return 1; // Generic parameters and generic arguments both contribute // to a types generity. Note that a nested type can be both a generic definition // and a constructed type: Outer[of int].Inner[of T] int generity = 0; if (type.GenericInfo != null) generity += type.GenericInfo.GenericParameters.Length; if (type.ConstructedInfo != null) foreach (IType typeArg in type.ConstructedInfo.GenericArguments) generity += GetTypeGenerity(typeArg); return generity; } /// <summary> /// Determines the number of total generic parameters in the specified type. /// </summary> public static int GetTypeGenericDepth(IType type) { if (type.IsByRef || type.IsArray) return GetTypeGenericDepth(type.ElementType); if (type is IGenericParameter) return 1; // Generic parameters and generic arguments both contribute // to a types genrity. Note that a nested type can be both a generic definition // and a constructed type: Outer[of int].Inner[of T] int generity = 0; if (type.GenericInfo != null) generity += type.GenericInfo.GenericParameters.Length; if (type.ConstructedInfo != null) foreach (IType typeArg in type.ConstructedInfo.GenericArguments) generity += GetTypeGenericDepth(typeArg) + 1; return generity; } public static int GetMethodGenerity(IMethod method) { IConstructedMethodInfo constructedInfo = method.ConstructedInfo; if (constructedInfo != null) return constructedInfo.GenericArguments.Length; IGenericMethodInfo genericInfo = method.GenericInfo; if (genericInfo != null) return genericInfo.GenericParameters.Length; return 0; } } }
// *********************************************************************** // Copyright (c) 2012 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Text; using System.Collections; using System.Globalization; using NUnit.Framework.Internal; namespace NUnit.Framework.Constraints { /// <summary> /// Custom value formatter function /// </summary> /// <param name="val">The value</param> /// <returns></returns> public delegate string ValueFormatter(object val); /// <summary> /// Custom value formatter factory function /// </summary> /// <param name="next">The next formatter function</param> /// <returns>ValueFormatter</returns> /// <remarks>If the given formatter is unable to handle a certain format, it must call the next formatter in the chain</remarks> public delegate ValueFormatter ValueFormatterFactory(ValueFormatter next); /// <summary> /// Static methods used in creating messages /// </summary> internal static class MsgUtils { /// <summary> /// Static string used when strings are clipped /// </summary> private const string ELLIPSIS = "..."; /// <summary> /// Formatting strings used for expected and actual _values /// </summary> private static readonly string Fmt_Null = "null"; private static readonly string Fmt_EmptyString = "<string.Empty>"; private static readonly string Fmt_EmptyCollection = "<empty>"; private static readonly string Fmt_String = "\"{0}\""; private static readonly string Fmt_Char = "'{0}'"; private static readonly string Fmt_DateTime = "yyyy-MM-dd HH:mm:ss.FFFFFFF"; private static readonly string Fmt_DateTimeOffset = "yyyy-MM-dd HH:mm:ss.FFFFFFFzzz"; private static readonly string Fmt_ValueType = "{0}"; private static readonly string Fmt_Default = "<{0}>"; /// <summary> /// Current head of chain of value formatters. Public for testing. /// </summary> public static ValueFormatter DefaultValueFormatter { get; set; } static MsgUtils() { // Initialize formatter to default for values of indeterminate type. DefaultValueFormatter = val => string.Format(Fmt_Default, val); AddFormatter(next => val => val is ValueType ? string.Format(Fmt_ValueType, val) : next(val)); AddFormatter(next => val => val is DateTime ? FormatDateTime((DateTime)val) : next(val)); AddFormatter(next => val => val is DateTimeOffset ? FormatDateTimeOffset ((DateTimeOffset)val) : next (val)); AddFormatter(next => val => val is decimal ? FormatDecimal((decimal)val) : next(val)); AddFormatter(next => val => val is float ? FormatFloat((float)val) : next(val)); AddFormatter(next => val => val is double ? FormatDouble((double)val) : next(val)); AddFormatter(next => val => val is char ? string.Format(Fmt_Char, val) : next(val)); AddFormatter(next => val => val is IEnumerable ? FormatCollection((IEnumerable)val, 0, 10) : next(val)); AddFormatter(next => val => val is string ? FormatString((string)val) : next(val)); AddFormatter(next => val => val.GetType().IsArray ? FormatArray((Array)val) : next(val)); } /// <summary> /// Add a formatter to the chain of responsibility. /// </summary> /// <param name="formatterFactory"></param> public static void AddFormatter(ValueFormatterFactory formatterFactory) { DefaultValueFormatter = formatterFactory(DefaultValueFormatter); } /// <summary> /// Formats text to represent a generalized value. /// </summary> /// <param name="val">The value</param> /// <returns>The formatted text</returns> public static string FormatValue(object val) { if (val == null) return Fmt_Null; var context = TestExecutionContext.CurrentContext; if (context != null) return context.CurrentValueFormatter(val); else return DefaultValueFormatter(val); } /// <summary> /// Formats text for a collection value, /// starting at a particular point, to a max length /// </summary> /// <param name="collection">The collection containing elements to write.</param> /// <param name="start">The starting point of the elements to write</param> /// <param name="max">The maximum number of elements to write</param> public static string FormatCollection(IEnumerable collection, long start, int max) { int count = 0; int index = 0; System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (object obj in collection) { if (index++ >= start) { if (++count > max) break; sb.Append(count == 1 ? "< " : ", "); sb.Append(FormatValue(obj)); } } if (count == 0) return Fmt_EmptyCollection; if (count > max) sb.Append("..."); sb.Append(" >"); return sb.ToString(); } private static string FormatArray(Array array) { if (array.Length == 0) return Fmt_EmptyCollection; int rank = array.Rank; int[] products = new int[rank]; for (int product = 1, r = rank; --r >= 0; ) products[r] = product *= array.GetLength(r); int count = 0; System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (object obj in array) { if (count > 0) sb.Append(", "); bool startSegment = false; for (int r = 0; r < rank; r++) { startSegment = startSegment || count % products[r] == 0; if (startSegment) sb.Append("< "); } sb.Append(FormatValue(obj)); ++count; bool nextSegment = false; for (int r = 0; r < rank; r++) { nextSegment = nextSegment || count % products[r] == 0; if (nextSegment) sb.Append(" >"); } } return sb.ToString(); } private static string FormatString(string s) { return s == string.Empty ? Fmt_EmptyString : string.Format(Fmt_String, s); } private static string FormatDouble(double d) { if (double.IsNaN(d) || double.IsInfinity(d)) return d.ToString(); else { string s = d.ToString("G17", CultureInfo.InvariantCulture); if (s.IndexOf('.') > 0) return s + "d"; else return s + ".0d"; } } private static string FormatFloat(float f) { if (float.IsNaN(f) || float.IsInfinity(f)) return f.ToString(); else { string s = f.ToString("G9", CultureInfo.InvariantCulture); if (s.IndexOf('.') > 0) return s + "f"; else return s + ".0f"; } } private static string FormatDecimal(Decimal d) { return d.ToString("G29", CultureInfo.InvariantCulture) + "m"; } private static string FormatDateTime(DateTime dt) { return dt.ToString(Fmt_DateTime, CultureInfo.InvariantCulture); } private static string FormatDateTimeOffset(DateTimeOffset dto) { return dto.ToString(Fmt_DateTimeOffset, CultureInfo.InvariantCulture); } /// <summary> /// Returns the representation of a type as used in NUnitLite. /// This is the same as Type.ToString() except for arrays, /// which are displayed with their declared sizes. /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string GetTypeRepresentation(object obj) { Array array = obj as Array; if (array == null) return string.Format("<{0}>", obj.GetType()); StringBuilder sb = new StringBuilder(); Type elementType = array.GetType(); int nest = 0; while (elementType.IsArray) { elementType = elementType.GetElementType(); ++nest; } sb.Append(elementType.ToString()); sb.Append('['); for (int r = 0; r < array.Rank; r++) { if (r > 0) sb.Append(','); sb.Append(array.GetLength(r)); } sb.Append(']'); while (--nest > 0) sb.Append("[]"); return string.Format("<{0}>", sb.ToString()); } /// <summary> /// Converts any control characters in a string /// to their escaped representation. /// </summary> /// <param name="s">The string to be converted</param> /// <returns>The converted string</returns> public static string EscapeControlChars(string s) { if (s != null) { StringBuilder sb = new StringBuilder(); foreach (char c in s) { switch (c) { //case '\'': // sb.Append("\\\'"); // break; //case '\"': // sb.Append("\\\""); // break; case '\\': sb.Append("\\\\"); break; case '\0': sb.Append("\\0"); break; case '\a': sb.Append("\\a"); break; case '\b': sb.Append("\\b"); break; case '\f': sb.Append("\\f"); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; case '\v': sb.Append("\\v"); break; case '\x0085': case '\x2028': case '\x2029': sb.Append(string.Format("\\x{0:X4}", (int)c)); break; default: sb.Append(c); break; } } s = sb.ToString(); } return s; } /// <summary> /// Converts any null characters in a string /// to their escaped representation. /// </summary> /// <param name="s">The string to be converted</param> /// <returns>The converted string</returns> public static string EscapeNullCharacters(string s) { if(s != null) { StringBuilder sb = new StringBuilder(); foreach(char c in s) { switch(c) { case '\0': sb.Append("\\0"); break; default: sb.Append(c); break; } } s = sb.ToString(); } return s; } /// <summary> /// Return the a string representation for a set of indices into an array /// </summary> /// <param name="indices">Array of indices for which a string is needed</param> public static string GetArrayIndicesAsString(int[] indices) { StringBuilder sb = new StringBuilder(); sb.Append('['); for (int r = 0; r < indices.Length; r++) { if (r > 0) sb.Append(','); sb.Append(indices[r].ToString()); } sb.Append(']'); return sb.ToString(); } /// <summary> /// Get an array of indices representing the point in a collection or /// array corresponding to a single int index into the collection. /// </summary> /// <param name="collection">The collection to which the indices apply</param> /// <param name="index">Index in the collection</param> /// <returns>Array of indices</returns> public static int[] GetArrayIndicesFromCollectionIndex(IEnumerable collection, long index) { Array array = collection as Array; int rank = array == null ? 1 : array.Rank; int[] result = new int[rank]; for (int r = rank; --r > 0; ) { int l = array.GetLength(r); result[r] = (int)index % l; index /= l; } result[0] = (int)index; return result; } /// <summary> /// Clip a string to a given length, starting at a particular offset, returning the clipped /// string with ellipses representing the removed parts /// </summary> /// <param name="s">The string to be clipped</param> /// <param name="maxStringLength">The maximum permitted length of the result string</param> /// <param name="clipStart">The point at which to start clipping</param> /// <returns>The clipped string</returns> public static string ClipString(string s, int maxStringLength, int clipStart) { int clipLength = maxStringLength; StringBuilder sb = new StringBuilder(); if (clipStart > 0) { clipLength -= ELLIPSIS.Length; sb.Append(ELLIPSIS); } if (s.Length - clipStart > clipLength) { clipLength -= ELLIPSIS.Length; sb.Append(s.Substring(clipStart, clipLength)); sb.Append(ELLIPSIS); } else if (clipStart > 0) sb.Append(s.Substring(clipStart)); else sb.Append(s); return sb.ToString(); } /// <summary> /// Clip the expected and actual strings in a coordinated fashion, /// so that they may be displayed together. /// </summary> /// <param name="expected"></param> /// <param name="actual"></param> /// <param name="maxDisplayLength"></param> /// <param name="mismatch"></param> public static void ClipExpectedAndActual(ref string expected, ref string actual, int maxDisplayLength, int mismatch) { // Case 1: Both strings fit on line int maxStringLength = Math.Max(expected.Length, actual.Length); if (maxStringLength <= maxDisplayLength) return; // Case 2: Assume that the tail of each string fits on line int clipLength = maxDisplayLength - ELLIPSIS.Length; int clipStart = maxStringLength - clipLength; // Case 3: If it doesn't, center the mismatch position if (clipStart > mismatch) clipStart = Math.Max(0, mismatch - clipLength / 2); expected = ClipString(expected, maxDisplayLength, clipStart); actual = ClipString(actual, maxDisplayLength, clipStart); } /// <summary> /// Shows the position two strings start to differ. Comparison /// starts at the start index. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The actual string</param> /// <param name="istart">The index in the strings at which comparison should start</param> /// <param name="ignoreCase">Boolean indicating whether case should be ignored</param> /// <returns>-1 if no mismatch found, or the index where mismatch found</returns> static public int FindMismatchPosition(string expected, string actual, int istart, bool ignoreCase) { int length = Math.Min(expected.Length, actual.Length); string s1 = ignoreCase ? expected.ToLower() : expected; string s2 = ignoreCase ? actual.ToLower() : actual; for (int i = istart; i < length; i++) { if (s1[i] != s2[i]) return i; } // // Strings have same content up to the length of the shorter string. // Mismatch occurs because string lengths are different, so show // that they start differing where the shortest string ends // if (expected.Length != actual.Length) return length; // // Same strings : We shouldn't get here // return -1; } } }
// // OpenPgpContext.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013 Jeffrey Stedfast // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Linq; using System.Diagnostics; using System.Collections.Generic; using Org.BouncyCastle.Bcpg; using Org.BouncyCastle.Bcpg.OpenPgp; namespace MimeKit.Cryptography { /// <summary> /// An abstract OpenPGP cryptography context which can be used for PGP/MIME. /// </summary> /// <remarks> /// Generally speaking, applications should not use a <see cref="OpenPgpContext"/> /// directly, but rather via higher level APIs such as <see cref="MultipartSigned"/> /// and <see cref="MultipartEncrypted"/>. /// </remarks> public abstract class OpenPgpContext : CryptographyContext { /// <summary> /// Gets the public keyring path. /// </summary> /// <value>The public key ring path.</value> protected string PublicKeyRingPath { get; private set; } /// <summary> /// Gets the secret keyring path. /// </summary> /// <value>The secret key ring path.</value> protected string SecretKeyRingPath { get; private set; } /// <summary> /// Gets the public keyring bundle. /// </summary> /// <value>The public keyring bundle.</value> public PgpPublicKeyRingBundle PublicKeyRingBundle { get; protected set; } /// <summary> /// Gets the secret keyring bundle. /// </summary> /// <value>The secret keyring bundle.</value> public PgpSecretKeyRingBundle SecretKeyRingBundle { get; protected set; } /// <summary> /// Gets the signature protocol. /// </summary> /// <remarks> /// <para>The signature protocol is used by <see cref="MultipartSigned"/> /// in order to determine what the protocol parameter of the Content-Type /// header should be.</para> /// </remarks> /// <value>The signature protocol.</value> public override string SignatureProtocol { get { return "application/pgp-signature"; } } /// <summary> /// Gets the encryption protocol. /// </summary> /// <remarks> /// <para>The encryption protocol is used by <see cref="MultipartEncrypted"/> /// in order to determine what the protocol parameter of the Content-Type /// header should be.</para> /// </remarks> /// <value>The encryption protocol.</value> public override string EncryptionProtocol { get { return "application/pgp-encrypted"; } } /// <summary> /// Gets the key exchange protocol. /// </summary> /// <value>The key exchange protocol.</value> public override string KeyExchangeProtocol { get { return "application/pgp-keys"; } } /// <summary> /// Checks whether or not the specified protocol is supported by the <see cref="CryptographyContext"/>. /// </summary> /// <returns><c>true</c> if the protocol is supported; otherwise <c>false</c></returns> /// <param name="protocol">The protocol.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="protocol"/> is <c>null</c>. /// </exception> public override bool Supports (string protocol) { if (protocol == null) throw new ArgumentNullException ("protocol"); var type = protocol.ToLowerInvariant ().Split (new char[] { '/' }); if (type.Length != 2 || type[0] != "application") return false; if (type[1].StartsWith ("x-", StringComparison.Ordinal)) type[1] = type[1].Substring (2); return type[1] == "pgp-signature" || type[1] == "pgp-encrypted" || type[1] == "pgp-keys"; } /// <summary> /// Gets the string name of the digest algorithm for use with the micalg parameter of a multipart/signed part. /// </summary> /// <remarks> /// <para>Maps the <see cref="DigestAlgorithm"/> to the appropriate string identifier /// as used by the micalg parameter value of a multipart/signed Content-Type /// header. For example:</para> /// <list type="table"> /// <listheader><term>Algorithm</term><description>Name</description></listheader> /// <item><term><see cref="DigestAlgorithm.MD5"/></term><description>pgp-md5</description></item> /// <item><term><see cref="DigestAlgorithm.Sha1"/></term><description>pgp-sha1</description></item> /// <item><term><see cref="DigestAlgorithm.RipeMD160"/></term><description>pgp-ripemd160</description></item> /// <item><term><see cref="DigestAlgorithm.MD2"/></term><description>pgp-md2</description></item> /// <item><term><see cref="DigestAlgorithm.Tiger192"/></term><description>pgp-tiger192</description></item> /// <item><term><see cref="DigestAlgorithm.Haval5160"/></term><description>pgp-haval-5-160</description></item> /// </list> /// </remarks> /// <returns>The micalg value.</returns> /// <param name="micalg">The digest algorithm.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="micalg"/> is out of range. /// </exception> public override string GetDigestAlgorithmName (DigestAlgorithm micalg) { switch (micalg) { case DigestAlgorithm.MD5: return "pgp-md5"; case DigestAlgorithm.Sha1: return "pgp-sha1"; case DigestAlgorithm.RipeMD160: return "pgp-ripemd160"; case DigestAlgorithm.MD2: return "pgp-md2"; case DigestAlgorithm.Tiger192: return "pgp-tiger192"; case DigestAlgorithm.Haval5160: return "pgp-haval-5-160"; case DigestAlgorithm.Sha256: return "pgp-sha256"; case DigestAlgorithm.Sha384: return "pgp-sha384"; case DigestAlgorithm.Sha512: return "pgp-sha512"; case DigestAlgorithm.Sha224: return "pgp-sha224"; case DigestAlgorithm.MD4: return "pgp-md4"; default: throw new ArgumentOutOfRangeException ("micalg"); } } /// <summary> /// Gets the digest algorithm from the micalg parameter value in a multipart/signed part. /// </summary> /// <remarks> /// Maps the micalg parameter value string back to the appropriate <see cref="DigestAlgorithm"/>. /// </remarks> /// <returns>The digest algorithm.</returns> /// <param name="micalg">The micalg parameter value.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="micalg"/> is <c>null</c>. /// </exception> public override DigestAlgorithm GetDigestAlgorithm (string micalg) { if (micalg == null) throw new ArgumentNullException ("micalg"); switch (micalg.ToLowerInvariant ()) { case "pgp-md5": return DigestAlgorithm.MD5; case "pgp-sha1": return DigestAlgorithm.Sha1; case "pgp-ripemd160": return DigestAlgorithm.RipeMD160; case "pgp-md2": return DigestAlgorithm.MD2; case "pgp-tiger192": return DigestAlgorithm.Tiger192; case "pgp-haval-5-160": return DigestAlgorithm.Haval5160; case "pgp-sha256": return DigestAlgorithm.Sha256; case "pgp-sha384": return DigestAlgorithm.Sha384; case "pgp-sha512": return DigestAlgorithm.Sha512; case "pgp-sha224": return DigestAlgorithm.Sha224; case "pgp-md4": return DigestAlgorithm.MD4; default: return DigestAlgorithm.None; } } /// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.OpenPgpContext"/> class. /// </summary> /// <param name="pubring">The public keyring file path.</param> /// <param name="secring">The secret keyring file path.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="pubring"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="secring"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred while reading one of the keyring files. /// </exception> /// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException"> /// An error occurred while parsing one of the keyring files. /// </exception> protected OpenPgpContext (string pubring, string secring) { if (pubring == null) throw new ArgumentNullException ("pubring"); if (secring == null) throw new ArgumentNullException ("secring"); PublicKeyRingPath = pubring; SecretKeyRingPath = secring; if (File.Exists (pubring)) { using (var file = File.OpenRead (pubring)) { PublicKeyRingBundle = new PgpPublicKeyRingBundle (file); } } else { PublicKeyRingBundle = new PgpPublicKeyRingBundle (new byte[0]); } if (File.Exists (secring)) { using (var file = File.OpenRead (secring)) { SecretKeyRingBundle = new PgpSecretKeyRingBundle (file); } } else { SecretKeyRingBundle = new PgpSecretKeyRingBundle (new byte[0]); } } /// <summary> /// Gets the public key associated with the <see cref="MimeKit.MailboxAddress"/>. /// </summary> /// <returns>The encryption key.</returns> /// <param name="mailbox">The mailbox.</param> /// <exception cref="PublicKeyNotFoundException"> /// The public key for the specified <paramref name="mailbox"/> could not be found. /// </exception> protected virtual PgpPublicKey GetPublicKey (MailboxAddress mailbox) { // FIXME: do the mailbox comparisons ourselves? foreach (PgpPublicKeyRing keyring in PublicKeyRingBundle.GetKeyRings (mailbox.Address, true)) { foreach (PgpPublicKey key in keyring.GetPublicKeys ()) { if (!key.IsEncryptionKey || key.IsRevoked ()) continue; long seconds = key.GetValidSeconds (); if (seconds != 0) { var expires = key.CreationTime.AddSeconds ((double) seconds); if (expires >= DateTime.Now) continue; } return key; } } throw new PublicKeyNotFoundException (mailbox, "The public key could not be found."); } /// <summary> /// Gets the public keys for the specified <see cref="MimeKit.MailboxAddress"/>es. /// </summary> /// <returns>The encryption keys.</returns> /// <param name="mailboxes">The mailboxes.</param> /// <exception cref="PublicKeyNotFoundException"> /// A public key for one or more of the <paramref name="mailboxes"/> could not be found. /// </exception> protected virtual IList<PgpPublicKey> GetPublicKeys (IEnumerable<MailboxAddress> mailboxes) { var recipients = new List<PgpPublicKey> (); foreach (var mailbox in mailboxes) recipients.Add (GetPublicKey (mailbox)); return recipients; } /// <summary> /// Gets the signing key associated with the <see cref="MimeKit.MailboxAddress"/>. /// </summary> /// <returns>The signing key.</returns> /// <param name="mailbox">The mailbox.</param> /// <exception cref="PrivateKeyNotFoundException"> /// A private key for the specified <paramref name="mailbox"/> could not be found. /// </exception> protected virtual PgpSecretKey GetSigningKey (MailboxAddress mailbox) { foreach (PgpSecretKeyRing keyring in SecretKeyRingBundle.GetKeyRings (mailbox.Address, true)) { foreach (PgpSecretKey key in keyring.GetSecretKeys ()) { if (!key.IsSigningKey) continue; var pubkey = key.PublicKey; if (pubkey.IsRevoked ()) continue; long seconds = pubkey.GetValidSeconds (); if (seconds != 0) { var expires = pubkey.CreationTime.AddSeconds ((double) seconds); if (expires >= DateTime.Now) continue; } return key; } } throw new PrivateKeyNotFoundException (mailbox, "The private key could not be found."); } /// <summary> /// Gets the password for key. /// </summary> /// <returns>The password for key.</returns> /// <param name="key">The key.</param> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password request. /// </exception> protected abstract string GetPasswordForKey (PgpSecretKey key); /// <summary> /// Gets the private key from the specified secret key. /// </summary> /// <returns>The private key.</returns> /// <param name="key">The secret key.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="key"/> is <c>null</c>. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> protected PgpPrivateKey GetPrivateKey (PgpSecretKey key) { int attempts = 0; string password; if (key == null) throw new ArgumentNullException ("key"); do { if ((password = GetPasswordForKey (key)) == null) throw new OperationCanceledException (); try { return key.ExtractPrivateKey (password.ToCharArray ()); } catch (Exception ex) { Debug.WriteLine ("Failed to extract secret key: {0}", ex); } attempts++; } while (attempts < 3); throw new UnauthorizedAccessException (); } /// <summary> /// Gets the private key. /// </summary> /// <returns>The private key.</returns> /// <param name="keyId">The key identifier.</param> /// <exception cref="CertificateNotFoundException"> /// The specified secret key could not be found. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> protected PgpPrivateKey GetPrivateKey (long keyId) { foreach (PgpSecretKeyRing keyring in SecretKeyRingBundle.GetKeyRings ()) { foreach (PgpSecretKey key in keyring.GetSecretKeys ()) { if (key.KeyId != keyId) continue; return GetPrivateKey (key); } } throw new PrivateKeyNotFoundException (keyId.ToString ("X"), "The private key could not be found."); } /// <summary> /// Gets the equivalent <see cref="Org.BouncyCastle.Bcpg.HashAlgorithmTag"/> for the /// specified <see cref="DigestAlgorithm"/>. /// </summary> /// <remarks> /// Maps a <see cref="DigestAlgorithm"/> to the equivalent <see cref="Org.BouncyCastle.Bcpg.HashAlgorithmTag"/>. /// </remarks> /// <returns>The hash algorithm.</returns> /// <param name="digestAlgo">The digest algorithm.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="digestAlgo"/> is out of range. /// </exception> /// <exception cref="System.NotSupportedException"> /// <paramref name="digestAlgo"/> does not have an equivalent /// <see cref="Org.BouncyCastle.Bcpg.HashAlgorithmTag"/> value. /// </exception> public static HashAlgorithmTag GetHashAlgorithm (DigestAlgorithm digestAlgo) { switch (digestAlgo) { case DigestAlgorithm.MD5: return HashAlgorithmTag.MD5; case DigestAlgorithm.Sha1: return HashAlgorithmTag.Sha1; case DigestAlgorithm.RipeMD160: return HashAlgorithmTag.RipeMD160; case DigestAlgorithm.DoubleSha: return HashAlgorithmTag.DoubleSha; case DigestAlgorithm.MD2: return HashAlgorithmTag.MD2; case DigestAlgorithm.Tiger192: return HashAlgorithmTag.Tiger192; case DigestAlgorithm.Haval5160: return HashAlgorithmTag.Haval5pass160; case DigestAlgorithm.Sha256: return HashAlgorithmTag.Sha256; case DigestAlgorithm.Sha384: return HashAlgorithmTag.Sha384; case DigestAlgorithm.Sha512: return HashAlgorithmTag.Sha512; case DigestAlgorithm.Sha224: return HashAlgorithmTag.Sha224; case DigestAlgorithm.MD4: throw new NotSupportedException ("The MD4 digest algorithm is not supported."); default: throw new ArgumentOutOfRangeException ("digestAlgo"); } } /// <summary> /// Sign the content using the specified signer. /// </summary> /// <returns>A new <see cref="MimeKit.MimePart"/> instance /// containing the detached signature data.</returns> /// <param name="signer">The signer.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="content">The content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="content"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="digestAlgo"/> is out of range. /// </exception> /// <exception cref="System.NotSupportedException"> /// The specified <see cref="DigestAlgorithm"/> is not supported by this context. /// </exception> /// <exception cref="PrivateKeyNotFoundException"> /// A signing key could not be found for <paramref name="signer"/>. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public override MimePart Sign (MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content) { if (signer == null) throw new ArgumentNullException ("signer"); if (content == null) throw new ArgumentNullException ("content"); var key = GetSigningKey (signer); return Sign (key, digestAlgo, content); } /// <summary> /// Sign the content using the specified signer. /// </summary> /// <returns>A new <see cref="MimeKit.MimePart"/> instance /// containing the detached signature data.</returns> /// <param name="signer">The signer.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="content">The content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="content"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="signer"/> cannot be used for signing. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// The <paramref name="digestAlgo"/> was out of range. /// </exception> /// <exception cref="System.NotSupportedException"> /// The <paramref name="digestAlgo"/> is not supported. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public ApplicationPgpSignature Sign (PgpSecretKey signer, DigestAlgorithm digestAlgo, Stream content) { if (signer == null) throw new ArgumentNullException ("signer"); if (!signer.IsSigningKey) throw new ArgumentException ("The specified secret key cannot be used for signing.", "signer"); if (content == null) throw new ArgumentNullException ("content"); var hashAlgorithm = GetHashAlgorithm (digestAlgo); var memory = new MemoryStream (); using (var armored = new ArmoredOutputStream (memory)) { var compresser = new PgpCompressedDataGenerator (CompressionAlgorithmTag.ZLib); using (var compressed = compresser.Open (armored)) { var signatureGenerator = new PgpSignatureGenerator (signer.PublicKey.Algorithm, hashAlgorithm); var buf = new byte[4096]; int nread; signatureGenerator.InitSign (PgpSignature.CanonicalTextDocument, GetPrivateKey (signer)); while ((nread = content.Read (buf, 0, buf.Length)) > 0) signatureGenerator.Update (buf, 0, nread); var signature = signatureGenerator.Generate (); signature.Encode (compressed); compressed.Flush (); } armored.Flush (); } memory.Position = 0; return new ApplicationPgpSignature (memory); } /// <summary> /// Gets the equivalent <see cref="DigestAlgorithm"/> for the specified /// <see cref="Org.BouncyCastle.Bcpg.HashAlgorithmTag"/>. /// </summary> /// <returns>The digest algorithm.</returns> /// <param name="hashAlgorithm">The hash algorithm.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="hashAlgorithm"/> is out of range. /// </exception> /// <exception cref="System.NotSupportedException"> /// <paramref name="hashAlgorithm"/> does not have an equivalent <see cref="DigestAlgorithm"/> value. /// </exception> public static DigestAlgorithm GetDigestAlgorithm (HashAlgorithmTag hashAlgorithm) { switch (hashAlgorithm) { case HashAlgorithmTag.MD5: return DigestAlgorithm.MD5; case HashAlgorithmTag.Sha1: return DigestAlgorithm.Sha1; case HashAlgorithmTag.RipeMD160: return DigestAlgorithm.RipeMD160; case HashAlgorithmTag.DoubleSha: return DigestAlgorithm.DoubleSha; case HashAlgorithmTag.MD2: return DigestAlgorithm.MD2; case HashAlgorithmTag.Tiger192: return DigestAlgorithm.Tiger192; case HashAlgorithmTag.Haval5pass160: return DigestAlgorithm.Haval5160; case HashAlgorithmTag.Sha256: return DigestAlgorithm.Sha256; case HashAlgorithmTag.Sha384: return DigestAlgorithm.Sha384; case HashAlgorithmTag.Sha512: return DigestAlgorithm.Sha512; case HashAlgorithmTag.Sha224: return DigestAlgorithm.Sha224; default: throw new ArgumentOutOfRangeException ("hashAlgorithm"); } } /// <summary> /// Gets the equivalent <see cref="PublicKeyAlgorithm"/> for the specified /// <see cref="Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag"/>. /// </summary> /// <returns>The public-key algorithm.</returns> /// <param name="algorithm">The public-key algorithm.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="algorithm"/> is out of range. /// </exception> /// <exception cref="System.NotSupportedException"> /// <paramref name="algorithm"/> does not have an equivalent <see cref="PublicKeyAlgorithm"/> value. /// </exception> public static PublicKeyAlgorithm GetPublicKeyAlgorithm (PublicKeyAlgorithmTag algorithm) { switch (algorithm) { case PublicKeyAlgorithmTag.RsaGeneral: return PublicKeyAlgorithm.RsaGeneral; case PublicKeyAlgorithmTag.RsaEncrypt: return PublicKeyAlgorithm.RsaEncrypt; case PublicKeyAlgorithmTag.RsaSign: return PublicKeyAlgorithm.RsaSign; case PublicKeyAlgorithmTag.ElGamalEncrypt: return PublicKeyAlgorithm.ElGamalEncrypt; case PublicKeyAlgorithmTag.Dsa: return PublicKeyAlgorithm.Dsa; case PublicKeyAlgorithmTag.EC: return PublicKeyAlgorithm.EllipticCurve; case PublicKeyAlgorithmTag.ECDsa: return PublicKeyAlgorithm.EllipticCurveDsa; case PublicKeyAlgorithmTag.ElGamalGeneral: return PublicKeyAlgorithm.ElGamalGeneral; case PublicKeyAlgorithmTag.DiffieHellman: return PublicKeyAlgorithm.DiffieHellman; default: throw new ArgumentOutOfRangeException ("algorithm"); } } DigitalSignatureCollection GetDigitalSignatures (PgpSignatureList signatureList, Stream content) { var signatures = new List<IDigitalSignature> (); var buf = new byte[4096]; int nread; for (int i = 0; i < signatureList.Count; i++) { var pubkey = PublicKeyRingBundle.GetPublicKey (signatureList[i].KeyId); var signature = new OpenPgpDigitalSignature (pubkey, signatureList[i]) { PublicKeyAlgorithm = GetPublicKeyAlgorithm (signatureList[i].KeyAlgorithm), DigestAlgorithm = GetDigestAlgorithm (signatureList[i].HashAlgorithm), CreationDate = signatureList[i].CreationTime, }; if (pubkey != null) signatureList[i].InitVerify (pubkey); signatures.Add (signature); } while ((nread = content.Read (buf, 0, buf.Length)) > 0) { for (int i = 0; i < signatures.Count; i++) { if (signatures[i].SignerCertificate != null) { var pgp = (OpenPgpDigitalSignature) signatures[i]; pgp.Signature.Update (buf, 0, nread); } } } return new DigitalSignatureCollection (signatures); } /// <summary> /// Verify the specified content and signatureData. /// </summary> /// <returns>A list of digital signatures.</returns> /// <param name="content">The content.</param> /// <param name="signatureData">The signature data.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="content"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="signatureData"/> is <c>null</c>.</para> /// </exception> public override DigitalSignatureCollection Verify (Stream content, Stream signatureData) { if (content == null) throw new ArgumentNullException ("content"); if (signatureData == null) throw new ArgumentNullException ("signatureData"); using (var armored = new ArmoredInputStream (signatureData)) { var factory = new PgpObjectFactory (armored); var data = factory.NextPgpObject (); PgpSignatureList signatureList; var compressed = data as PgpCompressedData; if (compressed != null) { factory = new PgpObjectFactory (compressed.GetDataStream ()); signatureList = (PgpSignatureList) factory.NextPgpObject (); } else { if ((signatureList = data as PgpSignatureList) == null) throw new Exception ("Unexpected pgp object"); } return GetDigitalSignatures (signatureList, content); } } /// <summary> /// Encrypts the specified content for the specified recipients. /// </summary> /// <returns>A new <see cref="MimeKit.MimePart"/> instance /// containing the encrypted data.</returns> /// <param name="recipients">The recipients.</param> /// <param name="content">The content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="content"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <para>One or more of the recipient keys cannot be used for encrypting.</para> /// <para>-or-</para> /// <para>No recipients were specified.</para> /// </exception> /// <exception cref="PublicKeyNotFoundException"> /// A public key could not be found for one or more of the <paramref name="recipients"/>. /// </exception> public override MimePart Encrypt (IEnumerable<MailboxAddress> recipients, Stream content) { if (recipients == null) throw new ArgumentNullException ("recipients"); if (content == null) throw new ArgumentNullException ("content"); // FIXME: document the exceptions that can be thrown by BouncyCastle return Encrypt (GetPublicKeys (recipients), content); } Stream Compress (Stream content) { var compresser = new PgpCompressedDataGenerator (CompressionAlgorithmTag.ZLib); var memory = new MemoryStream (); using (var compressed = compresser.Open (memory)) { var literalGenerator = new PgpLiteralDataGenerator (); using (var literal = literalGenerator.Open (compressed, 't', "mime.txt", content.Length, DateTime.Now)) { content.CopyTo (literal, 4096); literal.Flush (); } compressed.Flush (); } memory.Position = 0; return memory; } Stream Encrypt (PgpEncryptedDataGenerator encrypter, Stream content) { var memory = new MemoryStream (); using (var armored = new ArmoredOutputStream (memory)) { using (var compressed = Compress (content)) { using (var encrypted = encrypter.Open (armored, compressed.Length)) { compressed.CopyTo (encrypted, 4096); encrypted.Flush (); } } armored.Flush (); } memory.Position = 0; return memory; } /// <summary> /// Encrypts the specified content for the specified recipients. /// </summary> /// <returns>A new <see cref="MimeKit.MimePart"/> instance /// containing the encrypted data.</returns> /// <param name="recipients">The recipients.</param> /// <param name="content">The content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="content"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <para>One or more of the recipient keys cannot be used for encrypting.</para> /// <para>-or-</para> /// <para>No recipients were specified.</para> /// </exception> public MimePart Encrypt (IEnumerable<PgpPublicKey> recipients, Stream content) { if (recipients == null) throw new ArgumentNullException ("recipients"); if (content == null) throw new ArgumentNullException ("content"); var encrypter = new PgpEncryptedDataGenerator (SymmetricKeyAlgorithmTag.Aes256, true); int count = 0; foreach (var recipient in recipients) { if (!recipient.IsEncryptionKey) throw new ArgumentException ("One or more of the recipient keys cannot be used for encrypting.", "recipients"); encrypter.AddMethod (recipient); count++; } if (count == 0) throw new ArgumentException ("No recipients specified.", "recipients"); var encrypted = Encrypt (encrypter, content); return new MimePart ("application", "octet-stream") { ContentDisposition = new ContentDisposition ("attachment"), ContentObject = new ContentObject (encrypted, ContentEncoding.Default), }; } /// <summary> /// Signs and encrypts the specified content for the specified recipients. /// </summary> /// <returns>A new <see cref="MimeKit.MimePart"/> instance /// containing the encrypted data.</returns> /// <param name="signer">The signer.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="recipients">The recipients.</param> /// <param name="content">The content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="content"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="digestAlgo"/> is out of range. /// </exception> /// <exception cref="System.ArgumentException"> /// <para>One or more of the recipient keys cannot be used for encrypting.</para> /// <para>-or-</para> /// <para>No recipients were specified.</para> /// </exception> /// <exception cref="System.NotSupportedException"> /// The specified <see cref="DigestAlgorithm"/> is not supported by this context. /// </exception> /// <exception cref="PrivateKeyNotFoundException"> /// The private key could not be found for <paramref name="signer"/>. /// </exception> /// <exception cref="PublicKeyNotFoundException"> /// A public key could not be found for one or more of the <paramref name="recipients"/>. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public MimePart SignAndEncrypt (MailboxAddress signer, DigestAlgorithm digestAlgo, IEnumerable<MailboxAddress> recipients, Stream content) { if (signer == null) throw new ArgumentNullException ("signer"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (content == null) throw new ArgumentNullException ("content"); var key = GetSigningKey (signer); return SignAndEncrypt (key, digestAlgo, GetPublicKeys (recipients), content); } /// <summary> /// Signs and encrypts the specified content for the specified recipients. /// </summary> /// <returns>A new <see cref="MimeKit.MimePart"/> instance /// containing the encrypted data.</returns> /// <param name="signer">The signer.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="recipients">The recipients.</param> /// <param name="content">The content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="content"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="signer"/> cannot be used for signing.</para> /// <para>-or-</para> /// <para>One or more of the recipient keys cannot be used for encrypting.</para> /// <para>-or-</para> /// <para>No recipients were specified.</para> /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public MimePart SignAndEncrypt (PgpSecretKey signer, DigestAlgorithm digestAlgo, IEnumerable<PgpPublicKey> recipients, Stream content) { // FIXME: document the exceptions that can be thrown by BouncyCastle if (signer == null) throw new ArgumentNullException ("signer"); if (!signer.IsSigningKey) throw new ArgumentException ("The specified secret key cannot be used for signing.", "signer"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (content == null) throw new ArgumentNullException ("content"); var encrypter = new PgpEncryptedDataGenerator (SymmetricKeyAlgorithmTag.Aes256, true); var hashAlgorithm = GetHashAlgorithm (digestAlgo); int count = 0; foreach (var recipient in recipients) { if (!recipient.IsEncryptionKey) throw new ArgumentException ("One or more of the recipient keys cannot be used for encrypting.", "recipients"); encrypter.AddMethod (recipient); count++; } if (count == 0) throw new ArgumentException ("No recipients specified.", "recipients"); var compresser = new PgpCompressedDataGenerator (CompressionAlgorithmTag.ZLib); using (var compressed = new MemoryStream ()) { using (var signed = compresser.Open (compressed)) { var signatureGenerator = new PgpSignatureGenerator (signer.PublicKey.Algorithm, hashAlgorithm); signatureGenerator.InitSign (PgpSignature.CanonicalTextDocument, GetPrivateKey (signer)); var subpacket = new PgpSignatureSubpacketGenerator (); foreach (string userId in signer.PublicKey.GetUserIds ()) { subpacket.SetSignerUserId (false, userId); break; } signatureGenerator.SetHashedSubpackets (subpacket.Generate ()); var onepass = signatureGenerator.GenerateOnePassVersion (false); onepass.Encode (signed); var literalGenerator = new PgpLiteralDataGenerator (); using (var literal = literalGenerator.Open (signed, 't', "mime.txt", content.Length, DateTime.Now)) { byte[] buf = new byte[4096]; int nread; while ((nread = content.Read (buf, 0, buf.Length)) > 0) { signatureGenerator.Update (buf, 0, nread); literal.Write (buf, 0, nread); } literal.Flush (); } var signature = signatureGenerator.Generate (); signature.Encode (signed); signed.Flush (); } compressed.Position = 0; var memory = new MemoryStream (); using (var armored = new ArmoredOutputStream (memory)) { using (var encrypted = encrypter.Open (armored, compressed.Length)) { compressed.CopyTo (encrypted, 4096); encrypted.Flush (); } armored.Flush (); } memory.Position = 0; return new MimePart ("application", "octet-stream") { ContentDisposition = new ContentDisposition ("attachment"), ContentObject = new ContentObject (memory, ContentEncoding.Default) }; } } /// <summary> /// Decrypt an encrypted stream. /// </summary> /// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns> /// <param name="encryptedData">The encrypted data.</param> /// <param name="signatures">A list of digital signatures if the data was both signed and encrypted.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="encryptedData"/> is <c>null</c>. /// </exception> /// <exception cref="PrivateKeyNotFoundException"> /// The private key could not be found to decrypt the stream. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public MimeEntity Decrypt (Stream encryptedData, out DigitalSignatureCollection signatures) { if (encryptedData == null) throw new ArgumentNullException ("encryptedData"); // FIXME: document the exceptions that can be thrown by BouncyCastle using (var armored = new ArmoredInputStream (encryptedData)) { var factory = new PgpObjectFactory (armored); var obj = factory.NextPgpObject (); var list = obj as PgpEncryptedDataList; if (list == null) { // probably a PgpMarker... obj = factory.NextPgpObject (); list = obj as PgpEncryptedDataList; if (list == null) throw new Exception ("Unexpected pgp object"); } PgpPublicKeyEncryptedData encrypted = null; foreach (PgpEncryptedData data in list.GetEncryptedDataObjects ()) { if ((encrypted = data as PgpPublicKeyEncryptedData) != null) break; } if (encrypted == null) throw new Exception ("no encrypted data objects found?"); factory = new PgpObjectFactory (encrypted.GetDataStream (GetPrivateKey (encrypted.KeyId))); PgpOnePassSignatureList onepassList = null; PgpSignatureList signatureList = null; PgpCompressedData compressed = null; using (var memory = new MemoryStream ()) { obj = factory.NextPgpObject (); while (obj != null) { if (obj is PgpCompressedData) { if (compressed != null) throw new Exception ("recursive compression detected."); compressed = (PgpCompressedData) obj; factory = new PgpObjectFactory (compressed.GetDataStream ()); } else if (obj is PgpOnePassSignatureList) { onepassList = (PgpOnePassSignatureList) obj; } else if (obj is PgpSignatureList) { signatureList = (PgpSignatureList) obj; } else if (obj is PgpLiteralData) { var literal = (PgpLiteralData) obj; using (var stream = literal.GetDataStream ()) { stream.CopyTo (memory, 4096); } } obj = factory.NextPgpObject (); } memory.Position = 0; // FIXME: validate the OnePass signatures... and do what with them? // if (onepassList != null) { // for (int i = 0; i < onepassList.Count; i++) { // var onepass = onepassList[i]; // } // } if (signatureList != null) { signatures = GetDigitalSignatures (signatureList, memory); memory.Position = 0; } else { signatures = null; } return MimeEntity.Load (memory); } } } /// <summary> /// Decrypt the encrypted data. /// </summary> /// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns> /// <param name="encryptedData">The encrypted data.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="encryptedData"/> is <c>null</c>. /// </exception> /// <exception cref="PrivateKeyNotFoundException"> /// The private key could not be found to decrypt the stream. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public override MimeEntity Decrypt (Stream encryptedData) { DigitalSignatureCollection signatures; if (encryptedData == null) throw new ArgumentNullException ("encryptedData"); return Decrypt (encryptedData, out signatures); } /// <summary> /// Saves the public key-ring bundle. /// </summary> /// <exception cref="System.IO.IOException"> /// An error occured while saving the public key-ring bundle. /// </exception> protected void SavePublicKeyRingBundle () { var filename = Path.GetFileName (PublicKeyRingPath) + "~"; var dirname = Path.GetDirectoryName (PublicKeyRingPath); var tmp = Path.Combine (dirname, "." + filename); var bak = Path.Combine (dirname, filename); if (!Directory.Exists (dirname)) Directory.CreateDirectory (dirname); using (var file = File.OpenWrite (tmp)) { PublicKeyRingBundle.Encode (file); file.Flush (); } if (File.Exists (PublicKeyRingPath)) File.Replace (tmp, PublicKeyRingPath, bak); else File.Move (tmp, PublicKeyRingPath); } /// <summary> /// Saves the secret key-ring bundle. /// </summary> /// <exception cref="System.IO.IOException"> /// An error occured while saving the secret key-ring bundle. /// </exception> protected void SaveSecretKeyRingBundle () { var filename = Path.GetFileName (SecretKeyRingPath) + "~"; var dirname = Path.GetDirectoryName (SecretKeyRingPath); var tmp = Path.Combine (dirname, "." + filename); var bak = Path.Combine (dirname, filename); if (!Directory.Exists (dirname)) Directory.CreateDirectory (dirname); using (var file = File.OpenWrite (tmp)) { SecretKeyRingBundle.Encode (file); file.Flush (); } if (File.Exists (SecretKeyRingPath)) File.Replace (tmp, SecretKeyRingPath, bak); else File.Move (tmp, SecretKeyRingPath); } /// <summary> /// Imports public pgp keys from the specified stream. /// </summary> /// <param name="stream">The raw key data.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.IO.IOException"> /// <para>An error occurred while parsing the raw key-ring data</para> /// <para>-or-</para> /// <para>An error occured while saving the public key-ring bundle.</para> /// </exception> public override void Import (Stream stream) { if (stream == null) throw new ArgumentNullException ("stream"); using (var armored = new ArmoredInputStream (stream)) { var imported = new PgpPublicKeyRingBundle (armored); if (imported.Count == 0) return; int publicKeysAdded = 0; foreach (PgpPublicKeyRing pubring in imported.GetKeyRings ()) { if (!PublicKeyRingBundle.Contains (pubring.GetPublicKey ().KeyId)) { PublicKeyRingBundle = PgpPublicKeyRingBundle.AddPublicKeyRing (PublicKeyRingBundle, pubring); publicKeysAdded++; } } if (publicKeysAdded > 0) SavePublicKeyRingBundle (); } } /// <summary> /// Imports secret pgp keys from the specified stream. /// </summary> /// <param name="rawData">The raw key data.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="rawData"/> is <c>null</c>. /// </exception> /// <exception cref="System.IO.IOException"> /// <para>An error occurred while parsing the raw key-ring data</para> /// <para>-or-</para> /// <para>An error occured while saving the public key-ring bundle.</para> /// </exception> public virtual void ImportSecretKeys (Stream rawData) { if (rawData == null) throw new ArgumentNullException ("rawData"); using (var armored = new ArmoredInputStream (rawData)) { var imported = new PgpSecretKeyRingBundle (armored); if (imported.Count == 0) return; int secretKeysAdded = 0; foreach (PgpSecretKeyRing secring in imported.GetKeyRings ()) { if (!SecretKeyRingBundle.Contains (secring.GetSecretKey ().KeyId)) { SecretKeyRingBundle = PgpSecretKeyRingBundle.AddSecretKeyRing (SecretKeyRingBundle, secring); secretKeysAdded++; } } if (secretKeysAdded > 0) SaveSecretKeyRingBundle (); } } /// <summary> /// Exports the public keys for the specified mailboxes. /// </summary> /// <returns>A new <see cref="MimeKit.MimePart"/> instance containing the exported public keys.</returns> /// <param name="mailboxes">The mailboxes.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="mailboxes"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="mailboxes"/> was empty. /// </exception> public override MimePart Export (IEnumerable<MailboxAddress> mailboxes) { if (mailboxes == null) throw new ArgumentNullException ("mailboxes"); return Export (GetPublicKeys (mailboxes)); } /// <summary> /// Exports the specified public keys. /// </summary> /// <returns>A new <see cref="MimeKit.MimePart"/> instance containing the exported public keys.</returns> /// <param name="keys">The keys.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="keys"/> is <c>null</c>. /// </exception> public MimePart Export (IEnumerable<PgpPublicKey> keys) { if (keys == null) throw new ArgumentNullException ("keys"); var keyrings = keys.Select (key => new PgpPublicKeyRing (key.GetEncoded ())); var bundle = new PgpPublicKeyRingBundle (keyrings); return Export (bundle); } /// <summary> /// Exports the specified public keys. /// </summary> /// <returns>A new <see cref="MimeKit.MimePart"/> instance containing the exported public keys.</returns> /// <param name="keys">The keys.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="keys"/> is <c>null</c>. /// </exception> public MimePart Export (PgpPublicKeyRingBundle keys) { if (keys == null) throw new ArgumentNullException ("keys"); var content = new MemoryStream (); using (var armored = new ArmoredOutputStream (content)) { keys.Encode (armored); armored.Flush (); } content.Position = 0; return new MimePart ("application", "pgp-keys") { ContentDisposition = new ContentDisposition ("attachment"), ContentObject = new ContentObject (content, ContentEncoding.Default) }; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.Text; #endregion /// <summary> /// String reader. /// </summary> public class StringReader { #region Members private readonly string m_OriginalString = ""; private string m_SourceString = ""; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="source">Source string.</param> /// <exception cref="ArgumentNullException">Is raised when <b>source</b> is null.</exception> public StringReader(string source) { if (source == null) { throw new ArgumentNullException("source"); } m_OriginalString = source; m_SourceString = source; } #endregion #region Properties /// <summary> /// Gets how many chars are available for reading. /// </summary> public long Available { get { return m_SourceString.Length; } } /// <summary> /// Gets original string passed to class constructor. /// </summary> public string OriginalString { get { return m_OriginalString; } } /// <summary> /// Gets position in original string. /// </summary> public int Position { get { return m_OriginalString.Length - m_SourceString.Length; } } /// <summary> /// Gets currently remaining string. /// </summary> public string SourceString { get { return m_SourceString; } } #endregion #region Methods /// <summary> /// Appends specified string to SourceString. /// </summary> /// <param name="str">String value to append.</param> public void AppenString(string str) { m_SourceString += str; } /// <summary> /// Reads to first char, skips white-space(SP,VTAB,HTAB,CR,LF) from the beginning of source string. /// </summary> /// <returns>Returns white-space chars which was readed.</returns> public string ReadToFirstChar() { int whiteSpaces = 0; for (int i = 0; i < m_SourceString.Length; i++) { if (char.IsWhiteSpace(m_SourceString[i])) { whiteSpaces++; } else { break; } } string whiteSpaceChars = m_SourceString.Substring(0, whiteSpaces); m_SourceString = m_SourceString.Substring(whiteSpaces); return whiteSpaceChars; } // public string ReadToDelimiter(char delimiter) // { // } /// <summary> /// Reads string with specified length. Throws exception if read length is bigger than source string length. /// </summary> /// <param name="length">Number of chars to read.</param> /// <returns></returns> public string ReadSpecifiedLength(int length) { if (m_SourceString.Length >= length) { string retVal = m_SourceString.Substring(0, length); m_SourceString = m_SourceString.Substring(length); return retVal; } else { throw new Exception("Read length can't be bigger than source string !"); } } /// <summary> /// Reads string to specified delimiter or to end of underlying string. Notes: Delimiter in quoted string is skipped. /// Delimiter is removed by default. /// For example: delimiter = ',', text = '"aaaa,eee",qqqq' - then result is '"aaaa,eee"'. /// </summary> /// <param name="delimiter">Data delimiter.</param> /// <returns></returns> public string QuotedReadToDelimiter(char delimiter) { return QuotedReadToDelimiter(new[] {delimiter}); } /// <summary> /// Reads string to specified delimiter or to end of underlying string. Notes: Delimiters in quoted string is skipped. /// Delimiter is removed by default. /// For example: delimiter = ',', text = '"aaaa,eee",qqqq' - then result is '"aaaa,eee"'. /// </summary> /// <param name="delimiters">Data delimiters.</param> /// <returns></returns> public string QuotedReadToDelimiter(char[] delimiters) { return QuotedReadToDelimiter(delimiters, true); } /// <summary> /// Reads string to specified delimiter or to end of underlying string. Notes: Delimiters in quoted string is skipped. /// For example: delimiter = ',', text = '"aaaa,eee",qqqq' - then result is '"aaaa,eee"'. /// </summary> /// <param name="delimiters">Data delimiters.</param> /// <param name="removeDelimiter">Specifies if delimiter is removed from underlying string.</param> /// <returns></returns> public string QuotedReadToDelimiter(char[] delimiters, bool removeDelimiter) { StringBuilder currentSplitBuffer = new StringBuilder(); // Holds active bool inQuotedString = false; // Holds flag if position is quoted string or not char lastChar = (char) 0; for (int i = 0; i < m_SourceString.Length; i++) { char c = m_SourceString[i]; // Skip escaped(\) " if (lastChar != '\\' && c == '\"') { // Start/end quoted string area inQuotedString = !inQuotedString; } // See if char is delimiter bool isDelimiter = false; foreach (char delimiter in delimiters) { if (c == delimiter) { isDelimiter = true; break; } } // Current char is split char and it isn't in quoted string, do split if (!inQuotedString && isDelimiter) { string retVal = currentSplitBuffer.ToString(); // Remove readed string + delimiter from source string if (removeDelimiter) { m_SourceString = m_SourceString.Substring(retVal.Length + 1); } // Remove readed string else { m_SourceString = m_SourceString.Substring(retVal.Length); } return retVal; } else { currentSplitBuffer.Append(c); } lastChar = c; } // If we reached so far then we are end of string, return it m_SourceString = ""; return currentSplitBuffer.ToString(); } /// <summary> /// Reads word from string. Returns null if no word is available. /// Word reading begins from first char, for example if SP"text", then space is trimmed. /// </summary> /// <returns></returns> public string ReadWord() { return ReadWord(true); } /// <summary> /// Reads word from string. Returns null if no word is available. /// Word reading begins from first char, for example if SP"text", then space is trimmed. /// </summary> /// <param name="unQuote">Specifies if quoted string word is unquoted.</param> /// <returns></returns> public string ReadWord(bool unQuote) { return ReadWord(unQuote, new[] {' ', ',', ';', '{', '}', '(', ')', '[', ']', '<', '>', '\r', '\n'}, false); } /// <summary> /// Reads word from string. Returns null if no word is available. /// Word reading begins from first char, for example if SP"text", then space is trimmed. /// </summary> /// <param name="unQuote">Specifies if quoted string word is unquoted.</param> /// <param name="wordTerminatorChars">Specifies chars what terminate word.</param> /// <param name="removeWordTerminator">Specifies if work terminator is removed.</param> /// <returns></returns> public string ReadWord(bool unQuote, char[] wordTerminatorChars, bool removeWordTerminator) { // Always start word reading from first char. ReadToFirstChar(); if (Available == 0) { return null; } // quoted word can contain any char, " must be escaped with \ // unqouted word can conatin any char except: SP VTAB HTAB,{}()[]<> if (m_SourceString.StartsWith("\"")) { if (unQuote) { return TextUtils.UnQuoteString(QuotedReadToDelimiter(wordTerminatorChars, removeWordTerminator)); } else { return QuotedReadToDelimiter(wordTerminatorChars, removeWordTerminator); } } else { int wordLength = 0; for (int i = 0; i < m_SourceString.Length; i++) { char c = m_SourceString[i]; bool isTerminator = false; foreach (char terminator in wordTerminatorChars) { if (c == terminator) { isTerminator = true; break; } } if (isTerminator) { break; } wordLength++; } string retVal = m_SourceString.Substring(0, wordLength); if (removeWordTerminator) { if (m_SourceString.Length >= wordLength + 1) { m_SourceString = m_SourceString.Substring(wordLength + 1); } } else { m_SourceString = m_SourceString.Substring(wordLength); } return retVal; } } /// <summary> /// Reads parenthesized value. Supports {},(),[],&lt;&gt; parenthesis. /// Throws exception if there isn't parenthesized value or closing parenthesize is missing. /// </summary> /// <returns></returns> public string ReadParenthesized() { ReadToFirstChar(); char startingChar = ' '; char closingChar = ' '; if (m_SourceString.StartsWith("{")) { startingChar = '{'; closingChar = '}'; } else if (m_SourceString.StartsWith("(")) { startingChar = '('; closingChar = ')'; } else if (m_SourceString.StartsWith("[")) { startingChar = '['; closingChar = ']'; } else if (m_SourceString.StartsWith("<")) { startingChar = '<'; closingChar = '>'; } else { throw new Exception("No parenthesized value '" + m_SourceString + "' !"); } bool inQuotedString = false; // Holds flag if position is quoted string or not char lastChar = (char) 0; int closingCharIndex = -1; int nestedStartingCharCounter = 0; for (int i = 1; i < m_SourceString.Length; i++) { // Skip escaped(\) " if (lastChar != '\\' && m_SourceString[i] == '\"') { // Start/end quoted string area inQuotedString = !inQuotedString; } // We need to skip parenthesis in quoted string else if (!inQuotedString) { // There is nested parenthesis if (m_SourceString[i] == startingChar) { nestedStartingCharCounter++; } // Closing char else if (m_SourceString[i] == closingChar) { // There isn't nested parenthesis closing chars left, this is closing char what we want if (nestedStartingCharCounter == 0) { closingCharIndex = i; break; } // This is nested parenthesis closing char else { nestedStartingCharCounter--; } } } lastChar = m_SourceString[i]; } if (closingCharIndex == -1) { throw new Exception("There is no closing parenthesize for '" + m_SourceString + "' !"); } else { string retVal = m_SourceString.Substring(1, closingCharIndex - 1); m_SourceString = m_SourceString.Substring(closingCharIndex + 1); return retVal; } } /// <summary> /// Reads all remaining string, returns null if no chars left to read. /// </summary> /// <returns></returns> public string ReadToEnd() { if (Available == 0) { return null; } string retVal = m_SourceString; m_SourceString = ""; return retVal; } /// <summary> /// Gets if source string starts with specified value. Compare is case-sensitive. /// </summary> /// <param name="value">Start string value.</param> /// <returns></returns> public bool StartsWith(string value) { return m_SourceString.StartsWith(value); } /// <summary> /// Gets if source string starts with specified value. /// </summary> /// <param name="value">Start string value.</param> /// <param name="case_sensitive">Specifies if compare is case-sensitive.</param> /// <returns></returns> public bool StartsWith(string value, bool case_sensitive) { if (case_sensitive) { return m_SourceString.StartsWith(value); } else { return m_SourceString.ToLower().StartsWith(value.ToLower()); } } /// <summary> /// Gets if current source string starts with word. For example if source string starts with /// whiter space or parenthesize, this method returns false. /// </summary> /// <returns></returns> public bool StartsWithWord() { if (m_SourceString.Length == 0) { return false; } if (char.IsWhiteSpace(m_SourceString[0])) { return false; } if (char.IsSeparator(m_SourceString[0])) { return false; } char[] wordTerminators = new[] {' ', ',', ';', '{', '}', '(', ')', '[', ']', '<', '>', '\r', '\n'}; foreach (char c in wordTerminators) { if (c == m_SourceString[0]) { return false; } } return true; } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Media.Imaging; namespace MvvmScarletToolkit.Wpf { /// <summary> /// Represent an element Tag in Html /// </summary> [DebuggerDisplay("{ID} {Name}")] internal sealed class HtmlTag { private readonly Dictionary<string, string> _variables; private readonly Lazy<int> _id; private readonly Lazy<bool> _isEndTag; private readonly Lazy<int> _level; /// <summary> /// HtmlTag ID in BuiltInTags. (without <>) /// </summary> public int ID => _id.Value; /// <summary> /// HtmlTag name. (without <>) /// </summary> public string Name { get; } /// <summary> /// HtmlTag Level in BuiltInTags. (without <>) /// </summary> internal int Level => _level.Value; internal bool IsEndTag => _isEndTag.Value; private HtmlTag(string name, Dictionary<string, string> variables, List<HTMLTagInfo> builtinTags) { _variables = variables ?? throw new ArgumentNullException(nameof(variables)); Name = name.ToLower(); _id = new Lazy<int>(() => builtinTags.FindIndex(tagInfo => tagInfo.Html.Equals(Name.TrimStart('/')))); _isEndTag = new Lazy<bool>(() => (Name.IndexOf('/') == 0) || _variables.ContainsKey("/")); _level = new Lazy<int>(() => ID == -1 ? 0 : builtinTags[ID].TagLevel); } public HtmlTag(IParamParser paramParser, string name, string variableString, List<HTMLTagInfo> builtinTags) : this(name, paramParser.StringToDictionary(variableString), builtinTags) { } public HtmlTag(string text, List<HTMLTagInfo> builtinTags) : this("text", new Dictionary<string, string> { { "value", text } }, builtinTags) { } public bool Contains(string key) { return _variables.ContainsKey(key); } public string this[string key] { get { return _variables[key]; } } public Inline CreateInline(TextBlock textBlock, InlineCreationContext currentStateType) { var result = CreateInlineInternal(textBlock, currentStateType); return TryWrapInHyperLink(result, currentStateType.HyperLink?.Trim('\"')); } private Inline CreateInlineInternal(TextBlock textBlock, InlineCreationContext currentStateType) { switch (Name) { case "br": return new LineBreak(); case "binding": case "text": Inline result; if (Name == "binding") { result = new Bold(new Run("{Binding}")); if (Contains("path") && (textBlock.DataContext != null)) { var dataContext = textBlock.DataContext; var propertyName = _variables["path"]; var property = dataContext.GetType().GetProperty(propertyName); if (property != null && property.CanRead == true) { var value = property.GetValue(dataContext, null); result = new Run(value?.ToString() ?? ""); } } } else { result = new Run(_variables["value"]); } if (currentStateType.SubScript) { result.SetCurrentValue(Typography.VariantsProperty, FontVariants.Subscript); } if (currentStateType.SuperScript) { result.SetCurrentValue(Typography.VariantsProperty, FontVariants.Superscript); } if (currentStateType.Bold) { result = new Bold(result); } if (currentStateType.Italic) { result = new Italic(result); } if (currentStateType.Underline) { result = new Underline(result); } if (currentStateType.Foreground.HasValue) { result.Foreground = new SolidColorBrush(currentStateType.Foreground.Value); } return result; case "img": if (!Contains("source")) { return new Run(); } var width = double.NaN; if (Contains("width") && double.TryParse(_variables["width"], out var internal_width)) width = internal_width; var height = double.NaN; if (Contains("height") && double.TryParse(_variables["height"], out var internal_height)) height = internal_height; if (!Uri.TryCreate(_variables["source"], UriKind.RelativeOrAbsolute, out var uri)) { return new Run(); } var bitmap = new BitmapImage { CacheOption = BitmapCacheOption.OnLoad }; bitmap.BeginInit(); bitmap.UriSource = uri; bitmap.EndInit(); // TODO fetch and apply style var image = new Image { Source = bitmap, Width = width, Height = height }; if (Contains("href")) { return TryWrapInHyperLink(new InlineUIContainer(image), _variables["href"]); } return new InlineUIContainer(image); default: return new Run(); } } private static Inline TryWrapInHyperLink(Inline content, string? url) { if (string.IsNullOrEmpty(url)) { return content; } var link = new Hyperlink(content); if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out var uri)) { link.NavigateUri = uri; link.ToolTip = url; } else { link.NavigateUri = null; } return link; } } }
// Author: Robert Scheller using Landis.Core; using Landis.SpatialModeling; using Landis.Utilities; using System.IO; using System; using Landis.Library.Metadata; using System.Data; using System.Collections.Generic; using System.Collections; namespace Landis.Extension.Succession.NECN { public class Outputs { public static MetadataTable<MonthlyLog> monthlyLog; public static MetadataTable<PrimaryLog> primaryLog; public static MetadataTable<PrimaryLogShort> primaryLogShort; public static MetadataTable<ReproductionLog> reproductionLog; public static MetadataTable<EstablishmentLog> establishmentLog; public static MetadataTable<CalibrateLog> calibrateLog; public static void WriteReproductionLog(int CurrentTime) { foreach (ISpecies spp in PlugIn.ModelCore.Species) { reproductionLog.Clear(); ReproductionLog rl = new ReproductionLog(); rl.Time = CurrentTime; rl.SpeciesName = spp.Name; rl.NumCohortsPlanting = PlugIn.SpeciesByPlant[spp.Index]; rl.NumCohortsSerotiny = PlugIn.SpeciesBySerotiny[spp.Index]; rl.NumCohortsSeed = PlugIn.SpeciesBySeed[spp.Index]; rl.NumCohortsResprout = PlugIn.SpeciesByResprout[spp.Index]; reproductionLog.AddObject(rl); reproductionLog.WriteToFile(); } } //--------------------------------------------------------------------- public static void WriteShortPrimaryLogFile(int CurrentTime) { double avgNEEc = 0.0; double avgSOMtc = 0.0; double avgAGB = 0.0; double avgAGNPPtc = 0.0; double avgMineralN = 0.0; double avgDeadWoodC = 0.0; foreach (ActiveSite site in PlugIn.ModelCore.Landscape) { avgNEEc += SiteVars.AnnualNEE[site] / PlugIn.ModelCore.Landscape.ActiveSiteCount; avgSOMtc += GetOrganicCarbon(site) / PlugIn.ModelCore.Landscape.ActiveSiteCount; avgAGB += (double) Main.ComputeLivingBiomass(SiteVars.Cohorts[site]) / PlugIn.ModelCore.Landscape.ActiveSiteCount; avgAGNPPtc += SiteVars.AGNPPcarbon[site] / PlugIn.ModelCore.Landscape.ActiveSiteCount; avgMineralN += SiteVars.MineralN[site] / PlugIn.ModelCore.Landscape.ActiveSiteCount; avgDeadWoodC += SiteVars.SurfaceDeadWood[site].Carbon / PlugIn.ModelCore.Landscape.ActiveSiteCount; } primaryLogShort.Clear(); PrimaryLogShort pl = new PrimaryLogShort(); pl.Time = CurrentTime; pl.NEEC = avgNEEc; pl.SOMTC = avgSOMtc; pl.AGB = avgAGB; pl.AG_NPPC = avgAGNPPtc; pl.MineralN = avgMineralN; pl.C_DeadWood = avgDeadWoodC; primaryLogShort.AddObject(pl); primaryLogShort.WriteToFile(); } //--------------------------------------------------------------------- public static void WritePrimaryLogFile(int CurrentTime) { double[] avgAnnualPPT = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgJJAtemp = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgNEEc = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOMtc = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgAGB = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgAGNPPtc = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgBGNPPtc = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgLittertc = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgWoodMortality = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgMineralN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgGrossMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgTotalN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortLeafC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortFRootC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortWoodC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgWoodC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortCRootC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCRootC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortLeafN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortFRootN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortWoodN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortCRootN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgWoodN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCRootN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSurfStrucC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSurfMetaC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSoilStrucC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSoilMetaC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSurfStrucN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSurfMetaN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSoilStrucN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSoilMetaN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSurfStrucNetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSurfMetaNetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSoilStrucNetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSoilMetaNetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM1surfC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM1soilC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM2C = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM3C = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM1surfN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM1soilN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM2N = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM3N = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM1surfNetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM1soilNetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM2NetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM3NetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; //doubl[] avgNDeposition = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgStreamC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgStreamN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgFireCEfflux = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgFireNEfflux = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgNvol = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgNresorbed = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgTotalSoilN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgNuptake = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgfrassC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avglai = new double[PlugIn.ModelCore.Ecoregions.Count]; foreach (IEcoregion ecoregion in PlugIn.ModelCore.Ecoregions) { avgAnnualPPT[ecoregion.Index] = 0.0; avgJJAtemp[ecoregion.Index] = 0.0; avgNEEc[ecoregion.Index] = 0.0; avgSOMtc[ecoregion.Index] = 0.0; avgAGB[ecoregion.Index] = 0.0; avgAGNPPtc[ecoregion.Index] = 0.0; avgBGNPPtc[ecoregion.Index] = 0.0; avgLittertc[ecoregion.Index] = 0.0; avgWoodMortality[ecoregion.Index] = 0.0; avgMineralN[ecoregion.Index] = 0.0; avgGrossMin[ecoregion.Index] = 0.0; avgTotalN[ecoregion.Index] = 0.0; avgCohortLeafC[ecoregion.Index] = 0.0; avgCohortFRootC[ecoregion.Index] = 0.0; avgCohortWoodC[ecoregion.Index] = 0.0; avgCohortCRootC[ecoregion.Index] = 0.0; avgWoodC[ecoregion.Index] = 0.0; avgCRootC[ecoregion.Index] = 0.0; avgSurfStrucC[ecoregion.Index] = 0.0; avgSurfMetaC[ecoregion.Index] = 0.0; avgSoilStrucC[ecoregion.Index] = 0.0; avgSoilMetaC[ecoregion.Index] = 0.0; avgCohortLeafN[ecoregion.Index] = 0.0; avgCohortFRootN[ecoregion.Index] = 0.0; avgCohortWoodN[ecoregion.Index] = 0.0; avgCohortCRootN[ecoregion.Index] = 0.0; avgWoodN[ecoregion.Index] = 0.0; avgCRootN[ecoregion.Index] = 0.0; avgSurfStrucN[ecoregion.Index] = 0.0; avgSurfMetaN[ecoregion.Index] = 0.0; avgSoilStrucN[ecoregion.Index] = 0.0; avgSoilMetaN[ecoregion.Index] = 0.0; avgSurfStrucNetMin[ecoregion.Index] = 0.0; avgSurfMetaNetMin[ecoregion.Index] = 0.0; avgSoilStrucNetMin[ecoregion.Index] = 0.0; avgSoilMetaNetMin[ecoregion.Index] = 0.0; avgSOM1surfC[ecoregion.Index] = 0.0; avgSOM1soilC[ecoregion.Index] = 0.0; avgSOM2C[ecoregion.Index] = 0.0; avgSOM3C[ecoregion.Index] = 0.0; avgSOM1surfN[ecoregion.Index] = 0.0; avgSOM1soilN[ecoregion.Index] = 0.0; avgSOM2N[ecoregion.Index] = 0.0; avgSOM3N[ecoregion.Index] = 0.0; avgSOM1surfNetMin[ecoregion.Index] = 0.0; avgSOM1soilNetMin[ecoregion.Index] = 0.0; avgSOM2NetMin[ecoregion.Index] = 0.0; avgSOM3NetMin[ecoregion.Index] = 0.0; //avgNDeposition[ecoregion.Index] = 0.0; avgStreamC[ecoregion.Index] = 0.0; avgStreamN[ecoregion.Index] = 0.0; avgFireCEfflux[ecoregion.Index] = 0.0; avgFireNEfflux[ecoregion.Index] = 0.0; avgNuptake[ecoregion.Index] = 0.0; avgNresorbed[ecoregion.Index] = 0.0; avgTotalSoilN[ecoregion.Index] = 0.0; avgNvol[ecoregion.Index] = 0.0; avgfrassC[ecoregion.Index] = 0.0; } foreach (ActiveSite site in PlugIn.ModelCore.Landscape) { IEcoregion ecoregion = PlugIn.ModelCore.Ecoregion[site]; avgNEEc[ecoregion.Index] += SiteVars.AnnualNEE[site]; avgSOMtc[ecoregion.Index] += GetOrganicCarbon(site); avgAGB[ecoregion.Index] += Main.ComputeLivingBiomass(SiteVars.Cohorts[site]); avgAGNPPtc[ecoregion.Index] += SiteVars.AGNPPcarbon[site]; avgBGNPPtc[ecoregion.Index] += SiteVars.BGNPPcarbon[site]; avgLittertc[ecoregion.Index] += SiteVars.LitterfallC[site]; avgWoodMortality[ecoregion.Index] += SiteVars.WoodMortality[site] * 0.47; avgMineralN[ecoregion.Index] += SiteVars.MineralN[site]; avgTotalN[ecoregion.Index] += GetTotalNitrogen(site); avgGrossMin[ecoregion.Index] += SiteVars.GrossMineralization[site]; avgCohortLeafC[ecoregion.Index] += SiteVars.CohortLeafC[site]; avgCohortFRootC[ecoregion.Index] += SiteVars.CohortFRootC[site]; avgCohortWoodC[ecoregion.Index] += SiteVars.CohortWoodC[site]; avgCohortCRootC[ecoregion.Index] += SiteVars.CohortCRootC[site]; avgWoodC[ecoregion.Index] += SiteVars.SurfaceDeadWood[site].Carbon; avgCRootC[ecoregion.Index] += SiteVars.SoilDeadWood[site].Carbon; avgSurfStrucC[ecoregion.Index] += SiteVars.SurfaceStructural[site].Carbon; avgSurfMetaC[ecoregion.Index] += SiteVars.SurfaceMetabolic[site].Carbon; avgSoilStrucC[ecoregion.Index] += SiteVars.SoilStructural[site].Carbon; avgSoilMetaC[ecoregion.Index] += SiteVars.SoilMetabolic[site].Carbon; avgSOM1surfC[ecoregion.Index] += SiteVars.SOM1surface[site].Carbon; avgSOM1soilC[ecoregion.Index] += SiteVars.SOM1soil[site].Carbon; avgSOM2C[ecoregion.Index] += SiteVars.SOM2[site].Carbon; avgSOM3C[ecoregion.Index] += SiteVars.SOM3[site].Carbon; avgCohortLeafN[ecoregion.Index] += SiteVars.CohortLeafN[site]; avgCohortFRootN[ecoregion.Index] += SiteVars.CohortFRootN[site]; avgCohortWoodN[ecoregion.Index] += SiteVars.CohortWoodN[site]; avgCohortCRootN[ecoregion.Index] += SiteVars.CohortCRootN[site]; avgWoodN[ecoregion.Index] += SiteVars.SurfaceDeadWood[site].Nitrogen; avgCRootN[ecoregion.Index] += SiteVars.SoilDeadWood[site].Nitrogen; avgSurfStrucN[ecoregion.Index] += SiteVars.SurfaceStructural[site].Nitrogen; avgSurfMetaN[ecoregion.Index] += SiteVars.SurfaceMetabolic[site].Nitrogen; avgSoilStrucN[ecoregion.Index] += SiteVars.SoilStructural[site].Nitrogen; avgSoilMetaN[ecoregion.Index] += SiteVars.SoilMetabolic[site].Nitrogen; avgSOM1surfN[ecoregion.Index] += SiteVars.SOM1surface[site].Nitrogen; avgSOM1soilN[ecoregion.Index] += SiteVars.SOM1soil[site].Nitrogen; avgSOM2N[ecoregion.Index] += SiteVars.SOM2[site].Nitrogen; avgSOM3N[ecoregion.Index] += SiteVars.SOM3[site].Nitrogen; avgTotalSoilN[ecoregion.Index] += GetTotalSoilNitrogen(site); avgSurfStrucNetMin[ecoregion.Index] += SiteVars.SurfaceStructural[site].NetMineralization; avgSurfMetaNetMin[ecoregion.Index] += SiteVars.SurfaceMetabolic[site].NetMineralization; avgSoilStrucNetMin[ecoregion.Index] += SiteVars.SoilStructural[site].NetMineralization; avgSoilMetaNetMin[ecoregion.Index] += SiteVars.SoilMetabolic[site].NetMineralization; avgSOM1surfNetMin[ecoregion.Index] += SiteVars.SOM1surface[site].NetMineralization; avgSOM1soilNetMin[ecoregion.Index] += SiteVars.SOM1soil[site].NetMineralization; avgSOM2NetMin[ecoregion.Index] += SiteVars.SOM2[site].NetMineralization; avgSOM3NetMin[ecoregion.Index] += SiteVars.SOM3[site].NetMineralization; //avgNDeposition[ecoregion.Index] = ClimateRegionData.AnnualNDeposition[ecoregion]; avgStreamC[ecoregion.Index] += SiteVars.Stream[site].Carbon; avgStreamN[ecoregion.Index] += SiteVars.Stream[site].Nitrogen; //+ SiteVars.NLoss[site]; avgFireCEfflux[ecoregion.Index] += SiteVars.FireCEfflux[site]; avgFireNEfflux[ecoregion.Index] += SiteVars.FireNEfflux[site]; avgNresorbed[ecoregion.Index] += SiteVars.ResorbedN[site]; avgNuptake[ecoregion.Index] += GetSoilNuptake(site); avgNvol[ecoregion.Index] += SiteVars.Nvol[site]; avgfrassC[ecoregion.Index] += SiteVars.FrassC[site]; } foreach (IEcoregion ecoregion in PlugIn.ModelCore.Ecoregions) { if (!ecoregion.Active || ClimateRegionData.ActiveSiteCount[ecoregion] < 1) continue; primaryLog.Clear(); PrimaryLog pl = new PrimaryLog(); pl.Time = CurrentTime; pl.ClimateRegionName = ecoregion.Name; pl.ClimateRegionIndex = ecoregion.Index; pl.NumSites = ClimateRegionData.ActiveSiteCount[ecoregion]; pl.NEEC = (avgNEEc[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.SOMTC = (avgSOMtc[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.AGB = (avgAGB[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.AG_NPPC = (avgAGNPPtc[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.BG_NPPC = (avgBGNPPtc[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.Litterfall = (avgLittertc[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.AgeMortality = (avgWoodMortality[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.MineralN = (avgMineralN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.TotalN = (avgTotalN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.GrossMineralization = (avgGrossMin[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.TotalNdep = (ClimateRegionData.AnnualNDeposition[ecoregion] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.C_LiveLeaf = (avgCohortLeafC[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.C_LiveFRoot = (avgCohortFRootC[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.C_LiveWood = (avgCohortWoodC[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.C_LiveCRoot = (avgCohortCRootC[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.C_DeadWood = (avgWoodC[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.C_DeadCRoot = (avgCRootC[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.C_DeadLeaf_Struc = (avgSurfStrucC[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.C_DeadLeaf_Meta = (avgSurfMetaC[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.C_DeadFRoot_Struc = (avgSoilStrucC[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.C_DeadFRoot_Meta = (avgSoilMetaC[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.C_SOM1surf = (avgSOM1surfC[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.C_SOM1soil = (avgSOM1soilC[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.C_SOM2 = (avgSOM2C[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.C_SOM3 = (avgSOM3C[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.N_Leaf = (avgCohortLeafN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.N_FRoot = (avgCohortFRootN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.N_Wood = (avgCohortWoodN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.N_CRoot = (avgCohortCRootN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.N_DeadWood = (avgWoodN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.N_DeadCRoot = (avgCRootN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.N_DeadLeaf_Struc = (avgSurfStrucN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.N_DeadLeaf_Meta = (avgSurfMetaN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.N_DeadFRoot_Struc = (avgSoilStrucN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.N_DeadFRoot_Meta = (avgSoilMetaN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.N_SOM1surf = (avgSOM1surfN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.N_SOM1soil = (avgSOM1soilN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.N_SOM2 = (avgSOM2N[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.N_SOM3 = (avgSOM3N[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.SurfStrucNetMin = (avgSurfStrucNetMin[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.SurfMetaNetMin = (avgSurfMetaNetMin[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.SoilStrucNetMin = (avgSoilStrucNetMin[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.SoilMetaNetMin = (avgSoilMetaNetMin[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.SOM1surfNetMin = (avgSOM1surfNetMin[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.SOM1soilNetMin = (avgSOM1soilNetMin[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.SOM2NetMin = (avgSOM2NetMin[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.SOM3NetMin = (avgSOM3NetMin[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.LeachedC = (avgStreamC[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.LeachedN = (avgStreamN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.FireCEfflux = (avgFireCEfflux[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.FireNEfflux = (avgFireNEfflux[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.Nuptake = (avgNuptake[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.Nresorbed = (avgNresorbed[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.TotalSoilN = (avgTotalSoilN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.Nvol = (avgNvol[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); pl.FrassC = (avgfrassC[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); primaryLog.AddObject(pl); primaryLog.WriteToFile(); } //Reset back to zero: //These are being reset here because fire effects are handled in the first year of the //growth loop but the reporting doesn't happen until after all growth is finished. SiteVars.FireCEfflux.ActiveSiteValues = 0.0; SiteVars.FireNEfflux.ActiveSiteValues = 0.0; } public static void WriteMonthlyLogFile(int month) { double[] ppt = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] airtemp = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgNPPtc = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgTotalResp = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSoilResp = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgNEE = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] nitrogenDeposition = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] streamN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] soilWaterContent = new double[PlugIn.ModelCore.Ecoregions.Count]; foreach (IEcoregion ecoregion in PlugIn.ModelCore.Ecoregions) { ppt[ecoregion.Index] = 0.0; airtemp[ecoregion.Index] = 0.0; avgNPPtc[ecoregion.Index] = 0.0; avgTotalResp[ecoregion.Index] = 0.0; avgSoilResp[ecoregion.Index] = 0.0; avgNEE[ecoregion.Index] = 0.0; nitrogenDeposition[ecoregion.Index] = 0.0; streamN[ecoregion.Index] = 0.0; soilWaterContent[ecoregion.Index] = 0.0; } foreach (ActiveSite site in PlugIn.ModelCore.Landscape) { IEcoregion ecoregion = PlugIn.ModelCore.Ecoregion[site]; ppt[ecoregion.Index] = ClimateRegionData.AnnualWeather[ecoregion].MonthlyPrecip[month]; airtemp[ecoregion.Index] = ClimateRegionData.AnnualWeather[ecoregion].MonthlyTemp[month]; avgNPPtc[ecoregion.Index] += SiteVars.MonthlyAGNPPcarbon[site][month] + SiteVars.MonthlyBGNPPcarbon[site][month]; avgTotalResp[ecoregion.Index] += SiteVars.MonthlyHeteroResp[site][month]; avgSoilResp[ecoregion.Index] += SiteVars.MonthlySoilResp[site][month]; avgNEE[ecoregion.Index] += SiteVars.MonthlyNEE[site][month]; SiteVars.AnnualNEE[site] += SiteVars.MonthlyNEE[site][month]; nitrogenDeposition[ecoregion.Index] = ClimateRegionData.MonthlyNDeposition[ecoregion][month]; streamN[ecoregion.Index] += SiteVars.MonthlyStreamN[site][month]; soilWaterContent[ecoregion.Index] += SiteVars.MonthlySoilWaterContent[site][month]; } foreach (IEcoregion ecoregion in PlugIn.ModelCore.Ecoregions) { if (ClimateRegionData.ActiveSiteCount[ecoregion] > 0) { monthlyLog.Clear(); MonthlyLog ml = new MonthlyLog(); ml.Time = PlugIn.ModelCore.CurrentTime; ml.Month = month + 1; ml.ClimateRegionName = ecoregion.Name; ml.ClimateRegionIndex = ecoregion.Index; ml.NumSites = Convert.ToInt32(ClimateRegionData.ActiveSiteCount[ecoregion]); ml.Precipitation = ClimateRegionData.AnnualWeather[ecoregion].MonthlyPrecip[month]; ml.AirTemp = ClimateRegionData.AnnualWeather[ecoregion].MonthlyTemp[month]; ml.AvgTotalNPP_C = (avgNPPtc[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); ml.AvgHeteroRespiration = (avgTotalResp[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); ml.AvgSoilRespiration = (avgSoilResp[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); ml.avgNEE = (avgNEE[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); ml.Ndep = nitrogenDeposition[ecoregion.Index]; ml.StreamN = (streamN[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); ml.SoilWaterContent = (soilWaterContent[ecoregion.Index] / (double)ClimateRegionData.ActiveSiteCount[ecoregion]); monthlyLog.AddObject(ml); monthlyLog.WriteToFile(); } } } public static void WriteMaps() { string pathH2O = MapNames.ReplaceTemplateVars(@"NECN\Annual-water-budget-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<IntPixel> outputRaster = PlugIn.ModelCore.CreateRaster<IntPixel>(pathH2O, PlugIn.ModelCore.Landscape.Dimensions)) { IntPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (int)((SiteVars.AnnualWaterBalance[site])); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string pathANPP = MapNames.ReplaceTemplateVars(@"NECN\AG_NPP-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<IntPixel> outputRaster = PlugIn.ModelCore.CreateRaster<IntPixel>(pathANPP, PlugIn.ModelCore.Landscape.Dimensions)) { IntPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (int)((SiteVars.AGNPPcarbon[site])); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string path = MapNames.ReplaceTemplateVars(@"NECN\SOMTC-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<IntPixel> outputRaster = PlugIn.ModelCore.CreateRaster<IntPixel>(path, PlugIn.ModelCore.Landscape.Dimensions)) { IntPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (int)((SiteVars.SOM1surface[site].Carbon + SiteVars.SOM1soil[site].Carbon + SiteVars.SOM2[site].Carbon + SiteVars.SOM3[site].Carbon)); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string path2 = MapNames.ReplaceTemplateVars(@"NECN\SoilN-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<ShortPixel> outputRaster = PlugIn.ModelCore.CreateRaster<ShortPixel>(path2, PlugIn.ModelCore.Landscape.Dimensions)) { ShortPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (short)(SiteVars.MineralN[site]); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string path4 = MapNames.ReplaceTemplateVars(@"NECN\ANEE-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<ShortPixel> outputRaster = PlugIn.ModelCore.CreateRaster<ShortPixel>(path4, PlugIn.ModelCore.Landscape.Dimensions)) { ShortPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (short)(SiteVars.AnnualNEE[site] + 1000); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string path5 = MapNames.ReplaceTemplateVars(@"NECN\TotalC-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<IntPixel> outputRaster = PlugIn.ModelCore.CreateRaster<IntPixel>(path5, PlugIn.ModelCore.Landscape.Dimensions)) { IntPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (int)(Outputs.GetOrganicCarbon(site) + SiteVars.CohortLeafC[site] + SiteVars.CohortFRootC[site] + SiteVars.CohortWoodC[site] + SiteVars.CohortCRootC[site] + SiteVars.SurfaceDeadWood[site].Carbon + SiteVars.SoilDeadWood[site].Carbon); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } //} string pathLAI = MapNames.ReplaceTemplateVars(@"NECN\LAI-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<IntPixel> outputRaster = PlugIn.ModelCore.CreateRaster<IntPixel>(pathLAI, PlugIn.ModelCore.Landscape.Dimensions)) { IntPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (short)(SiteVars.LAI[site]); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string pathavailablewater = MapNames.ReplaceTemplateVars(@"NECN\AvailableWater-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<IntPixel> outputRaster = PlugIn.ModelCore.CreateRaster<IntPixel>(pathavailablewater, PlugIn.ModelCore.Landscape.Dimensions)) { IntPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (int)((SiteVars.AvailableWater[site])); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } if (PlugIn.Parameters.SmokeModelOutputs) { string pathNeedles = MapNames.ReplaceTemplateVars(@"NECN\ConiferNeedleBiomass-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<IntPixel> outputRaster = PlugIn.ModelCore.CreateRaster<IntPixel>(pathNeedles, PlugIn.ModelCore.Landscape.Dimensions)) { IntPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (int)(Main.ComputeNeedleBiomass(SiteVars.Cohorts[site])); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string pathDWD = MapNames.ReplaceTemplateVars(@"NECN\DeadWoodBiomass-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<IntPixel> outputRaster = PlugIn.ModelCore.CreateRaster<IntPixel>(pathDWD, PlugIn.ModelCore.Landscape.Dimensions)) { IntPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (int) (SiteVars.SurfaceDeadWood[site].Carbon * 2.0); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string pathLitter = MapNames.ReplaceTemplateVars(@"NECN\SurfaceLitterBiomass-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<IntPixel> outputRaster = PlugIn.ModelCore.CreateRaster<IntPixel>(pathLitter, PlugIn.ModelCore.Landscape.Dimensions)) { IntPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (int)((SiteVars.SurfaceStructural[site].Carbon + SiteVars.SurfaceMetabolic[site].Carbon) * 2.0); ; } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string pathDuff = MapNames.ReplaceTemplateVars(@"NECN\SurfaceDuffBiomass-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<IntPixel> outputRaster = PlugIn.ModelCore.CreateRaster<IntPixel>(pathDuff, PlugIn.ModelCore.Landscape.Dimensions)) { IntPixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (int)(SiteVars.SOM1surface[site].Carbon * 2.0); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } } } // --------------------------------------------------- // This method created to create maps that could be used during a subsequent new model run. // These would be read as inputs for the next model run. public static void WriteCommunityMaps() { string input_map_1 = MapNames.ReplaceTemplateVars(@"NECN-Initial-Conditions\SOM1Nsurface-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<DoublePixel> outputRaster = PlugIn.ModelCore.CreateRaster<DoublePixel>(input_map_1, PlugIn.ModelCore.Landscape.Dimensions)) { DoublePixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (double)((SiteVars.SOM1surface[site].Nitrogen)); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string input_map_2 = MapNames.ReplaceTemplateVars(@"NECN-Initial-Conditions\SOM1Nsoil-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<DoublePixel> outputRaster = PlugIn.ModelCore.CreateRaster<DoublePixel>(input_map_2, PlugIn.ModelCore.Landscape.Dimensions)) { DoublePixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (double)((SiteVars.SOM1soil[site].Nitrogen)); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string input_map_3 = MapNames.ReplaceTemplateVars(@"NECN-Initial-Conditions\SOM2N-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<DoublePixel> outputRaster = PlugIn.ModelCore.CreateRaster<DoublePixel>(input_map_3, PlugIn.ModelCore.Landscape.Dimensions)) { DoublePixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (double)((SiteVars.SOM2[site].Nitrogen)); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string input_map_4 = MapNames.ReplaceTemplateVars(@"NECN-Initial-Conditions\SOM3N-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<DoublePixel> outputRaster = PlugIn.ModelCore.CreateRaster<DoublePixel>(input_map_4, PlugIn.ModelCore.Landscape.Dimensions)) { DoublePixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (double)((SiteVars.SOM3[site].Nitrogen)); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string input_map_5 = MapNames.ReplaceTemplateVars(@"NECN-Initial-Conditions\SOM1Csoil-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<DoublePixel> outputRaster = PlugIn.ModelCore.CreateRaster<DoublePixel>(input_map_5, PlugIn.ModelCore.Landscape.Dimensions)) { DoublePixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (double)((SiteVars.SOM1soil[site].Carbon)); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string input_map_6 = MapNames.ReplaceTemplateVars(@"NECN-Initial-Conditions\SOM2C-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<DoublePixel> outputRaster = PlugIn.ModelCore.CreateRaster<DoublePixel>(input_map_6, PlugIn.ModelCore.Landscape.Dimensions)) { DoublePixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (double)((SiteVars.SOM2[site].Carbon)); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string input_map_7 = MapNames.ReplaceTemplateVars(@"NECN-Initial-Conditions\SOM3C-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<DoublePixel> outputRaster = PlugIn.ModelCore.CreateRaster<DoublePixel>(input_map_7, PlugIn.ModelCore.Landscape.Dimensions)) { DoublePixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (double)((SiteVars.SOM3[site].Carbon)); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string input_map_8 = MapNames.ReplaceTemplateVars(@"NECN-Initial-Conditions\DeadRootC-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<DoublePixel> outputRaster = PlugIn.ModelCore.CreateRaster<DoublePixel>(input_map_8, PlugIn.ModelCore.Landscape.Dimensions)) { DoublePixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (double)((SiteVars.SoilDeadWood[site].Carbon)); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } string input_map_9 = MapNames.ReplaceTemplateVars(@"NECN-Initial-Conditions\DeadRootN-{timestep}.img", PlugIn.ModelCore.CurrentTime); using (IOutputRaster<DoublePixel> outputRaster = PlugIn.ModelCore.CreateRaster<DoublePixel>(input_map_9, PlugIn.ModelCore.Landscape.Dimensions)) { DoublePixel pixel = outputRaster.BufferPixel; foreach (Site site in PlugIn.ModelCore.Landscape.AllSites) { if (site.IsActive) { pixel.MapCode.Value = (double)((SiteVars.SoilDeadWood[site].Nitrogen)); } else { // Inactive site pixel.MapCode.Value = 0; } outputRaster.WriteBufferPixel(); } } } //--------------------------------------------------------------------- private static double GetTotalNitrogen(Site site) { double totalN = + SiteVars.CohortLeafN[site] + SiteVars.CohortFRootN[site] + SiteVars.CohortWoodN[site] + SiteVars.CohortCRootN[site] + SiteVars.MineralN[site] + SiteVars.SurfaceDeadWood[site].Nitrogen + SiteVars.SoilDeadWood[site].Nitrogen + SiteVars.SurfaceStructural[site].Nitrogen + SiteVars.SoilStructural[site].Nitrogen + SiteVars.SurfaceMetabolic[site].Nitrogen + SiteVars.SoilMetabolic[site].Nitrogen + SiteVars.SOM1surface[site].Nitrogen + SiteVars.SOM1soil[site].Nitrogen + SiteVars.SOM2[site].Nitrogen + SiteVars.SOM3[site].Nitrogen ; return totalN; } private static double GetTotalSoilNitrogen(Site site) { double totalsoilN = +SiteVars.MineralN[site] + SiteVars.SurfaceStructural[site].Nitrogen + SiteVars.SoilStructural[site].Nitrogen + SiteVars.SurfaceMetabolic[site].Nitrogen + SiteVars.SoilMetabolic[site].Nitrogen + SiteVars.SOM1surface[site].Nitrogen + SiteVars.SOM1soil[site].Nitrogen + SiteVars.SOM2[site].Nitrogen + SiteVars.SOM3[site].Nitrogen; ; return totalsoilN; } //--------------------------------------------------------------------- public static double GetOrganicCarbon(Site site) { double totalC = SiteVars.SOM1surface[site].Carbon + SiteVars.SOM1soil[site].Carbon + SiteVars.SOM2[site].Carbon + SiteVars.SOM3[site].Carbon ; return totalC; } //--------------------------------------------------------------------- private static double GetSoilNuptake(ActiveSite site) { double soilNuptake = SiteVars.TotalNuptake[site] ; return soilNuptake; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Web.Security; using Stardust.Core.Security; using Stardust.Interstellar.ConfigurationReader; using Stardust.Nexus.Business.CahceManagement; using Stardust.Nexus.Repository; using Stardust.Nucleus.Extensions; using Stardust.Particles; using Stardust.Particles.Collection; namespace Stardust.Nexus.Business { public class ConfigSetTask : IConfigSetTask { private readonly ICacheManagementService cacheController; private readonly IEnvironmentTasks environmentTasks; private ConfigurationContext Repository; public ConfigSetTask(IRepositoryFactory repositoryFactory, IEnvironmentTasks environmentTasks) { this.cacheController = cacheController; this.environmentTasks = environmentTasks; Repository = repositoryFactory.GetRepository(); Repository.SavingChanges += SavingChanges; } private void SavingChanges(object sender, EventArgs e) { try { foreach (var brightstarEntityObject in from to in Repository.TrackedObjects where to.Implements<IEnvironment>() select to as IEnvironment) { var key = GetCacheKey(brightstarEntityObject.ConfigSet.Id, brightstarEntityObject.Name); ConfigurationSet old; ConfigSetCache.TryRemove(key, out old); } } catch (Exception) { // ignored } } ~ConfigSetTask() { Dispose(false); } public bool CreateConfigSet(string name, string systemName, IConfigSet parent) { var configSets = from cs in Repository.ConfigSets where cs.Name == name && cs.System == systemName select cs; if (configSets.Count() != 0) throw new AmbiguousMatchException(string.Format("Config set '{0}\\{1}' already exists", name, systemName)); if (parent.IsNull()) { configSets = from cs in Repository.ConfigSets where cs.System == systemName select cs; if (configSets.Count() != 0) throw new AmbiguousMatchException(string.Format("Config set '{0}\\{1}'... system {1} already exists", name, systemName)); } var configSet = Repository.ConfigSets.Create(); if (parent.IsInstance()) { foreach (var administrator in parent.Administrators) { configSet.Administrators.Add(administrator); } } else { if (ConfigReaderFactory.CurrentUser != null) configSet.Administrators.Add(ConfigReaderFactory.CurrentUser); } configSet.Name = name; configSet.Created = DateTime.UtcNow; configSet.System = systemName; configSet.LastUpdate = DateTime.UtcNow; CreateEncryptionKey(configSet); Repository.SaveChanges(); if (parent.IsInstance()) { configSet.ParentConfigSet = parent; foreach (var serviceDescription in parent.Services) { var c = serviceDescription.CreateChild(Repository, ref configSet); configSet.Services.Add(c); Repository.SaveChanges(); } foreach (var serviceHostSettingse in parent.ServiceHosts) { var hostChild = serviceHostSettingse.CreateChild(Repository, ref configSet); configSet.ServiceHosts.Add(hostChild); Repository.SaveChanges(); } foreach (var environment in parent.Environments) { var child = environment.CreateChild(Repository, ref configSet); configSet.Environments.Add(child); Repository.SaveChanges(); } Repository.SaveChanges(); } return true; } private void CreateEncryptionKey(IConfigSet configSet) { var encrytptionKey = Repository.SiteEncryptionss.Create(); encrytptionKey.Site = configSet; var key = UniqueIdGenerator.CreateNewId(26); var settings = Repository.Settingss.Single(); var masterKey = MachineKey.Unprotect(Convert.FromBase64String(settings.MasterEncryptionKey)).GetStringFromArray(); encrytptionKey.SiteEncryptionKey = key.Encrypt(new EncryptionKeyContainer(masterKey)); Repository.Settingss.Single().SiteEncryptions.Add(encrytptionKey); } public IEndpoint CreateEndpoint(IServiceDescription service, string endpointname, List<string> parameters = null) { var endpoint = service.CreateEndpoint(Repository, endpointname, false, parameters); endpoint.ServiceDescription.ConfigSet.LastUpdate = DateTime.UtcNow; Repository.SaveChanges(); return endpoint; } public void CreateFromTextConfigStoreFile(ConfigurationSet configSet) { var newSet = Repository.ConfigSets.Create(); newSet.Administrators.Add(ConfigReaderFactory.CurrentUser); newSet.Name = configSet.SetName; newSet.System = configSet.SetName; newSet.Created = DateTime.UtcNow; foreach (var e in configSet.Environments) { var env = newSet.CreateEnvironment(Repository, e.EnvironmentName, true); foreach (var p in e.Parameters) { var param = env.CreateParameters(Repository, p.Name, p.BinaryValue.ContainsElements()); param.ItemValue = p.Value; if (p.BinaryValue.ContainsElements()) { param.BinaryValue = p.BinaryValue; param.SetValue(Convert.ToBase64String(p.BinaryValue)); } } env.AddIdentitySettingsToEnvironment(Repository, (from s in configSet.Services where s.IdentitySettings != null select s.IdentitySettings).FirstOrDefault()); } foreach (var s in configSet.Endpoints) { var service = newSet.CreateService(Repository, s.ServiceName); Repository.SaveChanges(); foreach (var ep in s.Endpoints) { var endpoint = service.CreateEndpoint(Repository, ep.BindingType, true); endpoint.SetFromRawData(ep, Repository); } service.ClientEndpointValue = s.ActiveEndpoint; } if (configSet.Services.IsInstance()) { foreach (var host in configSet.Services) { try { var newHost = newSet.CreateServiceHost(Repository, host.ServiceName); foreach (var configParameter in host.Parameters) { var param = newHost.CreateParameter(Repository, configParameter.Name, configParameter.BinaryValue.ContainsElements(), false); param.ItemValue = configParameter.BinaryValue.ContainsElements() ? Convert.ToBase64String(configParameter.BinaryValue) : configParameter.Value; param.BinaryValue = configParameter.BinaryValue; } } catch (Exception ex) { throw new InvalidDataException(string.Format("Unable to create {0}: {1}", host.ServiceName, ex.Message), ex); } } } newSet.LastUpdate = DateTime.UtcNow; Repository.SaveChanges(); } public IServiceDescription CreateService(IConfigSet cs, string servicename) { var service = cs.CreateService(Repository, servicename); service.ConfigSet.LastUpdate = DateTime.UtcNow; Repository.SaveChanges(); return service; } public void Dispose() { Dispose(true); } public IEnumerable<IConfigSet> GetAllConfitSets() { if (ConfigReaderFactory.CurrentUser.AdministratorType != AdministratorTypes.SystemAdmin) return ConfigReaderFactory.CurrentUser.ConfigSet.ToList(); var configSets = from cs in Repository.ConfigSets orderby cs.Id select cs; return configSets.ToList(); } public IConfigSet GetConfigSet(string name, string systemName) { var configSet = GetConfigSetsWithName(name, systemName); return configSet.Single(); } public IConfigSet GetConfigSet(string id) { var configSets = from cs in Repository.ConfigSets where cs.Id == id select cs; var configSet = configSets.Single(); if (configSet.ReaderKey.IsNullOrWhiteSpace()) { configSet.SetReaderKey(UniqueIdGenerator.CreateNewId(20).Encrypt(KeySalt)); UpdateConfigSet(configSet); } foreach (var env in configSet.Environments) { if (env.ReaderKey.IsNullOrWhiteSpace()) { env.SetReaderKey(UniqueIdGenerator.CreateNewId(20).Encrypt(KeySalt)); environmentTasks.UpdateEnvironment(env); } } return configSet; } public string GenerateReaderKey(string id) { var configSets = from cs in Repository.ConfigSets where cs.Id == id select cs; var configSet = configSets.Single(); configSet.ReaderKey = UniqueIdGenerator.CreateNewId(20).Encrypt(KeySalt); UpdateConfigSet(configSet); return configSet.ReaderKey; } public string GenerateReaderKey(IConfigSet configSet) { configSet.ReaderKey = UniqueIdGenerator.CreateNewId(20).Encrypt(KeySalt); return configSet.ReaderKey; } public List<string> GetAllConfigSetNames() { return Repository.ConfigSets.Select(c => c.Id).ToList(); } public void DeleteConfigSet(IConfigSet cs) { Repository.DeleteObject(cs); Repository.SaveChanges(); } public void DeleteServiceHost(IServiceHostSettings host) { Repository.DeleteObject(host); Repository.SaveChanges(); } private static EncryptionKeyContainer KeySalt { get { return new EncryptionKeyContainer("makeItHarderTowrite"); } } public ConfigurationSet GetConfigSetData(string id, string environment) { ConfigurationSet set; if (!TryGetSetFromCache(id, environment.ToLowerInvariant(), out set)) { bool doSave; var configSet = GetConfigSet(id); set = configSet.GetRawConfigData(environment, out doSave); if (doSave) UpdateConfigSet(configSet); AddToCache(id, environment, set); } return set; } private void AddToCache(string id, string environment, ConfigurationSet set) { ConfigSetCache.AddOrUpdate(GetCacheKey(id, environment), set); } private static ConcurrentDictionary<string, ConfigurationSet> ConfigSetCache = new ConcurrentDictionary<string, ConfigurationSet>(new Dictionary<string, ConfigurationSet>()); private bool TryGetSetFromCache(string id, string environment, out ConfigurationSet set) { ConfigurationSet item; if (!ConfigSetCache.TryGetValue(GetCacheKey(id, environment), out item)) { set = null; return false; } if (item.LastUpdated <= GetConfigSet(id).LastUpdate) { set = null; return false; } set = item; return true; } private static string GetCacheKey(string id, string environment) { return string.Format("{0}[{1}]", id, environment); } public IEndpoint GetEndpoint(string id) { try { var ep = Repository.Endpoints.Single(x => x.Id == id); if (ep.Name == "custom") { foreach (var endpointParameter in ep.Parameters) { endpointParameter.ConfigurableForEachEnvironment = true; endpointParameter.IsPerService = true; } Repository.SaveChanges(); } return ep; } catch (Exception ex) { throw new ArgumentException("Could not find item with id: " + id, "id", ex); } } public IEndpointParameter GetEnpointParameter(string id) { return Repository.EndpointParameters.Single(x => x.Id == id); } public IServiceDescription GetService(string id) { try { return Repository.ServiceDescriptions.Single(x => x.Id == id); } catch (Exception ex) { throw new ArgumentException("Could not find item with id: " + id, "id", ex); } } public void UpdateEndpointParameter(IEndpointParameter parameter) { parameter.Endpoint.ServiceDescription.ConfigSet.LastUpdate = DateTime.UtcNow; if (parameter.ConfigurableForEachEnvironment) { foreach (var environment in parameter.Endpoint.ServiceDescription.ConfigSet.Environments) { var param = environment.SubstitutionParameters.SingleOrDefault(p=>p.Name== parameter.Endpoint.ServiceDescription.Name+"_"+parameter.Name); if(param!=null&&!parameter.SubstitutionParameters.Contains(param)) parameter.SubstitutionParameters.Add(param); } if (parameter.Endpoint.ServiceDescription.ServiceHost != null) { var hostParam=parameter.Endpoint.ServiceDescription.ServiceHost.Parameters.SingleOrDefault(p => p.Name == parameter.Name); if (hostParam != null) { if(!parameter.HostParameters.Contains(hostParam)) parameter.HostParameters.Add(hostParam); } } } Repository.SaveChanges(); } public void UpdateService(IServiceDescription service) { service.ConfigSet.LastUpdate = DateTime.UtcNow; Repository.SaveChanges(); } public IServiceHostSettings GetServiceHost(string id) { return Repository.ServiceHostSettingss.Single(x => x.Id == id); } public IServiceHostSettings CreateServiceHost(IConfigSet configSet, string name) { var serviceHost = configSet.CreateServiceHost(Repository, name); configSet.LastUpdate = DateTime.UtcNow; Repository.SaveChanges(); return serviceHost; } public IServiceHostParameter CreateServiceHostParameter(IServiceHostSettings serviceHost, string name, bool isSecureString, string itemValue, bool isEnvironmental) { var param = serviceHost.CreateParameter(Repository, name, isSecureString, isEnvironmental); param.SetValue(itemValue); param.ServiceHost.ConfigSet.LastUpdate = DateTime.UtcNow; if (param.IsEnvironmental) { foreach (var environment in serviceHost.ConfigSet.Environments) { var keyName = serviceHost.Name + "_" + param.Name; var envParam = environment.SubstitutionParameters.SingleOrDefault(p => p.Name == keyName); if (envParam == null) { envParam = environment.CreateSubstitutionParameters(Repository, keyName); } if(param.SubstitutionParameters==null) param.SubstitutionParameters=new List<ISubstitutionParameter>(); if (!param.SubstitutionParameters.Contains(envParam)) { param.SubstitutionParameters.Add(envParam); } } } Repository.SaveChanges(); return param; } public IServiceHostParameter GetHostParameter(string id) { return Repository.ServiceHostParameters.Single(x => x.Id == id); } public void UpdateHostParameter(IServiceHostParameter serviceHostParameter) { serviceHostParameter.ServiceHost.ConfigSet.LastUpdate = DateTime.UtcNow; if (serviceHostParameter.IsEnvironmental) { foreach (var environment in serviceHostParameter.ServiceHost.ConfigSet.Environments) { var paramName = string.Format("{0}_{1}", serviceHostParameter.ServiceHost.Name, serviceHostParameter.Name); var subParam = environment.SubstitutionParameters.SingleOrDefault(sp => sp.Name == paramName); if (subParam.IsNull()) subParam=environment.CreateSubstitutionParameters(Repository, paramName); if (serviceHostParameter.SubstitutionParameters == null) serviceHostParameter.SubstitutionParameters = new List<ISubstitutionParameter>(); if (!serviceHostParameter.SubstitutionParameters.Contains(subParam)) { serviceHostParameter.SubstitutionParameters.Add(subParam); } } } Repository.SaveChanges(); } public void UpdateAdministrators(ICollection<IConfigUser> administrators) { Repository.SaveChanges(); } public void CreateEndpointParameter(string item, string name, string itemValue, bool isSubstiturtionParameter) { var endpoint = GetEndpoint(item); endpoint.AddParameter(Repository, name, itemValue, isSubstiturtionParameter); Repository.SaveChanges(); } public void DeleteEndpoint(IEndpoint endpoint) { Repository.DeleteObject(endpoint); Repository.SaveChanges(); } public ConfigurationSettings InitializeDatacenter(string id, ConfigurationSettings settings) { var configSet = GetConfigSet(id); var env = environmentTasks.GetEnvironment(configSet.Id + "-" + settings.Environment); env.CreateDataCenterKeyProperties(this.Repository, settings); Repository.SaveChanges(); var subPar = env.EnsureDataCentersKey(Repository, settings); subPar.AddNewDataCenter(Repository, settings); env.ConfigSet.GetUris(Repository, settings); return settings; } public ConfigurationSettings PublishDatacenter(string id, ConfigurationSettings settings) { //var configSet = GetConfigSet(id); var env = environmentTasks.GetEnvironment(id + "-" + settings.Environment); if (settings.DatabaseKeyName.ContainsCharacters()) { var database = environmentTasks.GetEnvironmentParameter(env.Id + "-" + settings.DatabaseKeyName); database.SetValue(settings.DatabaseAccessKey); environmentTasks.UpdateEnvironmentParameter(database); } if (settings.ReplicationBusKeyName.ContainsCharacters()) { var replicationBus = environmentTasks.GetEnvironmentParameter(env.Id + "-" + settings.ReplicationBusKeyName); replicationBus.SetValue(settings.ReplicationBusAccessKey); environmentTasks.UpdateEnvironmentParameter(replicationBus); } if (settings.ServiceBusKeyName.ContainsCharacters()) { var database = environmentTasks.GetEnvironmentParameter(env.Id + "-" + settings.ServiceBusKeyName); database.SetValue(settings.ServiceBusAccessKey); environmentTasks.UpdateEnvironmentParameter(database); } Repository.SaveChanges(); return settings; } public void UpdateServiceHost(IServiceHostSettings host) { Repository.SaveChanges(); } public void UpdateConfigSet(IConfigSet configSet) { Repository.SaveChanges(); } public void DeleteService(IServiceDescription service) { Repository.DeleteObject(service); Repository.SaveChanges(); } private void Dispose(bool disposing) { if (disposing) GC.SuppressFinalize(this); if (Repository != null) Repository.Dispose(); } private IQueryable<IConfigSet> GetConfigSetsWithName(string name, string systemName) { var configSet = from cs in Repository.ConfigSets where cs.Name == name && cs.System == systemName select cs; return configSet; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Reflection; using Hydra.Framework; namespace Hydra.SharedCache.Common { [Serializable] public class ServerStats { #region Properties private string name; // // ********************************************************************** /// <summary> /// Gets/sets the Name /// </summary> /// <value>The name.</value> // ********************************************************************** // public string Name { [System.Diagnostics.DebuggerStepThrough] get { return this.name; } [System.Diagnostics.DebuggerStepThrough] set { this.name = value; } } private long amountOfObjects; // // ********************************************************************** /// <summary> /// Gets/sets the AmountOfObjects /// </summary> /// <value>The amount of objects.</value> // ********************************************************************** // public long AmountOfObjects { [System.Diagnostics.DebuggerStepThrough] get { return this.amountOfObjects; } [System.Diagnostics.DebuggerStepThrough] set { this.amountOfObjects = value; } } private long cacheSize; // // ********************************************************************** /// <summary> /// Gets/sets the CacheSize /// </summary> /// <value>The size of the cache.</value> // ********************************************************************** // public long CacheSize { [System.Diagnostics.DebuggerStepThrough] get { return this.cacheSize; } [System.Diagnostics.DebuggerStepThrough] set { this.cacheSize = value; } } private Dictionary<string, long> usageList; // // ********************************************************************** /// <summary> /// Gets/sets the Long&gt; NodeUsageList /// </summary> /// <value>The usage list.</value> // ********************************************************************** // public Dictionary<string, long> UsageList { [System.Diagnostics.DebuggerStepThrough] get { return this.usageList; } [System.Diagnostics.DebuggerStepThrough] set { this.usageList = value; } } #endregion // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="ServerStats"/> class. /// </summary> // ********************************************************************** // public ServerStats() { } // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="ServerStats"/> class. /// </summary> /// <param name="nodeName">Name of the node.</param> /// <param name="nodeAmountOfObjects">The node amount of objects.</param> /// <param name="nodeSize">Size of the node.</param> /// <param name="nodeUsageList">The node usage list.</param> // ********************************************************************** // public ServerStats(string nodeName, long nodeAmountOfObjects, long nodeSize, Dictionary<string, long> nodeUsageList) { this.name = nodeName; this.amountOfObjects = nodeAmountOfObjects; this.cacheSize = nodeSize; this.usageList = nodeUsageList; } } // // ********************************************************************** /// <summary> /// Contains statistical information /// </summary> // ********************************************************************** // [Serializable] public class LBSStatistic { #region API // // ********************************************************************** /// <summary>Count the amount of success objects from cache</summary> // ********************************************************************** // internal long apiHitSuccess = 0; // // ********************************************************************** /// <summary>Count the amount of failed objects from cache</summary> // ********************************************************************** // internal long apiHitFailed = 0; // // ********************************************************************** /// <summary>Counts the amount of total added objects per instance</summary> // ********************************************************************** // internal long apiCounterAdd = 0; // // ********************************************************************** /// <summary>Counts the amount of total received objects per instance</summary> // ********************************************************************** // internal long apiCounterGet = 0; // // ********************************************************************** /// <summary>Counts the amount of total removed objects per instance</summary> // ********************************************************************** // internal long apiCounterRemove = 0; // // ********************************************************************** /// <summary>Counts the amount of statistics calls per instance</summary> // ********************************************************************** // internal long apiCounterStatistic = 0; // // ********************************************************************** /// <summary>amount of success calls</summary> // ********************************************************************** // internal long apiCounterSuccess = 0; // // ********************************************************************** /// <summary>amount of failed calls</summary> // ********************************************************************** // internal long apiCounterFailed = 0; // // ********************************************************************** /// <summary> /// Gets the API hit success. /// </summary> /// <value>The API hit success.</value> // ********************************************************************** // public long ApiHitSuccess { get { return this.apiHitSuccess; } } // // ********************************************************************** /// <summary> /// Gets the API hit failed. /// </summary> /// <value>The API hit failed.</value> // ********************************************************************** // public long ApiHitFailed { get { return this.apiHitFailed; } } // // ********************************************************************** /// <summary> /// Gets the API counter add. /// </summary> /// <value>The API counter add.</value> // ********************************************************************** // public long ApiCounterAdd { get { return this.apiCounterAdd; } } // // ********************************************************************** /// <summary> /// Gets the API counter get. /// </summary> /// <value>The API counter get.</value> // ********************************************************************** // public long ApiCounterGet { get { return this.apiCounterGet; } } // // ********************************************************************** /// <summary> /// Gets the API counter remove. /// </summary> /// <value>The API counter remove.</value> // ********************************************************************** // public long ApiCounterRemove { get { return this.apiCounterRemove; } } // // ********************************************************************** /// <summary> /// Gets the API counter statistic. /// </summary> /// <value>The API counter statistic.</value> // ********************************************************************** // public long ApiCounterStatistic { get { return this.apiCounterStatistic; } } // // ********************************************************************** /// <summary> /// Gets the API counter success. /// </summary> /// <value>The API counter success.</value> // ********************************************************************** // public long ApiCounterSuccess { get { return this.apiCounterSuccess; } } // // ********************************************************************** /// <summary> /// Gets the API counter failed. /// </summary> /// <value>The API counter failed.</value> // ********************************************************************** // public long ApiCounterFailed { get { return this.apiCounterFailed; } } #endregion API // // ********************************************************************** /// <summary> /// Contains server information fore specific node /// </summary> // ********************************************************************** // public List<ServerStats> NodeDate = new List<ServerStats>(); // // ********************************************************************** /// <summary>the amount of objects the service contains.</summary> // ********************************************************************** // private long serviceAmountOfObjects = 0; // // ********************************************************************** /// <summary>current total RAM which is needed.</summary> // ********************************************************************** // private long serviceTotalSize = 0; // // ********************************************************************** /// <summary>enables possibility to receive the usage of cache items</summary> // ********************************************************************** // private Dictionary<string, long> serviceUsageList = null; // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="T:LBSStatistic"/> class. /// </summary> // ********************************************************************** // public LBSStatistic() { } // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="T:LBSStatistic"/> class. /// </summary> /// <param name="add">The add. A <see cref="T:System.Int64"/> Object.</param> /// <param name="get">The get. A <see cref="T:System.Int64"/> Object.</param> /// <param name="remove">The remove. A <see cref="T:System.Int64"/> Object.</param> /// <param name="stat">The stat. A <see cref="T:System.Int64"/> Object.</param> /// <param name="failed">The failed.</param> /// <param name="success">The success.</param> /// <param name="amount">The amount. A <see cref="T:System.Int64"/> Object.</param> /// <param name="srvSize">Size of the SRV.</param> // ********************************************************************** // public LBSStatistic(long add, long get, long remove, long stat, long failed, long success, long amount, long srvSize) { this.apiCounterAdd = add; this.apiCounterGet = get; this.apiCounterRemove = remove; this.apiCounterStatistic = stat; this.apiHitFailed = failed; this.apiHitSuccess = success; if (amount > 0) this.serviceAmountOfObjects = amount; if (srvSize > 0) this.serviceTotalSize = srvSize; if (serviceUsageList == null) serviceUsageList = new Dictionary<string, long>(); } // // ********************************************************************** /// <summary> /// Gets the get hit ratio. /// </summary> /// <value>The get hit ratio.</value> // ********************************************************************** // public long GetHitRatio { get { // // prevent DivideByZeroException // if ((apiHitFailed + apiHitSuccess) == 0) { return 0; } return (apiHitSuccess * 100 / (apiHitFailed + apiHitSuccess)); } } // // ********************************************************************** /// <summary> /// Gets or sets the service amount of objects. /// </summary> /// <value>The service amount of objects.</value> // ********************************************************************** // public long ServiceAmountOfObjects { [System.Diagnostics.DebuggerStepThrough] set { this.serviceAmountOfObjects = value; } [System.Diagnostics.DebuggerStepThrough] get { return this.serviceAmountOfObjects; } } // // ********************************************************************** /// <summary> /// Gets or sets the total size of the service. /// </summary> /// <value>The total size of the service.</value> // ********************************************************************** // public long ServiceTotalSize { [System.Diagnostics.DebuggerStepThrough] set { this.serviceTotalSize = value; } [System.Diagnostics.DebuggerStepThrough] get { return this.serviceTotalSize; } } // // ********************************************************************** /// <summary> /// Gets/sets the ServiceUsageList /// </summary> /// <value>The service usage list.</value> // ********************************************************************** // public Dictionary<string, long> ServiceUsageList { [System.Diagnostics.DebuggerStepThrough] get { return this.serviceUsageList; } [System.Diagnostics.DebuggerStepThrough] set { this.serviceUsageList = value; } } // // ********************************************************************** /// <summary> /// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>. /// </summary> /// <returns> /// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>. /// </returns> // ********************************************************************** // public override string ToString() { if (Handler.NetworkMessage.countTransferDataToServer == 0) { return @"Run first some client / server interactions before you call the statistics [Send Data To Servers is 0]"; } if (Handler.NetworkMessage.countTransferDataFromServer == 0) { return @"Run first some client / server interactions before you call the statistics [Receive Data From Servers is 0]"; } string serviceUsageListOutput = string.Empty + Environment.NewLine; if (this.serviceUsageList != null && serviceUsageList.Count > 0) { int cntr = 0; foreach (KeyValuePair<string, long> kvp in this.serviceUsageList) { serviceUsageListOutput += string.Format(@" Key: {0} - Hits: {1}", kvp.Key, kvp.Value ) + Environment.NewLine; ++cntr; if (cntr >= 20) { break; } } } // // calculate hit ratio // long hitratio = 0; if (apiHitFailed == 0) { hitratio = 100; } else { hitratio = apiHitSuccess * 100 / (apiHitFailed + apiHitSuccess); } string msg = string.Format( Environment.NewLine + Environment.NewLine + "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * " + Environment.NewLine + "Statistic for LBSView Shared Cache API and Service;" + Environment.NewLine + "indeXus.Net API Data: " + Environment.NewLine + " {0,7} objects have been added." + Environment.NewLine + " {1,7} objects have been received." + Environment.NewLine + " {2,7} objects have been removed." + Environment.NewLine + " {3,7} statistics have been called." + Environment.NewLine + "indeXus.Net Shared Service Data: " + Environment.NewLine + " {4,7} items cache contains currently." + Environment.NewLine + " {5,7}kb contains the cache currently." + Environment.NewLine + " Hit Stats for key's (limited list to top 20 keys - if empty then are no key's available in cache!)" + Environment.NewLine + " {6}" + Environment.NewLine + "Network Data: " + Environment.NewLine + " {7,7} MB have been transferred to server." + Environment.NewLine + " {8,7} MB have been received from server." + Environment.NewLine + " {9,7} transfers succeeded." + Environment.NewLine + " {10,7} transfers failed." + Environment.NewLine + " {11,7}% are successfully." + Environment.NewLine + Environment.NewLine + "Overall Hitrate: " + Environment.NewLine + " {12,7} are successfully." + Environment.NewLine + " {13,7} are failed." + Environment.NewLine + " {14,7}% Hit Ratio" + Environment.NewLine + "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * " + Environment.NewLine + "* Stat Output date: {15:f} *" + Environment.NewLine + "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * " + Environment.NewLine, /*0*/apiCounterAdd, /*1*/apiCounterGet, /*2*/apiCounterRemove, /*3*/apiCounterStatistic, /*4*/serviceAmountOfObjects, /*5*/serviceTotalSize > 0 ? serviceTotalSize / 1024 : 0, /*6*/serviceUsageListOutput, /*7*/Handler.NetworkMessage.countTransferDataToServer > 0 ? Handler.NetworkMessage.countTransferDataToServer / (1024 * 1024) : 0, /*8*/Handler.NetworkMessage.countTransferDataFromServer > 0 ? Handler.NetworkMessage.countTransferDataFromServer / (1024 * 1024) : 0, /*9*/apiCounterSuccess, /*10*/apiCounterFailed, /*11*/apiCounterSuccess > 0 ? apiCounterSuccess * 100 / (apiCounterFailed + apiCounterSuccess) : -1, /*12*/apiHitSuccess, /*13*/apiHitFailed, /*14*/hitratio, /*15*/DateTime.Now ); return msg; } // // ********************************************************************** /// <summary> /// Same like ToString, used within Notify Application /// </summary> /// <returns> /// A formatted <see cref="string"/> object. /// </returns> // ********************************************************************** // public string ToNotify() { string result = string.Empty; result = string.Format( " - {0} items cache contains currently." + Environment.NewLine + " - {1} kb contains the cache currently." + Environment.NewLine, serviceAmountOfObjects, serviceTotalSize / 1024); return result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Threading; namespace System.Linq.Expressions { /// <summary> /// Represents a block that contains a sequence of expressions where variables can be defined. /// </summary> [DebuggerTypeProxy(typeof(Expression.BlockExpressionProxy))] public class BlockExpression : Expression { /// <summary> /// Gets the expressions in this block. /// </summary> public ReadOnlyCollection<Expression> Expressions { get { return GetOrMakeExpressions(); } } /// <summary> /// Gets the variables defined in this block. /// </summary> public ReadOnlyCollection<ParameterExpression> Variables { get { return GetOrMakeVariables(); } } /// <summary> /// Gets the last expression in this block. /// </summary> public Expression Result { get { Debug.Assert(ExpressionCount > 0); return GetExpression(ExpressionCount - 1); } } internal BlockExpression() { } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitBlock(this); } /// <summary> /// Returns the node type of this Expression. Extension nodes should return /// ExpressionType.Extension when overriding this method. /// </summary> /// <returns>The <see cref="ExpressionType"/> of the expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Block; } } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public override Type Type { get { return GetExpression(ExpressionCount - 1).Type; } } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="variables">The <see cref="Variables" /> property of the result.</param> /// <param name="expressions">The <see cref="Expressions" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public BlockExpression Update(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) { if (variables == Variables && expressions == Expressions) { return this; } return Expression.Block(Type, variables, expressions); } internal virtual Expression GetExpression(int index) { throw ContractUtils.Unreachable; } internal virtual int ExpressionCount { get { throw ContractUtils.Unreachable; } } internal virtual ReadOnlyCollection<Expression> GetOrMakeExpressions() { throw ContractUtils.Unreachable; } internal virtual ParameterExpression GetVariable(int index) { throw ContractUtils.Unreachable; } internal virtual int VariableCount { get { return 0; } } internal virtual ReadOnlyCollection<ParameterExpression> GetOrMakeVariables() { return EmptyReadOnlyCollection<ParameterExpression>.Instance; } /// <summary> /// Makes a copy of this node replacing the parameters/args with the provided values. The /// shape of the parameters/args needs to match the shape of the current block - in other /// words there should be the same # of parameters and args. /// /// parameters can be null in which case the existing parameters are used. /// /// This helper is provided to allow re-writing of nodes to not depend on the specific optimized /// subclass of BlockExpression which is being used. /// </summary> internal virtual BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { throw ContractUtils.Unreachable; } /// <summary> /// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T. /// /// This is similar to the ReturnReadOnly which only takes a single argument. This version /// supports nodes which hold onto 5 Expressions and puts all of the arguments into the /// ReadOnlyCollection. /// /// Ultimately this means if we create the readonly collection we will be slightly more wasteful as we'll /// have a readonly collection + some fields in the type. The DLR internally avoids accessing anything /// which would force the readonly collection to be created. /// /// This is used by BlockExpression5 and MethodCallExpression5. /// </summary> internal static ReadOnlyCollection<Expression> ReturnReadOnlyExpressions(BlockExpression provider, ref object collection) { Expression tObj = collection as Expression; if (tObj != null) { // otherwise make sure only one readonly collection ever gets exposed Interlocked.CompareExchange( ref collection, new ReadOnlyCollection<Expression>(new BlockExpressionList(provider, tObj)), tObj ); } // and return what is not guaranteed to be a readonly collection return (ReadOnlyCollection<Expression>)collection; } } #region Specialized Subclasses internal sealed class Block2 : BlockExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1; // storage for the 2nd argument. internal Block2(Expression arg0, Expression arg1) { _arg0 = arg0; _arg1 = arg1; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; default: throw new InvalidOperationException(); } } internal override int ExpressionCount { get { return 2; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args.Length == 2); Debug.Assert(variables == null || variables.Count == 0); return new Block2(args[0], args[1]); } } internal sealed class Block3 : BlockExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1, _arg2; // storage for the 2nd and 3rd arguments. internal Block3(Expression arg0, Expression arg1, Expression arg2) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; case 2: return _arg2; default: throw new InvalidOperationException(); } } internal override int ExpressionCount { get { return 3; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args.Length == 3); Debug.Assert(variables == null || variables.Count == 0); return new Block3(args[0], args[1], args[2]); } } internal sealed class Block4 : BlockExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1, _arg2, _arg3; // storarg for the 2nd, 3rd, and 4th arguments. internal Block4(Expression arg0, Expression arg1, Expression arg2, Expression arg3) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; case 2: return _arg2; case 3: return _arg3; default: throw new InvalidOperationException(); } } internal override int ExpressionCount { get { return 4; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args.Length == 4); Debug.Assert(variables == null || variables.Count == 0); return new Block4(args[0], args[1], args[2], args[3]); } } internal sealed class Block5 : BlockExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1, _arg2, _arg3, _arg4; // storage for the 2nd - 5th args. internal Block5(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; _arg4 = arg4; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; case 2: return _arg2; case 3: return _arg3; case 4: return _arg4; default: throw new InvalidOperationException(); } } internal override int ExpressionCount { get { return 5; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args.Length == 5); Debug.Assert(variables == null || variables.Count == 0); return new Block5(args[0], args[1], args[2], args[3], args[4]); } } internal class BlockN : BlockExpression { private IList<Expression> _expressions; // either the original IList<Expression> or a ReadOnlyCollection if the user has accessed it. internal BlockN(IList<Expression> expressions) { Debug.Assert(expressions.Count != 0); _expressions = expressions; } internal override Expression GetExpression(int index) { Debug.Assert(index >= 0 && index < _expressions.Count); return _expressions[index]; } internal override int ExpressionCount { get { return _expressions.Count; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnly(ref _expressions); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(variables == null || variables.Count == 0); return new BlockN(args); } } internal class ScopeExpression : BlockExpression { private IList<ParameterExpression> _variables; // list of variables or ReadOnlyCollection if the user has accessed the readonly collection internal ScopeExpression(IList<ParameterExpression> variables) { _variables = variables; } internal override int VariableCount { get { return _variables.Count; } } internal override ParameterExpression GetVariable(int index) { return _variables[index]; } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeVariables() { return ReturnReadOnly(ref _variables); } protected IList<ParameterExpression> VariablesList { get { return _variables; } } // Used for rewrite of the nodes to either reuse existing set of variables if not rewritten. internal IList<ParameterExpression> ReuseOrValidateVariables(ReadOnlyCollection<ParameterExpression> variables) { if (variables != null && variables != VariablesList) { // Need to validate the new variables (uniqueness, not byref) ValidateVariables(variables, "variables"); return variables; } else { return VariablesList; } } } internal sealed class Scope1 : ScopeExpression { private object _body; internal Scope1(IList<ParameterExpression> variables, Expression body) : base(variables) { _body = body; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_body); default: throw new InvalidOperationException(); } } internal override int ExpressionCount { get { return 1; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _body); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args.Length == 1); Debug.Assert(variables == null || variables.Count == VariableCount); return new Scope1(ReuseOrValidateVariables(variables), args[0]); } } internal class ScopeN : ScopeExpression { private IList<Expression> _body; internal ScopeN(IList<ParameterExpression> variables, IList<Expression> body) : base(variables) { _body = body; } internal override Expression GetExpression(int index) { return _body[index]; } internal override int ExpressionCount { get { return _body.Count; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnly(ref _body); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args.Length == ExpressionCount); Debug.Assert(variables == null || variables.Count == VariableCount); return new ScopeN(ReuseOrValidateVariables(variables), args); } } internal class ScopeWithType : ScopeN { private readonly Type _type; internal ScopeWithType(IList<ParameterExpression> variables, IList<Expression> expressions, Type type) : base(variables, expressions) { _type = type; } public sealed override Type Type { get { return _type; } } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args.Length == ExpressionCount); Debug.Assert(variables == null || variables.Count == VariableCount); return new ScopeWithType(ReuseOrValidateVariables(variables), args, _type); } } #endregion #region Block List Classes /// <summary> /// Provides a wrapper around an IArgumentProvider which exposes the argument providers /// members out as an IList of Expression. This is used to avoid allocating an array /// which needs to be stored inside of a ReadOnlyCollection. Instead this type has /// the same amount of overhead as an array without duplicating the storage of the /// elements. This ensures that internally we can avoid creating and copying arrays /// while users of the Expression trees also don't pay a size penalty for this internal /// optimization. See IArgumentProvider for more general information on the Expression /// tree optimizations being used here. /// </summary> internal class BlockExpressionList : IList<Expression> { private readonly BlockExpression _block; private readonly Expression _arg0; internal BlockExpressionList(BlockExpression provider, Expression arg0) { _block = provider; _arg0 = arg0; } #region IList<Expression> Members public int IndexOf(Expression item) { if (_arg0 == item) { return 0; } for (int i = 1; i < _block.ExpressionCount; i++) { if (_block.GetExpression(i) == item) { return i; } } return -1; } public void Insert(int index, Expression item) { throw ContractUtils.Unreachable; } public void RemoveAt(int index) { throw ContractUtils.Unreachable; } public Expression this[int index] { get { if (index == 0) { return _arg0; } return _block.GetExpression(index); } set { throw ContractUtils.Unreachable; } } #endregion #region ICollection<Expression> Members public void Add(Expression item) { throw ContractUtils.Unreachable; } public void Clear() { throw ContractUtils.Unreachable; } public bool Contains(Expression item) { return IndexOf(item) != -1; } public void CopyTo(Expression[] array, int arrayIndex) { array[arrayIndex++] = _arg0; for (int i = 1; i < _block.ExpressionCount; i++) { array[arrayIndex++] = _block.GetExpression(i); } } public int Count { get { return _block.ExpressionCount; } } public bool IsReadOnly { get { return true; } } public bool Remove(Expression item) { throw ContractUtils.Unreachable; } #endregion #region IEnumerable<Expression> Members public IEnumerator<Expression> GetEnumerator() { yield return _arg0; for (int i = 1; i < _block.ExpressionCount; i++) { yield return _block.GetExpression(i); } } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { yield return _arg0; for (int i = 1; i < _block.ExpressionCount; i++) { yield return _block.GetExpression(i); } } #endregion } #endregion public partial class Expression { /// <summary> /// Creates a <see cref="BlockExpression"/> that contains two expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1) { RequiresCanRead(arg0, "arg0"); RequiresCanRead(arg1, "arg1"); return new Block2(arg0, arg1); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains three expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <param name="arg2">The third expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2) { RequiresCanRead(arg0, "arg0"); RequiresCanRead(arg1, "arg1"); RequiresCanRead(arg2, "arg2"); return new Block3(arg0, arg1, arg2); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains four expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <param name="arg2">The third expression in the block.</param> /// <param name="arg3">The fourth expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3) { RequiresCanRead(arg0, "arg0"); RequiresCanRead(arg1, "arg1"); RequiresCanRead(arg2, "arg2"); RequiresCanRead(arg3, "arg3"); return new Block4(arg0, arg1, arg2, arg3); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains five expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <param name="arg2">The third expression in the block.</param> /// <param name="arg3">The fourth expression in the block.</param> /// <param name="arg4">The fifth expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) { RequiresCanRead(arg0, "arg0"); RequiresCanRead(arg1, "arg1"); RequiresCanRead(arg2, "arg2"); RequiresCanRead(arg3, "arg3"); RequiresCanRead(arg4, "arg4"); return new Block5(arg0, arg1, arg2, arg3, arg4); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables. /// </summary> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(params Expression[] expressions) { ContractUtils.RequiresNotNull(expressions, "expressions"); return GetOptimizedBlockExpression(expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables. /// </summary> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(IEnumerable<Expression> expressions) { return Block(EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, params Expression[] expressions) { ContractUtils.RequiresNotNull(expressions, "expressions"); return Block(type, (IEnumerable<Expression>)expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, IEnumerable<Expression> expressions) { return Block(type, EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(IEnumerable<ParameterExpression> variables, params Expression[] expressions) { return Block(variables, (IEnumerable<Expression>)expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, params Expression[] expressions) { return Block(type, variables, (IEnumerable<Expression>)expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) { ContractUtils.RequiresNotNull(expressions, "expressions"); var variableList = variables.ToReadOnly(); if (variableList.Count == 0) { return GetOptimizedBlockExpression(expressions as IReadOnlyList<Expression> ?? expressions.ToReadOnly()); } var expressionList = expressions.ToReadOnly(); return BlockCore(expressionList.Last().Type, variableList, expressionList); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) { ContractUtils.RequiresNotNull(type, "type"); ContractUtils.RequiresNotNull(expressions, "expressions"); var expressionList = expressions.ToReadOnly(); var variableList = variables.ToReadOnly(); if (variableList.Count == 0) { var expressionCount = expressionList.Count; if (expressionCount != 0) { var lastExpression = expressionList[expressionCount - 1]; if (lastExpression.Type == type) { return GetOptimizedBlockExpression(expressionList); } } } return BlockCore(type, variableList, expressionList); } private static BlockExpression BlockCore(Type type, ReadOnlyCollection<ParameterExpression> variableList, ReadOnlyCollection<Expression> expressionList) { ContractUtils.RequiresNotEmpty(expressionList, "expressions"); RequiresCanRead(expressionList, "expressions"); ValidateVariables(variableList, "variables"); Expression last = expressionList.Last(); if (type != typeof(void)) { if (!TypeUtils.AreReferenceAssignable(type, last.Type)) { throw Error.ArgumentTypesMustMatch(); } } if (!TypeUtils.AreEquivalent(type, last.Type)) { return new ScopeWithType(variableList, expressionList, type); } else { if (expressionList.Count == 1) { return new Scope1(variableList, expressionList[0]); } else { return new ScopeN(variableList, expressionList); } } } // Checks that all variables are non-null, not byref, and unique. internal static void ValidateVariables(ReadOnlyCollection<ParameterExpression> varList, string collectionName) { if (varList.Count == 0) { return; } int count = varList.Count; var set = new Set<ParameterExpression>(count); for (int i = 0; i < count; i++) { ParameterExpression v = varList[i]; if (v == null) { throw new ArgumentNullException(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}[{1}]", collectionName, set.Count)); } if (v.IsByRef) { throw Error.VariableMustNotBeByRef(v, v.Type); } if (set.Contains(v)) { throw Error.DuplicateVariable(v); } set.Add(v); } } private static BlockExpression GetOptimizedBlockExpression(IReadOnlyList<Expression> expressions) { switch (expressions.Count) { case 2: return Block(expressions[0], expressions[1]); case 3: return Block(expressions[0], expressions[1], expressions[2]); case 4: return Block(expressions[0], expressions[1], expressions[2], expressions[3]); case 5: return Block(expressions[0], expressions[1], expressions[2], expressions[3], expressions[4]); default: ContractUtils.RequiresNotEmptyList(expressions, "expressions"); RequiresCanRead(expressions, "expressions"); return new BlockN(expressions as ReadOnlyCollection<Expression> ?? (IList<Expression>)expressions.ToArray()); } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using System.ComponentModel; using System.Threading; using NLog.Common; using NLog.Internal; /// <summary> /// A target that buffers log events and sends them in batches to the wrapped target. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/BufferingWrapper-target">Documentation on NLog Wiki</seealso> [Target("BufferingWrapper", IsWrapper = true)] public class BufferingTargetWrapper : WrapperTargetBase { private LogEventInfoBuffer buffer; private Timer flushTimer; /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> public BufferingTargetWrapper() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> public BufferingTargetWrapper(Target wrappedTarget) : this(wrappedTarget, 100) { } /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="bufferSize">Size of the buffer.</param> public BufferingTargetWrapper(Target wrappedTarget, int bufferSize) : this(wrappedTarget, bufferSize, -1) { } /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="bufferSize">Size of the buffer.</param> /// <param name="flushTimeout">The flush timeout.</param> public BufferingTargetWrapper(Target wrappedTarget, int bufferSize, int flushTimeout) { this.WrappedTarget = wrappedTarget; this.BufferSize = bufferSize; this.FlushTimeout = flushTimeout; this.SlidingTimeout = true; } /// <summary> /// Gets or sets the number of log events to be buffered. /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(100)] public int BufferSize { get; set; } /// <summary> /// Gets or sets the timeout (in milliseconds) after which the contents of buffer will be flushed /// if there's no write in the specified period of time. Use -1 to disable timed flushes. /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(-1)] public int FlushTimeout { get; set; } /// <summary> /// Gets or sets a value indicating whether to use sliding timeout. /// </summary> /// <remarks> /// This value determines how the inactivity period is determined. If sliding timeout is enabled, /// the inactivity timer is reset after each write, if it is disabled - inactivity timer will /// count from the first event written to the buffer. /// </remarks> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(true)] public bool SlidingTimeout { get; set; } /// <summary> /// Flushes pending events in the buffer (if any). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { AsyncLogEventInfo[] events = this.buffer.GetEventsAndClear(); if (events.Length == 0) { this.WrappedTarget.Flush(asyncContinuation); } else { InternalLogger.Trace("BufferingWrapper: Flush {0} events async", events.Length); this.WrappedTarget.WriteAsyncLogEvents(events, ex => this.WrappedTarget.Flush(asyncContinuation)); } } /// <summary> /// Initializes the target. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); this.buffer = new LogEventInfoBuffer(this.BufferSize, false, 0); InternalLogger.Trace("BufferingWrapper: start timer"); this.flushTimer = new Timer(this.FlushCallback, null, -1, -1); } /// <summary> /// Closes the target by flushing pending events in the buffer (if any). /// </summary> protected override void CloseTarget() { base.CloseTarget(); if (this.flushTimer != null) { this.flushTimer.Dispose(); this.flushTimer = null; } } /// <summary> /// Adds the specified log event to the buffer and flushes /// the buffer in case the buffer gets full. /// </summary> /// <param name="logEvent">The log event.</param> protected override void Write(AsyncLogEventInfo logEvent) { this.WrappedTarget.PrecalculateVolatileLayouts(logEvent.LogEvent); int count = this.buffer.Append(logEvent); if (count >= this.BufferSize) { InternalLogger.Trace("BufferingWrapper: writing {0} events because of exceeding buffersize ({0}).", BufferSize); AsyncLogEventInfo[] events = this.buffer.GetEventsAndClear(); this.WrappedTarget.WriteAsyncLogEvents(events); } else { if (this.FlushTimeout > 0) { // reset the timer on first item added to the buffer or whenever SlidingTimeout is set to true if (this.SlidingTimeout || count == 1) { this.flushTimer.Change(this.FlushTimeout, -1); } } } } private void FlushCallback(object state) { lock (this.SyncRoot) { if (this.IsInitialized) { AsyncLogEventInfo[] events = this.buffer.GetEventsAndClear(); if (events.Length > 0) { this.WrappedTarget.WriteAsyncLogEvents(events); } } } } } }
/* * Author: Tristan Chambers * Date: Wednesday, April 1, 2015 * Email: Tristan.Chambers@hotmail.com * Website: Tristan.PaperHatStudios.com */ using System; namespace SMPL.Props { /// <summary> /// Property entry. /// </summary> public class PropertyEntry { #region Properties /// <summary> /// Gets or sets the key. /// </summary> public virtual string Key { get; internal set; } /// <summary> /// Gets or sets the value. /// </summary> public virtual string StringValue { get; internal set; } /// <summary> /// Gets or sets the value. /// </summary> public virtual bool BoolValue { get { return GetValue<bool>(); } } /// <summary> /// Gets or sets the value. /// </summary> public virtual byte ByteValue { get { return GetValue<byte>(); } } /// <summary> /// Gets or sets the value. /// </summary> public virtual short ShortValue { get { return GetValue<short>(); } } /// <summary> /// Gets or sets the value. /// </summary> public virtual int IntValue { get { return GetValue<int>(); } } /// <summary> /// Gets or sets the value. /// </summary> public virtual float FloatValue { get { return GetValue<float>(); } } /// <summary> /// Gets or sets the value. /// </summary> public virtual double DoubleValue { get { return GetValue<double>(); } } /// <summary> /// Gets or sets the value. /// </summary> public virtual long LongValue { get { return GetValue<long>(); } } /// <summary> /// Gets or sets the comment. /// </summary> public virtual string Comment { get; internal set; } private bool _loaded; /// <summary> /// Gets or sets a value indicating whether this <see cref="SimplifiedProperties.PropertyEntry"/> is loaded. /// </summary> /// <value><c>true</c> if loaded; otherwise, <c>false</c>.</value> public virtual bool Loaded { get { return _loaded && (Parent == null || Parent.Loaded); } internal set { _loaded = value; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="SimplifiedProperties.PropertyEntry"/> is modified. /// </summary> /// <value><c>true</c> if modified; otherwise, <c>false</c>.</value> public bool Modified { get; internal set; } /// <summary> /// Gets the root. /// </summary> /// <value>The root.</value> public virtual PropertyList Root { get { PropertyList list = this is PropertyList ? (PropertyList)this : Parent; while (list.Parent != null) { list = list.Parent; } return list; } } /// <summary> /// Gets or sets the parent. /// </summary> /// <value>The parent.</value> public virtual PropertyList Parent { get; set; } /// <summary> /// Gets the indent level. /// </summary> /// <value>The indent level.</value> public virtual int IndentLevel { get { int _indentLevel = 0; PropertyList list = Parent; while (list != null) { list = list.Parent; _indentLevel++; } return _indentLevel - 1; // Subtract one since the first list isn't indented. } } /// <summary> /// Gets or sets the line number. /// </summary> /// <value>The line number.</value> public virtual int LineNumber { get; internal set; } #endregion // Properties /// <summary> /// Initializes a new instance of the <see cref="SimplifiedProperties.PropertyEntry"/> class. /// </summary> /// <param name="file">File.</param> /// <param name="key">Key.</param> /// <param name="value">Value.</param> public PropertyEntry(string key, string stringValue) : this(key, stringValue, string.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="SimplifiedProperties.PropertyEntry"/> class. /// </summary> /// <param name="file">File.</param> /// <param name="key">Key.</param> /// <param name="value">Value.</param> /// <param name="comment">Comment.</param> public PropertyEntry(string key, string stringValue, string comment) { Key = key; StringValue = stringValue; Comment = comment; } public virtual bool TryGetValue<T>(out T value) { try { value = GetValue<T>(); } catch{ value = default(T); return false; } return true; } /// <summary> /// Gets the value. /// </summary> /// <returns>The value.</returns> /// <typeparam name="T">The type of value to get.</typeparam> public virtual T GetValue<T>() { T ret = default(T); try { ret = (T)Convert.ChangeType(StringValue, typeof(T)); } catch (Exception) { throw new PropertyException("Tried to get a " + typeof(T).Name + " from '" + StringValue + "'", this); } return ret; } /// <summary> /// Sets the value. /// </summary> /// <param name="newValue">New value.</param> public virtual void SetValue(object @newValue) { StringValue = @newValue.ToString(); Modified = true; } public override string ToString() { string toString = string.IsNullOrEmpty(Comment) ? Key + " = '" + StringValue + "'" : Key + " = '" + StringValue + "' # " + Comment; for (int i = 0; i < IndentLevel; i++) { toString = " " + toString; } return toString; } } }
using System; using System.Collections; using Server.Targeting; using Server.Network; using Server.Misc; using Server.Items; using Server.Mobiles; namespace Server.Spells.Fifth { public class PoisonFieldSpell : MagerySpell { private static SpellInfo m_Info = new SpellInfo( "Poison Field", "In Nox Grav", 230, 9052, false, Reagent.BlackPearl, Reagent.Nightshade, Reagent.SpidersSilk ); public override SpellCircle Circle { get { return SpellCircle.Fifth; } } public PoisonFieldSpell( Mobile caster, Item scroll ) : base( caster, scroll, m_Info ) { } public override void OnCast() { Caster.Target = new InternalTarget( this ); } public void Target( IPoint3D p ) { if ( !Caster.CanSee( p ) ) { Caster.SendLocalizedMessage( 500237 ); // Target can not be seen. } else if ( SpellHelper.CheckTown( p, Caster ) && CheckSequence() ) { SpellHelper.Turn( Caster, p ); SpellHelper.GetSurfaceTop( ref p ); int dx = Caster.Location.X - p.X; int dy = Caster.Location.Y - p.Y; int rx = (dx - dy) * 44; int ry = (dx + dy) * 44; bool eastToWest; if ( rx >= 0 && ry >= 0 ) { eastToWest = false; } else if ( rx >= 0 ) { eastToWest = true; } else if ( ry >= 0 ) { eastToWest = true; } else { eastToWest = false; } Effects.PlaySound( p, Caster.Map, 0x20B ); int itemID = eastToWest ? 0x3915 : 0x3922; TimeSpan duration = TimeSpan.FromSeconds( 3 + (Caster.Skills.Magery.Fixed / 25) ); for ( int i = -2; i <= 2; ++i ) { Point3D loc = new Point3D( eastToWest ? p.X + i : p.X, eastToWest ? p.Y : p.Y + i, p.Z ); new InternalItem( itemID, loc, Caster, Caster.Map, duration, i ); } } FinishSequence(); } [DispellableField] public class InternalItem : Item { private Timer m_Timer; private DateTime m_End; private Mobile m_Caster; public override bool BlocksFit{ get{ return true; } } public InternalItem( int itemID, Point3D loc, Mobile caster, Map map, TimeSpan duration, int val ) : base( itemID ) { bool canFit = SpellHelper.AdjustField( ref loc, map, 12, false ); Visible = false; Movable = false; Light = LightType.Circle300; MoveToWorld( loc, map ); m_Caster = caster; m_End = DateTime.Now + duration; m_Timer = new InternalTimer( this, TimeSpan.FromSeconds( Math.Abs( val ) * 0.2 ), caster.InLOS( this ), canFit ); m_Timer.Start(); } public override void OnAfterDelete() { base.OnAfterDelete(); if ( m_Timer != null ) m_Timer.Stop(); } public InternalItem( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 1 ); // version writer.Write( m_Caster ); writer.WriteDeltaTime( m_End ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 1: { m_Caster = reader.ReadMobile(); goto case 0; } case 0: { m_End = reader.ReadDeltaTime(); m_Timer = new InternalTimer( this, TimeSpan.Zero, true, true ); m_Timer.Start(); break; } } } public void ApplyPoisonTo( Mobile m ) { if ( m_Caster == null ) return; Poison p; if ( Core.AOS ) { int total = (m_Caster.Skills.Magery.Fixed + m_Caster.Skills.Poisoning.Fixed) / 2; if ( total >= 1000 ) p = Poison.Deadly; else if ( total > 850 ) p = Poison.Greater; else if ( total > 650 ) p = Poison.Regular; else p = Poison.Lesser; } else { p = Poison.Regular; } if ( m.ApplyPoison( m_Caster, p ) == ApplyPoisonResult.Poisoned ) if ( SpellHelper.CanRevealCaster( m ) ) m_Caster.RevealingAction(); if (m is BaseCreature) ((BaseCreature)m).OnHarmfulSpell(m_Caster); } public override bool OnMoveOver( Mobile m ) { if ( Visible && m_Caster != null && (!Core.AOS || m != m_Caster) && SpellHelper.ValidIndirectTarget( m_Caster, m ) && m_Caster.CanBeHarmful( m, false ) ) { m_Caster.DoHarmful( m ); ApplyPoisonTo( m ); m.PlaySound( 0x474 ); } return true; } private class InternalTimer : Timer { private InternalItem m_Item; private bool m_InLOS, m_CanFit; private static Queue m_Queue = new Queue(); public InternalTimer( InternalItem item, TimeSpan delay, bool inLOS, bool canFit ) : base( delay, TimeSpan.FromSeconds( 1.5 ) ) { m_Item = item; m_InLOS = inLOS; m_CanFit = canFit; Priority = TimerPriority.FiftyMS; } protected override void OnTick() { if ( m_Item.Deleted ) return; if ( !m_Item.Visible ) { if ( m_InLOS && m_CanFit ) m_Item.Visible = true; else m_Item.Delete(); if ( !m_Item.Deleted ) { m_Item.ProcessDelta(); Effects.SendLocationParticles( EffectItem.Create( m_Item.Location, m_Item.Map, EffectItem.DefaultDuration ), 0x376A, 9, 10, 5040 ); } } else if ( DateTime.Now > m_Item.m_End ) { m_Item.Delete(); Stop(); } else { Map map = m_Item.Map; Mobile caster = m_Item.m_Caster; if ( map != null && caster != null ) { bool eastToWest = ( m_Item.ItemID == 0x3915 ); IPooledEnumerable eable = map.GetMobilesInBounds( new Rectangle2D( m_Item.X - (eastToWest ? 0 : 1), m_Item.Y - (eastToWest ? 1 : 0), (eastToWest ? 1 : 2), (eastToWest ? 2 : 1) ) ); foreach ( Mobile m in eable ) { if ( (m.Z + 16) > m_Item.Z && (m_Item.Z + 12) > m.Z && (!Core.AOS || m != caster) && SpellHelper.ValidIndirectTarget( caster, m ) && caster.CanBeHarmful( m, false ) ) m_Queue.Enqueue( m ); } eable.Free(); while ( m_Queue.Count > 0 ) { Mobile m = (Mobile)m_Queue.Dequeue(); caster.DoHarmful( m ); m_Item.ApplyPoisonTo( m ); m.PlaySound( 0x474 ); } } } } } } private class InternalTarget : Target { private PoisonFieldSpell m_Owner; public InternalTarget( PoisonFieldSpell owner ) : base( Core.ML ? 10 : 12, true, TargetFlags.None ) { m_Owner = owner; } protected override void OnTarget( Mobile from, object o ) { if ( o is IPoint3D ) m_Owner.Target( (IPoint3D)o ); } protected override void OnTargetFinish( Mobile from ) { m_Owner.FinishSequence(); } } } }
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <author name="Daniel Grunwald"/> // <version>$Revision: 5931 $</version> // </file> using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Documents; using System.Windows.Input; using System.Linq; namespace ICSharpCode.AvalonEdit.CodeCompletion { /// <summary> /// The listbox used inside the CompletionWindow, contains CompletionListBox. /// </summary> public class CompletionList : Control { static CompletionList() { DefaultStyleKeyProperty.OverrideMetadata(typeof(CompletionList), new FrameworkPropertyMetadata(typeof(CompletionList))); } bool isFiltering = true; /// <summary> /// If true, the CompletionList is filtered to show only matching items. Also enables search by substring. /// If false, enables the old behavior: no filtering, search by string.StartsWith. /// </summary> public bool IsFiltering { get { return isFiltering; } set { isFiltering = value; } } /// <summary> /// Dependency property for <see cref="EmptyTemplate" />. /// </summary> public static readonly DependencyProperty EmptyTemplateProperty = DependencyProperty.Register("EmptyTemplate", typeof(ControlTemplate), typeof(CompletionList), new FrameworkPropertyMetadata()); /// <summary> /// Content of EmptyTemplate will be shown when CompletionList contains no items. /// If EmptyTemplate is null, nothing will be shown. /// </summary> public ControlTemplate EmptyTemplate { get { return (ControlTemplate)GetValue(EmptyTemplateProperty); } set { SetValue(EmptyTemplateProperty, value); } } /// <summary> /// Is raised when the completion list indicates that the user has chosen /// an entry to be completed. /// </summary> public event EventHandler InsertionRequested; /// <summary> /// Raises the InsertionRequested event. /// </summary> public void RequestInsertion(EventArgs e) { if (InsertionRequested != null) InsertionRequested(this, e); } CompletionListBox listBox; /// <inheritdoc/> public override void OnApplyTemplate() { base.OnApplyTemplate(); listBox = GetTemplateChild("PART_ListBox") as CompletionListBox; if (listBox != null) { listBox.ItemsSource = completionData; } } /// <summary> /// Gets the list box. /// </summary> public CompletionListBox ListBox { get { if (listBox == null) ApplyTemplate(); return listBox; } } /// <summary> /// Gets the scroll viewer used in this list box. /// </summary> public ScrollViewer ScrollViewer { get { return listBox != null ? listBox.scrollViewer : null; } } ObservableCollection<ICompletionData> completionData = new ObservableCollection<ICompletionData>(); /// <summary> /// Gets the list to which completion data can be added. /// </summary> public IList<ICompletionData> CompletionData { get { return completionData; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled) { HandleKey(e); } } /// <summary> /// Handles a key press. Used to let the completion list handle key presses while the /// focus is still on the text editor. /// </summary> public void HandleKey(KeyEventArgs e) { if (listBox == null) return; // We have to do some key handling manually, because the default doesn't work with // our simulated events. // Also, the default PageUp/PageDown implementation changes the focus, so we avoid it. int index = 0; switch (e.Key) { case Key.Down: e.Handled = true; index = listBox.SelectedIndex + 1; if(index > listBox.Items.Count - 1) { index = 0; } listBox.SelectIndex(index); break; case Key.Up: e.Handled = true; index = listBox.SelectedIndex - 1; if(0 == listBox.SelectedIndex) { index = listBox.Items.Count - 1; } listBox.SelectIndex(index); break; case Key.PageDown: e.Handled = true; listBox.SelectIndex(listBox.SelectedIndex + listBox.VisibleItemCount); break; case Key.PageUp: e.Handled = true; listBox.SelectIndex(listBox.SelectedIndex - listBox.VisibleItemCount); break; case Key.Home: e.Handled = true; listBox.SelectIndex(0); break; case Key.End: e.Handled = true; listBox.SelectIndex(listBox.Items.Count - 1); break; case Key.Tab: e.Handled = true; index = listBox.SelectedIndex + 1; if(index > listBox.Items.Count - 1) { index = 0; } listBox.SelectIndex(index); break; case Key.Enter: e.Handled = true; RequestInsertion(e); break; case Key.Oem5: RequestInsertion(e); break; } } /// <inheritdoc/> protected override void OnMouseDoubleClick(MouseButtonEventArgs e) { base.OnMouseDoubleClick(e); if (e.ChangedButton == MouseButton.Left) { e.Handled = true; RequestInsertion(e); } } /// <summary> /// Gets/Sets the selected item. /// </summary> public ICompletionData SelectedItem { get { return (listBox != null ? listBox.SelectedItem : null) as ICompletionData; } set { if (listBox == null && value != null) ApplyTemplate(); listBox.SelectedItem = value; } } /// <summary> /// Occurs when the SelectedItem property changes. /// </summary> public event SelectionChangedEventHandler SelectionChanged { add { AddHandler(Selector.SelectionChangedEvent, value); } remove { RemoveHandler(Selector.SelectionChangedEvent, value); } } // SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once string currentText; ObservableCollection<ICompletionData> currentList; /// <summary> /// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />. /// </summary> public void SelectItem(string text) { if (text == currentText) return; if (listBox == null) ApplyTemplate(); if (this.IsFiltering) { SelectItemFiltering(text); } else { SelectItemWithStart(text); } currentText = text; } /// <summary> /// Filters CompletionList items to show only those matching given text, and selects the best match. /// </summary> void SelectItemFiltering(string text) { // if the user just typed one more character, don't filter all data but just filter what we are already displaying var listToFilter = (this.currentList != null && (!string.IsNullOrEmpty(this.currentText)) && (!string.IsNullOrEmpty(text)) && text.StartsWith(this.currentText)) ? this.currentList : this.completionData; var itemsWithQualities = from item in listToFilter select new { Item = item, Quality = GetMatchQuality(item.Text, text) }; var matchingItems = itemsWithQualities.Where(item => item.Quality > 0); var listBoxItems = new ObservableCollection<ICompletionData>(); int bestIndex = -1; int bestQuality = -1; double bestPriority = 0; int i = 0; foreach (var matchingItem in matchingItems) { double priority = matchingItem.Item.Priority; int quality = matchingItem.Quality; if (quality > bestQuality || (quality == bestQuality && priority > bestPriority)) { bestIndex = i; bestPriority = priority; bestQuality = quality; } listBoxItems.Add(matchingItem.Item); i++; } this.currentList = listBoxItems; listBox.ItemsSource = listBoxItems; SelectIndexCentered(bestIndex); } /// <summary> /// Selects the item that starts with the specified text. /// </summary> void SelectItemWithStart(string startText) { if (string.IsNullOrEmpty(startText)) return; int selectedItem = listBox.SelectedIndex; int bestIndex = -1; int bestQuality = -1; double bestPriority = 0; for (int i = 0; i < completionData.Count; ++i) { int quality = GetMatchQuality(completionData[i].Text, startText); if (quality < 0) continue; double priority = completionData[i].Priority; bool useThisItem; if (bestQuality < quality) { useThisItem = true; } else { if (bestIndex == selectedItem) { // martin.konicek: I'm not sure what this does. This item could have higher priority, why not select it? useThisItem = false; } else if (i == selectedItem) { useThisItem = bestQuality == quality; } else { useThisItem = bestQuality == quality && bestPriority < priority; } } if (useThisItem) { bestIndex = i; bestPriority = priority; bestQuality = quality; } } SelectIndexCentered(bestIndex); } void SelectIndexCentered(int bestIndex) { if (bestIndex < 0) { listBox.ClearSelection(); } else { int firstItem = listBox.FirstVisibleItem; if (bestIndex < firstItem || firstItem + listBox.VisibleItemCount <= bestIndex) { // CenterViewOn does nothing as CompletionListBox.ScrollViewer is null listBox.CenterViewOn(bestIndex); listBox.SelectIndex(bestIndex); } else { listBox.SelectIndex(bestIndex); } } } int GetMatchQuality(string itemText, string query) { // Qualities: // -1 = no match // 1 = match CamelCase // 2 = match sustring // 3 = match substring case sensitive // 4 = match CamelCase when length of query is 1 or 2 characters // 5 = match start // 6 = match start case sensitive // 7 = full match // 8 = full match case sensitive if (query == itemText) return 8; if (string.Equals(itemText, query, StringComparison.OrdinalIgnoreCase)) return 7; if (itemText.StartsWith(query)) return 6; if (itemText.StartsWith(query, StringComparison.OrdinalIgnoreCase)) return 5; bool? camelCaseMatch = null; if (query.Length <= 2) { camelCaseMatch = CamelCaseMatch(itemText, query); if (camelCaseMatch.GetValueOrDefault(false)) return 4; } // search by substring, if filtering (i.e. new behavior) turned on if (IsFiltering && itemText.Contains(query)) return 3; if (IsFiltering && itemText.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0) return 2; if (!camelCaseMatch.HasValue) camelCaseMatch = CamelCaseMatch(itemText, query); if (camelCaseMatch.GetValueOrDefault(false)) return 1; return -1; } static bool CamelCaseMatch(string text, string query) { int i = 0; foreach (char upper in text.Where(c => char.IsUpper(c))) { if (i > query.Length - 1) return true; // return true here for CamelCase partial match (CQ match CodeQualityAnalysis) if (char.ToUpper(query[i]) != upper) return false; i++; } if (i >= query.Length) return true; return false; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Projeny.Internal { public static class PrjSerializer { public static string SerializeProjectConfig(ProjectConfig info) { return YamlSerializer.Serialize<ProjectConfigInternal>(ConvertToInternal(info)); } public static ProjectConfig DeserializeProjectConfig(string yamlStr) { return ConvertToPublic(YamlSerializer.Deserialize<ProjectConfigInternal>(yamlStr)); } public static ReleaseInfo DeserializeReleaseInfo(string yamlStr) { return ConvertToPublic(YamlSerializer.Deserialize<ReleaseInfoInternal>(yamlStr)); } public static PackageFolderInfo DeserializePackageFolderInfo(string yamlStr) { return ConvertToPublic(YamlSerializer.Deserialize<PackageFolderInfoInternal>(yamlStr)); } static ProjectConfigInternal ConvertToInternal(ProjectConfig info) { return new ProjectConfigInternal() { ProjectSettingsPath = info.ProjectSettingsPath, UnityPackagesPath = info.UnityPackagesPath, AssetsFolder = info.AssetsFolder.IsEmpty() ? null : info.AssetsFolder.ToList(), PluginsFolder = info.PluginsFolder.IsEmpty() ? null : info.PluginsFolder.ToList(), SolutionProjects = info.SolutionProjects.IsEmpty() ? null : info.SolutionProjects.ToList(), PackageFolders = info.PackageFolders.IsEmpty() ? null : info.PackageFolders.ToList(), Prebuilt = info.Prebuilt.IsEmpty() ? null : info.Prebuilt.ToList(), SolutionFolders = info.SolutionFolders.IsEmpty() ? null : info.SolutionFolders.Select(x => new Dictionary<string, string>() { { x.Key, x.Value } }).ToList(), TargetPlatforms = info.ProjectPlatforms.IsEmpty() ? null : info.ProjectPlatforms, }; } static ProjectConfig ConvertToPublic(ProjectConfigInternal info) { if (info == null) { return null; } var newInfo = new ProjectConfig(); newInfo.ProjectSettingsPath = info.ProjectSettingsPath; newInfo.UnityPackagesPath = info.UnityPackagesPath; if (info.AssetsFolder != null) { newInfo.AssetsFolder.AddRange(info.AssetsFolder.ToList()); } if (info.PluginsFolder != null) { newInfo.PluginsFolder.AddRange(info.PluginsFolder.ToList()); } if (info.SolutionProjects != null) { newInfo.SolutionProjects.AddRange(info.SolutionProjects.ToList()); } if (info.PackageFolders != null) { newInfo.PackageFolders.AddRange(info.PackageFolders.ToList()); } if (info.Prebuilt != null) { newInfo.Prebuilt.AddRange(info.Prebuilt.ToList()); } if (info.SolutionFolders != null) { newInfo.SolutionFolders.AddRange(info.SolutionFolders.Select(x => x.Single()).ToList()); } if (info.TargetPlatforms != null) { newInfo.ProjectPlatforms = info.TargetPlatforms; } return newInfo; } static PackageFolderInfo ConvertToPublic(PackageFolderInfoInternal info) { if (info == null) { return null; } var newInfo = new PackageFolderInfo(); newInfo.Path = info.Path; if (info.Packages != null) { foreach (var packageInfo in info.Packages) { var newPackageInfo = new PackageInfo(); newPackageInfo.Name = packageInfo.Name; newPackageInfo.InstallInfo = ConvertToPublic(packageInfo.InstallInfo); newPackageInfo.FullPath = Path.Combine(info.Path, packageInfo.Name); newInfo.Packages.Add(newPackageInfo); } } return newInfo; } static PackageInstallInfo ConvertToPublic(PackageInstallInfoInternal info) { if (info == null) { // Can't return null here since unity serialization doesn't support null return new PackageInstallInfo() { ReleaseInfo = ConvertToPublic((ReleaseInfoInternal)null) }; } var newInfo = new PackageInstallInfo(); newInfo.InstallDate = DateTimeToString(info.InstallDate); newInfo.InstallDateTicks = info.InstallDate.Ticks; newInfo.ReleaseInfo = ConvertToPublic(info.ReleaseInfo); return newInfo; } static ReleaseInfo ConvertToPublic(ReleaseInfoInternal info) { if (info == null) { // Can't return null here since unity serialization doesn't support null return new ReleaseInfo() { AssetStoreInfo = ConvertToPublic((AssetStoreInfoInternal)null), }; } var newInfo = new ReleaseInfo(); newInfo.Name = info.Name; newInfo.HasVersionCode = info.VersionCode.HasValue; if (info.VersionCode.HasValue) { newInfo.VersionCode = info.VersionCode.Value; } newInfo.HasCompressedSize = info.CompressedSize.HasValue; if (info.CompressedSize.HasValue) { newInfo.CompressedSize = info.CompressedSize.Value; } newInfo.Version = info.Version; newInfo.LocalPath = info.LocalPath; newInfo.Url = info.Url; Assert.That(!string.IsNullOrEmpty(info.Id)); newInfo.Id = info.Id; newInfo.FileModificationDate = info.FileModificationDate.HasValue ? DateTimeToString(info.FileModificationDate.Value) : null; newInfo.FileModificationDateTicks = info.FileModificationDate.HasValue ? info.FileModificationDate.Value.Ticks : 0; newInfo.AssetStoreInfo = ConvertToPublic(info.AssetStoreInfo); return newInfo; } static AssetStoreInfo ConvertToPublic(AssetStoreInfoInternal info) { if (info == null) { // Can't return null here since unity serialization doesn't support null return new AssetStoreInfo(); } var newInfo = new AssetStoreInfo(); newInfo.PublisherId = info.PublisherId; newInfo.PublisherLabel = info.PublisherLabel; newInfo.PublishNotes = info.PublishNotes; newInfo.CategoryId = info.CategoryId; newInfo.CategoryLabel = info.CategoryLabel; newInfo.UploadId = info.UploadId; newInfo.Description = info.Description; newInfo.PublishDate = info.PublishDate.HasValue ? DateTimeToString(info.PublishDate.Value) : null; newInfo.PublishDateTicks = info.PublishDate.HasValue ? info.PublishDate.Value.Ticks : 0; newInfo.UnityVersion = info.UnityVersion; newInfo.LinkId = info.LinkId; newInfo.LinkType = info.LinkType; return newInfo; } static string DateTimeToString(DateTime utcDate) { return "{0} ({1})".Fmt(DateTimeUtil.FormatPastDateAsRelative(utcDate), utcDate.ToLocalTime().ToString("d")); } // Yaml requires that we use properties, but Unity serialization requires // the opposite - that we use fields class ReleaseInfoInternal { public string Id { get; set; } public string Name { get; set; } public long? CompressedSize { get; set; } public long? VersionCode { get; set; } public string Version { get; set; } public string LocalPath { get; set; } public string Url { get; set; } public DateTime? FileModificationDate { get; set; } public AssetStoreInfoInternal AssetStoreInfo { get; set; } } class ProjectConfigInternal { public List<string> AssetsFolder { get; set; } public string ProjectSettingsPath { get; set; } public string UnityPackagesPath { get; set; } public List<string> PluginsFolder { get; set; } public List<string> PackageFolders { get; set; } public List<string> SolutionProjects { get; set; } public List<string> Prebuilt { get; set; } public List<Dictionary<string, string>> SolutionFolders { get; set; } public List<string> TargetPlatforms { get; set; } } class PackageInstallInfoInternal { public DateTime InstallDate { get; set; } public ReleaseInfoInternal ReleaseInfo { get; set; } } class PackageFolderInfoInternal { public string Path { get; set; } public List<PackageInfoInternal> Packages { get; set; } } class PackageInfoInternal { public string Name { get; set; } public PackageInstallInfoInternal InstallInfo { get; set; } } class AssetStoreInfoInternal { public string PublisherId { get; set; } public string PublisherLabel { get; set; } public string PublishNotes { get; set; } public string CategoryId { get; set; } public string CategoryLabel { get; set; } public string UploadId { get; set; } public string Description { get; set; } public DateTime? PublishDate { get; set; } public string UnityVersion { get; set; } public string LinkId { get; set; } public string LinkType { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.GraphAlgorithms; using Microsoft.Msagl.Core.Layout; namespace Microsoft.Msagl.Layout.Layered { /// <summary> /// vertical constraints for Suquiyama scheme /// </summary> internal class VerticalConstraintsForSugiyama { readonly Set<Node> _maxLayerOfGeomGraph = new Set<Node>(); /// <summary> /// nodes that are pinned to the max layer /// </summary> internal Set<Node> MaxLayerOfGeomGraph { get { return _maxLayerOfGeomGraph; } } readonly Set<Node> _minLayerOfGeomGraph = new Set<Node>(); /// <summary> /// nodes that are pinned to the min layer /// </summary> internal Set<Node> MinLayerOfGeomGraph { get { return _minLayerOfGeomGraph; } } Set<Tuple<Node, Node>> sameLayerConstraints = new Set<Tuple<Node, Node>>(); /// <summary> /// set of couple of nodes belonging to the same layer /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] internal Set<Tuple<Node, Node>> SameLayerConstraints { get { return sameLayerConstraints; } } Set<Tuple<Node, Node>> upDownConstraints = new Set<Tuple<Node, Node>>(); /// <summary> /// set of node couples such that the first node of the couple is above the second one /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] internal Set<Tuple<Node, Node>> UpDownConstraints { get { return upDownConstraints; } } /// <summary> /// pins a node to max layer /// </summary> /// <param name="node"></param> internal void PinNodeToMaxLayer(Node node) { MaxLayerOfGeomGraph.Insert(node); } /// <summary> /// pins a node to min layer /// </summary> /// <param name="node"></param> internal void PinNodeToMinLayer(Node node) { System.Diagnostics.Debug.Assert(node != null); MinLayerOfGeomGraph.Insert(node); } internal bool IsEmpty { get { return MaxLayerOfGeomGraph.Count == 0 && MinLayerOfGeomGraph.Count == 0 && SameLayerConstraints.Count == 0 && this.UpDownConstraints.Count == 0; } } internal void Clear() { this.MaxLayerOfGeomGraph.Clear(); this.MinLayerOfGeomGraph.Clear(); this.SameLayerConstraints.Clear(); this.UpDownConstraints.Clear(); } Set<IntPair> gluedUpDownIntConstraints = new Set<IntPair>(); internal Set<IntPair> GluedUpDownIntConstraints { get { return gluedUpDownIntConstraints; } set { gluedUpDownIntConstraints = value; } } Dictionary<Node, int> nodeIdToIndex; BasicGraph<Node, IntEdge> intGraph; /// <summary> /// this graph is obtained from intGraph by glueing together same layer vertices /// </summary> BasicGraph<IntPair> gluedIntGraph; int maxRepresentative; int minRepresentative; /// <summary> /// Maps each node participating in same layer relation its representative on the layer. /// </summary> Dictionary<int, int> sameLayerDictionaryOfRepresentatives = new Dictionary<int, int>(); Dictionary<int, IEnumerable<int>> representativeToItsLayer = new Dictionary<int, IEnumerable<int>>(); internal IEnumerable<IEdge> GetFeedbackSet(BasicGraph<Node, IntEdge> intGraphPar, Dictionary<Node, int> nodeIdToIndexPar) { this.nodeIdToIndex = nodeIdToIndexPar; this.intGraph = intGraphPar; this.maxRepresentative = -1; this.minRepresentative = -1; CreateIntegerConstraints(); GlueTogetherSameConstraintsMaxAndMin(); AddMaxMinConstraintsToGluedConstraints(); RemoveCyclesFromGluedConstraints(); return GetFeedbackSet(); } private void RemoveCyclesFromGluedConstraints() { var feedbackSet= CycleRemoval<IntPair>. GetFeedbackSetWithConstraints(new BasicGraph<IntPair>(GluedUpDownIntConstraints, this.intGraph.NodeCount), null); //feedbackSet contains all glued constraints making constraints cyclic foreach (IntPair p in feedbackSet) GluedUpDownIntConstraints.Remove(p); } private void AddMaxMinConstraintsToGluedConstraints() { if (this.maxRepresentative != -1) for (int i = 0; i < this.intGraph.NodeCount; i++) { int j = NodeToRepr(i); if (j != maxRepresentative) GluedUpDownIntConstraints.Insert(new IntPair(maxRepresentative, j)); } if (this.minRepresentative != -1) for (int i = 0; i < this.intGraph.NodeCount; i++) { int j = NodeToRepr(i); if (j != minRepresentative) GluedUpDownIntConstraints.Insert(new IntPair(j, minRepresentative)); } } private void GlueTogetherSameConstraintsMaxAndMin() { CreateDictionaryOfSameLayerRepresentatives(); GluedUpDownIntConstraints = new Set<IntPair>(from p in UpDownInts select GluedIntPair(p)); } internal IntPair GluedIntPair(Tuple<int, int> p) { return new IntPair(NodeToRepr(p.Item1), NodeToRepr(p.Item2)); } private IntPair GluedIntPair(IntEdge p) { return new IntPair(NodeToRepr(p.Source), NodeToRepr(p.Target)); } internal IntPair GluedIntPair(IntPair p) { return new IntPair(NodeToRepr(p.First), NodeToRepr(p.Second)); } internal IntEdge GluedIntEdge(IntEdge intEdge) { int sourceRepr = NodeToRepr(intEdge.Source); int targetRepr = NodeToRepr(intEdge.Target); IntEdge ie = new IntEdge(sourceRepr, targetRepr); ie.Separation = intEdge.Separation; ie.Weight = 0; ie.Edge = intEdge.Edge; return ie; } internal int NodeToRepr(int node) { int repr; if (this.sameLayerDictionaryOfRepresentatives.TryGetValue(node, out repr)) return repr; return node; } private void CreateDictionaryOfSameLayerRepresentatives() { BasicGraph<IntPair> graphOfSameLayers = CreateGraphOfSameLayers(); foreach (var comp in ConnectedComponentCalculator<IntPair>.GetComponents(graphOfSameLayers)) GlueSameLayerNodesOfALayer(comp); } private BasicGraph<IntPair> CreateGraphOfSameLayers() { return new BasicGraph<IntPair>(CreateEdgesOfSameLayers(), this.intGraph.NodeCount); } private IEnumerable<IntPair> CreateEdgesOfSameLayers() { List<IntPair> ret = new List<IntPair>(); if (maxRepresentative != -1) ret.AddRange(from v in maxLayerInt where v != maxRepresentative select new IntPair(maxRepresentative, v)); if (minRepresentative != -1) ret.AddRange(from v in minLayerInt where v != minRepresentative select new IntPair(minRepresentative, v)); ret.AddRange(from couple in SameLayerInts select new IntPair(couple.Item1, couple.Item2)); return ret; } /// <summary> /// maps all nodes of the component to one random representative /// </summary> /// <param name="sameLayerNodes"></param> private void GlueSameLayerNodesOfALayer(IEnumerable<int> sameLayerNodes) { if (sameLayerNodes.Count<int>() > 1) { int representative = -1; if (ComponentsIsMaxLayer(sameLayerNodes)) foreach (int v in sameLayerNodes) this.sameLayerDictionaryOfRepresentatives[v] = representative = maxRepresentative; else if (ComponentIsMinLayer(sameLayerNodes)) foreach (int v in sameLayerNodes) sameLayerDictionaryOfRepresentatives[v] = representative = minRepresentative; else { foreach (int v in sameLayerNodes) { if (representative == -1) representative = v; sameLayerDictionaryOfRepresentatives[v] = representative; } } this.representativeToItsLayer[representative] = sameLayerNodes; } } private bool ComponentIsMinLayer(IEnumerable<int> component) { return component.Contains<int>(this.minRepresentative); } private bool ComponentsIsMaxLayer(IEnumerable<int> component) { return component.Contains<int>(this.maxRepresentative); } List<int> maxLayerInt = new List<int>(); List<int> minLayerInt = new List<int>(); List<Tuple<int, int>> sameLayerInts = new List<Tuple<int, int>>(); /// <summary> /// contains also pinned max and min pairs /// </summary> internal List<Tuple<int, int>> SameLayerInts { get { return sameLayerInts; } set { sameLayerInts = value; } } List<Tuple<int, int>> upDownInts = new List<Tuple<int, int>>(); internal List<Tuple<int, int>> UpDownInts { get { return upDownInts; } set { upDownInts = value; } } private void CreateIntegerConstraints() { CreateMaxIntConstraints(); CreateMinIntConstraints(); CreateUpDownConstraints(); CreateSameLayerConstraints(); } private void CreateSameLayerConstraints() { this.SameLayerInts = CreateIntConstraintsFromStringCouples(this.SameLayerConstraints); } private void CreateUpDownConstraints() { this.UpDownInts = CreateIntConstraintsFromStringCouples(this.UpDownConstraints); } private List<Tuple<int, int>> CreateIntConstraintsFromStringCouples(Set<Tuple<Node, Node>> set) { return new List<Tuple<int, int>>(from couple in set let t = new Tuple<int, int>(NodeIndex(couple.Item1), NodeIndex(couple.Item2)) where t.Item1 != -1 && t.Item2 != -1 select t); } private void CreateMinIntConstraints() { this.minLayerInt = CreateIntConstraintsFromExtremeLayer(this.MinLayerOfGeomGraph); if (minLayerInt.Count > 0) this.minRepresentative = minLayerInt[0]; } private void CreateMaxIntConstraints() { this.maxLayerInt = CreateIntConstraintsFromExtremeLayer(this.MaxLayerOfGeomGraph); if (maxLayerInt.Count > 0) this.maxRepresentative = maxLayerInt[0]; } private List<int> CreateIntConstraintsFromExtremeLayer(Set<Node> setOfNodes) { return new List<int>(from node in setOfNodes let index = NodeIndex(node) where index != -1 select index); } int NodeIndex(Node node) { int index; if (this.nodeIdToIndex.TryGetValue(node, out index)) return index; return -1; } private IEnumerable<IEdge> GetFeedbackSet() { this.gluedIntGraph = CreateGluedGraph(); return UnglueIntPairs(CycleRemoval<IntPair>.GetFeedbackSetWithConstraints(gluedIntGraph, this.GluedUpDownIntConstraints));//avoiding lazy evaluation } private IEnumerable<IEdge> UnglueIntPairs(IEnumerable<IEdge> gluedEdges) { foreach (IEdge gluedEdge in gluedEdges) foreach (IEdge ungluedEdge in UnglueEdge(gluedEdge)) yield return ungluedEdge; } private IEnumerable<IEdge> UnglueEdge(IEdge gluedEdge) { foreach (int source in UnglueNode(gluedEdge.Source)) foreach (IntEdge edge in intGraph.OutEdges(source)) if (NodeToRepr(edge.Target) == gluedEdge.Target) yield return edge; } private BasicGraph<IntPair> CreateGluedGraph() { return new BasicGraph<IntPair>(new Set<IntPair>(from edge in this.intGraph.Edges select GluedIntPair(edge)), this.intGraph.NodeCount); } IEnumerable<int> UnglueNode(int node) { IEnumerable<int> layer; if (this.representativeToItsLayer.TryGetValue(node, out layer)) return layer; return new int[] { node }; } internal int[] GetGluedNodeCounts() { int[] ret = new int[this.nodeIdToIndex.Count]; for (int node = 0; node < ret.Length; node++) ret[NodeToRepr(node)]++; return ret; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Elasticsearch.Net; using Elasticsearch.Net.Serialization; using Nest.Resolvers; using Nest.Resolvers.Converters; using Newtonsoft.Json; namespace Nest { public class NestSerializer : INestSerializer { private readonly IConnectionSettingsValues _settings; private readonly JsonSerializerSettings _serializationSettings; public NestSerializer(IConnectionSettingsValues settings) { this._settings = settings; this._serializationSettings = this.CreateSettings(); } public virtual byte[] Serialize(object data, SerializationFormatting formatting = SerializationFormatting.Indented) { var format = formatting == SerializationFormatting.None ? Formatting.None : Formatting.Indented; var serialized = JsonConvert.SerializeObject(data, format, this._serializationSettings); return serialized.Utf8Bytes(); } /// <summary> /// Deserialize an object /// </summary> /// <typeparam name="T">The type you want to deserialize too</typeparam> /// <param name="response">If the type you want is a Nest Response you have to pass a response object</param> /// <param name="stream">The stream to deserialize off</param> /// <param name="deserializationState">Optional deserialization state</param> public virtual T Deserialize<T>(IElasticsearchResponse response, Stream stream, object deserializationState = null) { var settings = this._serializationSettings; var customConverter = deserializationState as Func<IElasticsearchResponse, Stream, T>; if (customConverter != null) { var t = customConverter(response, stream); return t; } var state = deserializationState as JsonConverter; if (state != null) settings = this.CreateSettings(state); return _Deserialize<T>(response, stream, settings); } /// <summary> /// Deserialize to type T bypassing checks for custom deserialization state and or BaseResponse return types. /// </summary> public T DeserializeInternal<T>(Stream stream) { var serializer = JsonSerializer.Create(this._serializationSettings); var jsonTextReader = new JsonTextReader(new StreamReader(stream)); var t = (T) serializer.Deserialize(jsonTextReader, typeof (T)); return t; } protected internal T _Deserialize<T>(IElasticsearchResponse response, Stream stream, JsonSerializerSettings settings = null) { settings = settings ?? _serializationSettings; var serializer = JsonSerializer.Create(settings); var jsonTextReader = new JsonTextReader(new StreamReader(stream)); var t = (T) serializer.Deserialize(jsonTextReader, typeof (T)); var r = t as BaseResponse; if (r != null) { r.ConnectionStatus = response; } return t; } public virtual Task<T> DeserializeAsync<T>(IElasticsearchResponse response, Stream stream, object deserializationState = null) { //TODO sadly json .net async does not read the stream async so //figure out wheter reading the stream async on our own might be beneficial //over memory possible memory usage var tcs = new TaskCompletionSource<T>(); var r = this.Deserialize<T>(response, stream, deserializationState); tcs.SetResult(r); return tcs.Task; } internal JsonSerializerSettings CreateSettings(JsonConverter piggyBackJsonConverter = null) { var piggyBackState = new JsonConverterPiggyBackState { ActualJsonConverter = piggyBackJsonConverter }; var settings = new JsonSerializerSettings() { ContractResolver = new ElasticContractResolver(this._settings) { PiggyBackState = piggyBackState }, DefaultValueHandling = DefaultValueHandling.Include, NullValueHandling = NullValueHandling.Ignore }; if (_settings.ModifyJsonSerializerSettings != null) _settings.ModifyJsonSerializerSettings(settings); return settings; } public string SerializeBulkDescriptor(BulkDescriptor bulkDescriptor) { bulkDescriptor.ThrowIfNull("bulkDescriptor"); bulkDescriptor._Operations.ThrowIfEmpty("Bulk descriptor does not define any operations"); var sb = new StringBuilder(); var inferrer = new ElasticInferrer(this._settings); foreach (var operation in bulkDescriptor._Operations) { var command = operation._Operation; var index = operation._Index ?? inferrer.IndexName(bulkDescriptor._Index) ?? inferrer.IndexName(operation._ClrType); var typeName = operation._Type ?? inferrer.TypeName(bulkDescriptor._Type) ?? inferrer.TypeName(operation._ClrType); var id = operation.GetIdForObject(inferrer); operation._Index = index; operation._Type = typeName; operation._Id = id; var opJson = this.Serialize(operation, SerializationFormatting.None).Utf8String(); var action = "{{ \"{0}\" : {1} }}\n".F(command, opJson); sb.Append(action); if (command == "index" || command == "create") { var jsonCommand = this.Serialize(operation._Object, SerializationFormatting.None).Utf8String(); sb.Append(jsonCommand + "\n"); } else if (command == "update") { var jsonCommand = this.Serialize(operation.GetBody(), SerializationFormatting.None).Utf8String(); sb.Append(jsonCommand + "\n"); } } var json = sb.ToString(); return json; } /// <summary> /// _msearch needs a specialized json format in the body /// </summary> public string SerializeMultiSearch(MultiSearchDescriptor multiSearchDescriptor) { var sb = new StringBuilder(); var inferrer = new ElasticInferrer(this._settings); foreach (var operation in multiSearchDescriptor._Operations.Values) { var indices = inferrer.IndexNames(operation._Indices); if (operation._AllIndices.GetValueOrDefault(false)) indices = "_all"; var index = indices ?? inferrer.IndexName(multiSearchDescriptor._Index) ?? inferrer.IndexName(operation._ClrType); var types = inferrer.TypeNames(operation._Types); var typeName = types ?? inferrer.TypeName(multiSearchDescriptor._Type) ?? inferrer.TypeName(operation._ClrType); if (operation._AllTypes.GetValueOrDefault(false)) typeName = null; //force empty typename so we'll query all types. var op = new { index = index, type = typeName, search_type = this.GetSearchType(operation, multiSearchDescriptor), preference = operation._Preference, routing = operation._Routing }; var opJson = this.Serialize(op, SerializationFormatting.None).Utf8String(); var action = "{0}\n".F(opJson); sb.Append(action); var searchJson = this.Serialize(operation, SerializationFormatting.None).Utf8String(); sb.Append(searchJson + "\n"); } var json = sb.ToString(); return json; } protected string GetSearchType(SearchDescriptorBase descriptor, MultiSearchDescriptor multiSearchDescriptor) { if (descriptor._SearchType != null) { switch (descriptor._SearchType.Value) { case SearchTypeOptions.Count: return "count"; case SearchTypeOptions.DfsQueryThenFetch: return "dfs_query_then_fetch"; case SearchTypeOptions.DfsQueryAndFetch: return "dfs_query_and_fetch"; case SearchTypeOptions.QueryThenFetch: return "query_then_fetch"; case SearchTypeOptions.QueryAndFetch: return "query_and_fetch"; case SearchTypeOptions.Scan: return "scan"; } } return multiSearchDescriptor._QueryString.ContainsKey("search_type") ? multiSearchDescriptor._QueryString._QueryStringDictionary["search_type"] as string : null; } } }
// This source file is based on mock4net by Alexandre Victoor which is licensed under the Apache 2.0 License. // For more details see 'mock4net/LICENSE.txt' and 'mock4net/readme.md' in this project root. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using JetBrains.Annotations; using Newtonsoft.Json; using WireMock.Admin.Mappings; using WireMock.Authentication; using WireMock.Exceptions; using WireMock.Handlers; using WireMock.Logging; using WireMock.Matchers.Request; using WireMock.Owin; using WireMock.RequestBuilders; using WireMock.ResponseProviders; using WireMock.Serialization; using WireMock.Settings; using Stef.Validation; namespace WireMock.Server { /// <summary> /// The fluent mock server. /// </summary> public partial class WireMockServer : IWireMockServer { private const int ServerStartDelayInMs = 100; private readonly IWireMockServerSettings _settings; private readonly IOwinSelfHost _httpServer; private readonly IWireMockMiddlewareOptions _options = new WireMockMiddlewareOptions(); private readonly MappingConverter _mappingConverter; private readonly MatcherMapper _matcherMapper; private readonly MappingToFileSaver _mappingToFileSaver; /// <inheritdoc cref="IWireMockServer.IsStarted" /> [PublicAPI] public bool IsStarted => _httpServer != null && _httpServer.IsStarted; /// <inheritdoc cref="IWireMockServer.Ports" /> [PublicAPI] public List<int> Ports { get; } /// <inheritdoc cref="IWireMockServer.Urls" /> [PublicAPI] public string[] Urls { get; } /// <summary> /// Gets the mappings. /// </summary> [PublicAPI] public IEnumerable<IMapping> Mappings => _options.Mappings.Values.ToArray(); /// <inheritdoc cref="IWireMockServer.MappingModels" /> [PublicAPI] public IEnumerable<MappingModel> MappingModels => ToMappingModels(); /// <summary> /// Gets the scenarios. /// </summary> [PublicAPI] public ConcurrentDictionary<string, ScenarioState> Scenarios => new ConcurrentDictionary<string, ScenarioState>(_options.Scenarios); #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { DisposeEnhancedFileSystemWatcher(); _httpServer?.StopAsync(); } #endregion #region Start/Stop /// <summary> /// Starts this WireMockServer with the specified settings. /// </summary> /// <param name="settings">The WireMockServerSettings.</param> /// <returns>The <see cref="WireMockServer"/>.</returns> [PublicAPI] public static WireMockServer Start([NotNull] IWireMockServerSettings settings) { Guard.NotNull(settings, nameof(settings)); return new WireMockServer(settings); } /// <summary> /// Start this WireMockServer. /// </summary> /// <param name="port">The port.</param> /// <param name="ssl">The SSL support.</param> /// <returns>The <see cref="WireMockServer"/>.</returns> [PublicAPI] public static WireMockServer Start([CanBeNull] int? port = 0, bool ssl = false) { return new WireMockServer(new WireMockServerSettings { Port = port, UseSSL = ssl }); } /// <summary> /// Start this WireMockServer. /// </summary> /// <param name="urls">The urls to listen on.</param> /// <returns>The <see cref="WireMockServer"/>.</returns> [PublicAPI] public static WireMockServer Start(params string[] urls) { Guard.NotNullOrEmpty(urls, nameof(urls)); return new WireMockServer(new WireMockServerSettings { Urls = urls }); } /// <summary> /// Start this WireMockServer with the admin interface. /// </summary> /// <param name="port">The port.</param> /// <param name="ssl">The SSL support.</param> /// <returns>The <see cref="WireMockServer"/>.</returns> [PublicAPI] public static WireMockServer StartWithAdminInterface(int? port = 0, bool ssl = false) { return new WireMockServer(new WireMockServerSettings { Port = port, UseSSL = ssl, StartAdminInterface = true }); } /// <summary> /// Start this WireMockServer with the admin interface. /// </summary> /// <param name="urls">The urls.</param> /// <returns>The <see cref="WireMockServer"/>.</returns> [PublicAPI] public static WireMockServer StartWithAdminInterface(params string[] urls) { Guard.NotNullOrEmpty(urls, nameof(urls)); return new WireMockServer(new WireMockServerSettings { Urls = urls, StartAdminInterface = true }); } /// <summary> /// Start this WireMockServer with the admin interface and read static mappings. /// </summary> /// <param name="urls">The urls.</param> /// <returns>The <see cref="WireMockServer"/>.</returns> [PublicAPI] public static WireMockServer StartWithAdminInterfaceAndReadStaticMappings(params string[] urls) { Guard.NotNullOrEmpty(urls, nameof(urls)); return new WireMockServer(new WireMockServerSettings { Urls = urls, StartAdminInterface = true, ReadStaticMappings = true }); } /// <summary> /// Initializes a new instance of the <see cref="WireMockServer"/> class. /// </summary> /// <param name="settings">The settings.</param> /// <exception cref="WireMockException"> /// Service start failed with error: {_httpServer.RunningException.Message} /// or /// Service start failed with error: {startTask.Exception.Message} /// </exception> /// <exception cref="TimeoutException">Service start timed out after {TimeSpan.FromMilliseconds(settings.StartTimeout)}</exception> protected WireMockServer(IWireMockServerSettings settings) { _settings = settings; // Set default values if not provided _settings.Logger = settings.Logger ?? new WireMockNullLogger(); _settings.FileSystemHandler = settings.FileSystemHandler ?? new LocalFileSystemHandler(); _settings.Logger.Info("By Stef Heyenrath (https://github.com/WireMock-Net/WireMock.Net)"); _settings.Logger.Debug("Server settings {0}", JsonConvert.SerializeObject(settings, Formatting.Indented)); HostUrlOptions urlOptions; if (settings.Urls != null) { urlOptions = new HostUrlOptions { Urls = settings.Urls }; } else { urlOptions = new HostUrlOptions { UseSSL = settings.UseSSL == true, Port = settings.Port }; } _options.FileSystemHandler = _settings.FileSystemHandler; _options.PreWireMockMiddlewareInit = _settings.PreWireMockMiddlewareInit; _options.PostWireMockMiddlewareInit = _settings.PostWireMockMiddlewareInit; _options.Logger = _settings.Logger; _options.DisableJsonBodyParsing = _settings.DisableJsonBodyParsing; _options.HandleRequestsSynchronously = settings.HandleRequestsSynchronously; _options.SaveUnmatchedRequests = settings.SaveUnmatchedRequests; if (settings.CustomCertificateDefined) { _options.X509StoreName = settings.CertificateSettings.X509StoreName; _options.X509StoreLocation = settings.CertificateSettings.X509StoreLocation; _options.X509ThumbprintOrSubjectName = settings.CertificateSettings.X509StoreThumbprintOrSubjectName; _options.X509CertificateFilePath = settings.CertificateSettings.X509CertificateFilePath; _options.X509CertificatePassword = settings.CertificateSettings.X509CertificatePassword; } _matcherMapper = new MatcherMapper(_settings); _mappingConverter = new MappingConverter(_matcherMapper); _mappingToFileSaver = new MappingToFileSaver(_settings, _mappingConverter); #if USE_ASPNETCORE _options.AdditionalServiceRegistration = _settings.AdditionalServiceRegistration; _options.CorsPolicyOptions = _settings.CorsPolicyOptions; _httpServer = new AspNetCoreSelfHost(_options, urlOptions); #else _httpServer = new OwinSelfHost(_options, urlOptions); #endif var startTask = _httpServer.StartAsync(); using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout)) { while (!_httpServer.IsStarted) { // Throw exception if service start fails if (_httpServer.RunningException != null) { throw new WireMockException($"Service start failed with error: {_httpServer.RunningException.Message}", _httpServer.RunningException); } if (ctsStartTimeout.IsCancellationRequested) { // In case of an aggregate exception, throw the exception. if (startTask.Exception != null) { throw new WireMockException($"Service start failed with error: {startTask.Exception.Message}", startTask.Exception); } // Else throw TimeoutException throw new TimeoutException($"Service start timed out after {TimeSpan.FromMilliseconds(settings.StartTimeout)}"); } ctsStartTimeout.Token.WaitHandle.WaitOne(ServerStartDelayInMs); } Urls = _httpServer.Urls.ToArray(); Ports = _httpServer.Ports; } if (settings.AllowBodyForAllHttpMethods == true) { _options.AllowBodyForAllHttpMethods = _settings.AllowBodyForAllHttpMethods; _settings.Logger.Info("AllowBodyForAllHttpMethods is set to True"); } if (settings.AllowOnlyDefinedHttpStatusCodeInResponse == true) { _options.AllowOnlyDefinedHttpStatusCodeInResponse = _settings.AllowOnlyDefinedHttpStatusCodeInResponse; _settings.Logger.Info("AllowOnlyDefinedHttpStatusCodeInResponse is set to True"); } if (settings.AllowPartialMapping == true) { AllowPartialMapping(); } if (settings.StartAdminInterface == true) { if (!string.IsNullOrEmpty(settings.AdminUsername) && !string.IsNullOrEmpty(settings.AdminPassword)) { SetBasicAuthentication(settings.AdminUsername, settings.AdminPassword); } if (!string.IsNullOrEmpty(settings.AdminAzureADTenant) && !string.IsNullOrEmpty(settings.AdminAzureADAudience)) { SetAzureADAuthentication(settings.AdminAzureADTenant, settings.AdminAzureADAudience); } InitAdmin(); } if (settings.ReadStaticMappings == true) { ReadStaticMappings(); } if (settings.WatchStaticMappings == true) { WatchStaticMappings(); } if (settings.ProxyAndRecordSettings != null) { InitProxyAndRecord(settings); } if (settings.RequestLogExpirationDuration != null) { SetRequestLogExpirationDuration(settings.RequestLogExpirationDuration); } if (settings.MaxRequestLogCount != null) { SetMaxRequestLogCount(settings.MaxRequestLogCount); } } /// <inheritdoc cref="IWireMockServer.Stop" /> [PublicAPI] public void Stop() { var result = _httpServer?.StopAsync(); result?.Wait(); // wait for stop to actually happen } #endregion /// <inheritdoc cref="IWireMockServer.AddCatchAllMapping" /> [PublicAPI] public void AddCatchAllMapping() { Given(Request.Create().WithPath("/*").UsingAnyMethod()) .WithGuid(Guid.Parse("90008000-0000-4444-a17e-669cd84f1f05")) .AtPriority(1000) .RespondWith(new DynamicResponseProvider(request => ResponseMessageBuilder.Create("No matching mapping found", 404))); } /// <inheritdoc cref="IWireMockServer.Reset" /> [PublicAPI] public void Reset() { ResetLogEntries(); ResetMappings(); } /// <inheritdoc cref="IWireMockServer.ResetMappings" /> [PublicAPI] public void ResetMappings() { foreach (var nonAdmin in _options.Mappings.ToArray().Where(m => !m.Value.IsAdminInterface)) { _options.Mappings.TryRemove(nonAdmin.Key, out _); } } /// <inheritdoc cref="IWireMockServer.DeleteMapping" /> [PublicAPI] public bool DeleteMapping(Guid guid) { // Check a mapping exists with the same GUID, if so, remove it. if (_options.Mappings.ContainsKey(guid)) { return _options.Mappings.TryRemove(guid, out _); } return false; } private bool DeleteMapping(string path) { // Check a mapping exists with the same path, if so, remove it. var mapping = _options.Mappings.ToArray().FirstOrDefault(entry => string.Equals(entry.Value.Path, path, StringComparison.OrdinalIgnoreCase)); return DeleteMapping(mapping.Key); } /// <inheritdoc cref="IWireMockServer.AddGlobalProcessingDelay" /> [PublicAPI] public void AddGlobalProcessingDelay(TimeSpan delay) { _options.RequestProcessingDelay = delay; } /// <inheritdoc cref="IWireMockServer.AllowPartialMapping" /> [PublicAPI] public void AllowPartialMapping(bool allow = true) { _settings.Logger.Info("AllowPartialMapping is set to {0}", allow); _options.AllowPartialMapping = allow; } /// <inheritdoc cref="IWireMockServer.SetAzureADAuthentication(string, string)" /> [PublicAPI] public void SetAzureADAuthentication([NotNull] string tenant, [NotNull] string audience) { Guard.NotNull(tenant, nameof(tenant)); Guard.NotNull(audience, nameof(audience)); #if NETSTANDARD1_3 throw new NotSupportedException("AzureADAuthentication is not supported for NETStandard 1.3"); #else _options.AuthenticationMatcher = new AzureADAuthenticationMatcher(tenant, audience); #endif } /// <inheritdoc cref="IWireMockServer.SetBasicAuthentication(string, string)" /> [PublicAPI] public void SetBasicAuthentication([NotNull] string username, [NotNull] string password) { Guard.NotNull(username, nameof(username)); Guard.NotNull(password, nameof(password)); _options.AuthenticationMatcher = new BasicAuthenticationMatcher(username, password); } /// <inheritdoc cref="IWireMockServer.RemoveAuthentication" /> [PublicAPI] public void RemoveAuthentication() { _options.AuthenticationMatcher = null; } /// <inheritdoc cref="IWireMockServer.SetMaxRequestLogCount" /> [PublicAPI] public void SetMaxRequestLogCount([CanBeNull] int? maxRequestLogCount) { _options.MaxRequestLogCount = maxRequestLogCount; } /// <inheritdoc cref="IWireMockServer.SetRequestLogExpirationDuration" /> [PublicAPI] public void SetRequestLogExpirationDuration([CanBeNull] int? requestLogExpirationDuration) { _options.RequestLogExpirationDuration = requestLogExpirationDuration; } /// <inheritdoc cref="IWireMockServer.ResetScenarios" /> [PublicAPI] public void ResetScenarios() { _options.Scenarios.Clear(); } /// <inheritdoc cref="IWireMockServer.WithMapping(MappingModel[])" /> [PublicAPI] public IWireMockServer WithMapping(params MappingModel[] mappings) { foreach (var mapping in mappings) { ConvertMappingAndRegisterAsRespondProvider(mapping, mapping.Guid ?? Guid.NewGuid()); } return this; } /// <inheritdoc cref="IWireMockServer.WithMapping(string)" /> [PublicAPI] public IWireMockServer WithMapping(string mappings) { var mappingModels = DeserializeJsonToArray<MappingModel>(mappings); foreach (var mappingModel in mappingModels) { ConvertMappingAndRegisterAsRespondProvider(mappingModel, mappingModel.Guid ?? Guid.NewGuid()); } return this; } /// <summary> /// The given. /// </summary> /// <param name="requestMatcher">The request matcher.</param> /// <param name="saveToFile">Optional boolean to indicate if this mapping should be saved as static mapping file.</param> /// <returns>The <see cref="IRespondWithAProvider"/>.</returns> [PublicAPI] public IRespondWithAProvider Given(IRequestMatcher requestMatcher, bool saveToFile = false) { return new RespondWithAProvider(RegisterMapping, requestMatcher, _settings, saveToFile); } private void RegisterMapping(IMapping mapping, bool saveToFile) { // Check a mapping exists with the same Guid, if so, replace it. if (_options.Mappings.ContainsKey(mapping.Guid)) { _options.Mappings[mapping.Guid] = mapping; } else { _options.Mappings.TryAdd(mapping.Guid, mapping); } if (saveToFile) { _mappingToFileSaver.SaveMappingToFile(mapping); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using GitHubHookApi.Areas.HelpPage.ModelDescriptions; using GitHubHookApi.Areas.HelpPage.Models; namespace GitHubHookApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// ZlibCodec.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-November-03 15:40:51> // // ------------------------------------------------------------------ // // This module defines a Codec for ZLIB compression and // decompression. This code extends code that was based the jzlib // implementation of zlib, but this code is completely novel. The codec // class is new, and encapsulates some behaviors that are new, and some // that were present in other classes in the jzlib code base. In // keeping with the license for jzlib, the copyright to the jzlib code // is included below. // // ------------------------------------------------------------------ // // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the distribution. // // 3. The names of the authors may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. // // ----------------------------------------------------------------------- // // This program is based on zlib-1.1.3; credit to authors // Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) // and contributors of zlib. // // ----------------------------------------------------------------------- using System; using Interop=System.Runtime.InteropServices; namespace Ionic.Zlib { /// <summary> /// Encoder and Decoder for ZLIB and DEFLATE (IETF RFC1950 and RFC1951). /// </summary> /// /// <remarks> /// This class compresses and decompresses data according to the Deflate algorithm /// and optionally, the ZLIB format, as documented in <see /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950 - ZLIB</see> and <see /// href="http://www.ietf.org/rfc/rfc1951.txt">RFC 1951 - DEFLATE</see>. /// </remarks> sealed public class ZlibCodec { /// <summary> /// The buffer from which data is taken. /// </summary> public byte[] InputBuffer; /// <summary> /// An index into the InputBuffer array, indicating where to start reading. /// </summary> public int NextIn; /// <summary> /// The number of bytes available in the InputBuffer, starting at NextIn. /// </summary> /// <remarks> /// Generally you should set this to InputBuffer.Length before the first Inflate() or Deflate() call. /// The class will update this number as calls to Inflate/Deflate are made. /// </remarks> public int AvailableBytesIn; /// <summary> /// Total number of bytes read so far, through all calls to Inflate()/Deflate(). /// </summary> public long TotalBytesIn; /// <summary> /// Buffer to store output data. /// </summary> public byte[] OutputBuffer; /// <summary> /// An index into the OutputBuffer array, indicating where to start writing. /// </summary> public int NextOut; /// <summary> /// The number of bytes available in the OutputBuffer, starting at NextOut. /// </summary> /// <remarks> /// Generally you should set this to OutputBuffer.Length before the first Inflate() or Deflate() call. /// The class will update this number as calls to Inflate/Deflate are made. /// </remarks> public int AvailableBytesOut; /// <summary> /// Total number of bytes written to the output so far, through all calls to Inflate()/Deflate(). /// </summary> public long TotalBytesOut; /// <summary> /// used for diagnostics, when something goes wrong! /// </summary> public System.String Message; internal DeflateManager dstate; internal InflateManager istate; internal uint _Adler32; /// <summary> /// The compression level to use in this codec. Useful only in compression mode. /// </summary> public CompressionLevel CompressLevel = CompressionLevel.Default; /// <summary> /// The number of Window Bits to use. /// </summary> /// <remarks> /// This gauges the size of the sliding window, and hence the /// compression effectiveness as well as memory consumption. It's best to just leave this /// setting alone if you don't know what it is. The maximum value is 15 bits, which implies /// a 32k window. /// </remarks> public int WindowBits = ZlibConstants.WindowBitsDefault; /// <summary> /// The compression strategy to use. /// </summary> /// <remarks> /// This is only effective in compression. The theory offered by ZLIB is that different /// strategies could potentially produce significant differences in compression behavior /// for different data sets. Unfortunately I don't have any good recommendations for how /// to set it differently. When I tested changing the strategy I got minimally different /// compression performance. It's best to leave this property alone if you don't have a /// good feel for it. Or, you may want to produce a test harness that runs through the /// different strategy options and evaluates them on different file types. If you do that, /// let me know your results. /// </remarks> public CompressionStrategy Strategy = CompressionStrategy.Default; /// <summary> /// The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this. /// </summary> public int Adler32 { get { return (int)_Adler32; } } /// <summary> /// Create a ZlibCodec. /// </summary> /// <remarks> /// If you use this default constructor, you will later have to explicitly call /// InitializeInflate() or InitializeDeflate() before using the ZlibCodec to compress /// or decompress. /// </remarks> public ZlibCodec() { } /// <summary> /// Create a ZlibCodec that either compresses or decompresses. /// </summary> /// <param name="mode"> /// Indicates whether the codec should compress (deflate) or decompress (inflate). /// </param> public ZlibCodec(CompressionMode mode) { if (mode == CompressionMode.Compress) { int rc = InitializeDeflate(); if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for deflate."); } else if (mode == CompressionMode.Decompress) { int rc = InitializeInflate(); if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for inflate."); } else throw new ZlibException("Invalid ZlibStreamFlavor."); } /// <summary> /// Initialize the inflation state. /// </summary> /// <remarks> /// It is not necessary to call this before using the ZlibCodec to inflate data; /// It is implicitly called when you call the constructor. /// </remarks> /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate() { return InitializeInflate(this.WindowBits); } /// <summary> /// Initialize the inflation state with an explicit flag to /// govern the handling of RFC1950 header bytes. /// </summary> /// /// <remarks> /// By default, the ZLIB header defined in <see /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</see> is expected. If /// you want to read a zlib stream you should specify true for /// expectRfc1950Header. If you have a deflate stream, you will want to specify /// false. It is only necessary to invoke this initializer explicitly if you /// want to specify false. /// </remarks> /// /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte /// pair when reading the stream of data to be inflated.</param> /// /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate(bool expectRfc1950Header) { return InitializeInflate(this.WindowBits, expectRfc1950Header); } /// <summary> /// Initialize the ZlibCodec for inflation, with the specified number of window bits. /// </summary> /// <param name="windowBits">The number of window bits to use. If you need to ask what that is, /// then you shouldn't be calling this initializer.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeInflate(int windowBits) { this.WindowBits = windowBits; return InitializeInflate(windowBits, true); } /// <summary> /// Initialize the inflation state with an explicit flag to govern the handling of /// RFC1950 header bytes. /// </summary> /// /// <remarks> /// If you want to read a zlib stream you should specify true for /// expectRfc1950Header. In this case, the library will expect to find a ZLIB /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC /// 1950</see>, in the compressed stream. If you will be reading a DEFLATE or /// GZIP stream, which does not have such a header, you will want to specify /// false. /// </remarks> /// /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte pair when reading /// the stream of data to be inflated.</param> /// <param name="windowBits">The number of window bits to use. If you need to ask what that is, /// then you shouldn't be calling this initializer.</param> /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate(int windowBits, bool expectRfc1950Header) { this.WindowBits = windowBits; if (dstate != null) throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate()."); istate = new InflateManager(expectRfc1950Header); return istate.Initialize(this, windowBits); } /// <summary> /// Inflate the data in the InputBuffer, placing the result in the OutputBuffer. /// </summary> /// <remarks> /// You must have set InputBuffer and OutputBuffer, NextIn and NextOut, and AvailableBytesIn and /// AvailableBytesOut before calling this method. /// </remarks> /// <example> /// <code> /// private void InflateBuffer() /// { /// int bufferSize = 1024; /// byte[] buffer = new byte[bufferSize]; /// ZlibCodec decompressor = new ZlibCodec(); /// /// Console.WriteLine("\n============================================"); /// Console.WriteLine("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length); /// MemoryStream ms = new MemoryStream(DecompressedBytes); /// /// int rc = decompressor.InitializeInflate(); /// /// decompressor.InputBuffer = CompressedBytes; /// decompressor.NextIn = 0; /// decompressor.AvailableBytesIn = CompressedBytes.Length; /// /// decompressor.OutputBuffer = buffer; /// /// // pass 1: inflate /// do /// { /// decompressor.NextOut = 0; /// decompressor.AvailableBytesOut = buffer.Length; /// rc = decompressor.Inflate(FlushType.None); /// /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END) /// throw new Exception("inflating: " + decompressor.Message); /// /// ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut); /// } /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0); /// /// // pass 2: finish and flush /// do /// { /// decompressor.NextOut = 0; /// decompressor.AvailableBytesOut = buffer.Length; /// rc = decompressor.Inflate(FlushType.Finish); /// /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK) /// throw new Exception("inflating: " + decompressor.Message); /// /// if (buffer.Length - decompressor.AvailableBytesOut &gt; 0) /// ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut); /// } /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0); /// /// decompressor.EndInflate(); /// } /// /// </code> /// </example> /// <param name="flush">The flush to use when inflating.</param> /// <returns>Z_OK if everything goes well.</returns> public int Inflate(FlushType flush) { if (istate == null) throw new ZlibException("No Inflate State!"); return istate.Inflate(flush); } /// <summary> /// Ends an inflation session. /// </summary> /// <remarks> /// Call this after successively calling Inflate(). This will cause all buffers to be flushed. /// After calling this you cannot call Inflate() without a intervening call to one of the /// InitializeInflate() overloads. /// </remarks> /// <returns>Z_OK if everything goes well.</returns> public int EndInflate() { if (istate == null) throw new ZlibException("No Inflate State!"); int ret = istate.End(); istate = null; return ret; } /// <summary> /// I don't know what this does! /// </summary> /// <returns>Z_OK if everything goes well.</returns> public int SyncInflate() { if (istate == null) throw new ZlibException("No Inflate State!"); return istate.Sync(); } /// <summary> /// Initialize the ZlibCodec for deflation operation. /// </summary> /// <remarks> /// The codec will use the MAX window bits and the default level of compression. /// </remarks> /// <example> /// <code> /// int bufferSize = 40000; /// byte[] CompressedBytes = new byte[bufferSize]; /// byte[] DecompressedBytes = new byte[bufferSize]; /// /// ZlibCodec compressor = new ZlibCodec(); /// /// compressor.InitializeDeflate(CompressionLevel.Default); /// /// compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress); /// compressor.NextIn = 0; /// compressor.AvailableBytesIn = compressor.InputBuffer.Length; /// /// compressor.OutputBuffer = CompressedBytes; /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = CompressedBytes.Length; /// /// while (compressor.TotalBytesIn != TextToCompress.Length &amp;&amp; compressor.TotalBytesOut &lt; bufferSize) /// { /// compressor.Deflate(FlushType.None); /// } /// /// while (true) /// { /// int rc= compressor.Deflate(FlushType.Finish); /// if (rc == ZlibConstants.Z_STREAM_END) break; /// } /// /// compressor.EndDeflate(); /// /// </code> /// </example> /// <returns>Z_OK if all goes well. You generally don't need to check the return code.</returns> public int InitializeDeflate() { return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel. /// </summary> /// <remarks> /// The codec will use the maximum window bits (15) and the specified /// CompressionLevel. It will emit a ZLIB stream as it compresses. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level) { this.CompressLevel = level; return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel, /// and the explicit flag governing whether to emit an RFC1950 header byte pair. /// </summary> /// <remarks> /// The codec will use the maximum window bits (15) and the specified CompressionLevel. /// If you want to generate a zlib stream, you should specify true for /// wantRfc1950Header. In this case, the library will emit a ZLIB /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC /// 1950</see>, in the compressed stream. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, bool wantRfc1950Header) { this.CompressLevel = level; return _InternalInitializeDeflate(wantRfc1950Header); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel, /// and the specified number of window bits. /// </summary> /// <remarks> /// The codec will use the specified number of window bits and the specified CompressionLevel. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, int bits) { this.CompressLevel = level; this.WindowBits = bits; return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified /// CompressionLevel, the specified number of window bits, and the explicit flag /// governing whether to emit an RFC1950 header byte pair. /// </summary> /// /// <param name="level">The compression level for the codec.</param> /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param> /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, int bits, bool wantRfc1950Header) { this.CompressLevel = level; this.WindowBits = bits; return _InternalInitializeDeflate(wantRfc1950Header); } private int _InternalInitializeDeflate(bool wantRfc1950Header) { if (istate != null) throw new ZlibException("You may not call InitializeDeflate() after calling InitializeInflate()."); dstate = new DeflateManager(); dstate.WantRfc1950HeaderBytes = wantRfc1950Header; return dstate.Initialize(this, this.CompressLevel, this.WindowBits, this.Strategy); } /// <summary> /// Deflate one batch of data. /// </summary> /// <remarks> /// You must have set InputBuffer and OutputBuffer before calling this method. /// </remarks> /// <example> /// <code> /// private void DeflateBuffer(CompressionLevel level) /// { /// int bufferSize = 1024; /// byte[] buffer = new byte[bufferSize]; /// ZlibCodec compressor = new ZlibCodec(); /// /// Console.WriteLine("\n============================================"); /// Console.WriteLine("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length); /// MemoryStream ms = new MemoryStream(); /// /// int rc = compressor.InitializeDeflate(level); /// /// compressor.InputBuffer = UncompressedBytes; /// compressor.NextIn = 0; /// compressor.AvailableBytesIn = UncompressedBytes.Length; /// /// compressor.OutputBuffer = buffer; /// /// // pass 1: deflate /// do /// { /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = buffer.Length; /// rc = compressor.Deflate(FlushType.None); /// /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END) /// throw new Exception("deflating: " + compressor.Message); /// /// ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut); /// } /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0); /// /// // pass 2: finish and flush /// do /// { /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = buffer.Length; /// rc = compressor.Deflate(FlushType.Finish); /// /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK) /// throw new Exception("deflating: " + compressor.Message); /// /// if (buffer.Length - compressor.AvailableBytesOut &gt; 0) /// ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut); /// } /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0); /// /// compressor.EndDeflate(); /// /// ms.Seek(0, SeekOrigin.Begin); /// CompressedBytes = new byte[compressor.TotalBytesOut]; /// ms.Read(CompressedBytes, 0, CompressedBytes.Length); /// } /// </code> /// </example> /// <param name="flush">whether to flush all data as you deflate. Generally you will want to /// use Z_NO_FLUSH here, in a series of calls to Deflate(), and then call EndDeflate() to /// flush everything. /// </param> /// <returns>Z_OK if all goes well.</returns> public int Deflate(FlushType flush) { if (dstate == null) throw new ZlibException("No Deflate State!"); return dstate.Deflate(flush); } /// <summary> /// End a deflation session. /// </summary> /// <remarks> /// Call this after making a series of one or more calls to Deflate(). All buffers are flushed. /// </remarks> /// <returns>Z_OK if all goes well.</returns> public int EndDeflate() { if (dstate == null) throw new ZlibException("No Deflate State!"); // TODO: dinoch Tue, 03 Nov 2009 15:39 (test this) //int ret = dstate.End(); dstate = null; return ZlibConstants.Z_OK; //ret; } /// <summary> /// Reset a codec for another deflation session. /// </summary> /// <remarks> /// Call this to reset the deflation state. For example if a thread is deflating /// non-consecutive blocks, you can call Reset() after the Deflate(Sync) of the first /// block and before the next Deflate(None) of the second block. /// </remarks> /// <returns>Z_OK if all goes well.</returns> public void ResetDeflate() { if (dstate == null) throw new ZlibException("No Deflate State!"); dstate.Reset(); } /// <summary> /// Set the CompressionStrategy and CompressionLevel for a deflation session. /// </summary> /// <param name="level">the level of compression to use.</param> /// <param name="strategy">the strategy to use for compression.</param> /// <returns>Z_OK if all goes well.</returns> public int SetDeflateParams(CompressionLevel level, CompressionStrategy strategy) { if (dstate == null) throw new ZlibException("No Deflate State!"); return dstate.SetParams(level, strategy); } /// <summary> /// Set the dictionary to be used for either Inflation or Deflation. /// </summary> /// <param name="dictionary">The dictionary bytes to use.</param> /// <returns>Z_OK if all goes well.</returns> public int SetDictionary(byte[] dictionary) { if (istate != null) return istate.SetDictionary(dictionary); if (dstate != null) return dstate.SetDictionary(dictionary); throw new ZlibException("No Inflate or Deflate state!"); } // Flush as much pending output as possible. All deflate() output goes // through this function so some applications may wish to modify it // to avoid allocating a large strm->next_out buffer and copying into it. // (See also read_buf()). internal void flush_pending() { int len = dstate.pendingCount; if (len > AvailableBytesOut) len = AvailableBytesOut; if (len == 0) return; if (dstate.pending.Length <= dstate.nextPending || OutputBuffer.Length <= NextOut || dstate.pending.Length < (dstate.nextPending + len) || OutputBuffer.Length < (NextOut + len)) { throw new ZlibException(String.Format("Invalid State. (pending.Length={0}, pendingCount={1})", dstate.pending.Length, dstate.pendingCount)); } Array.Copy(dstate.pending, dstate.nextPending, OutputBuffer, NextOut, len); NextOut += len; dstate.nextPending += len; TotalBytesOut += len; AvailableBytesOut -= len; dstate.pendingCount -= len; if (dstate.pendingCount == 0) { dstate.nextPending = 0; } } // Read a new buffer from the current input stream, update the adler32 // and total number of bytes read. All deflate() input goes through // this function so some applications may wish to modify it to avoid // allocating a large strm->next_in buffer and copying from it. // (See also flush_pending()). internal int read_buf(byte[] buf, int start, int size) { int len = AvailableBytesIn; if (len > size) len = size; if (len == 0) return 0; AvailableBytesIn -= len; if (dstate.WantRfc1950HeaderBytes) { _Adler32 = Adler.Adler32(_Adler32, InputBuffer, NextIn, len); } Array.Copy(InputBuffer, NextIn, buf, start, len); NextIn += len; TotalBytesIn += len; return len; } } }
namespace java.util { [global::MonoJavaBridge.JavaClass()] public partial class SimpleTimeZone : java.util.TimeZone { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected SimpleTimeZone(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override bool equals(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.SimpleTimeZone.staticClass, "equals", "(Ljava/lang/Object;)Z", ref global::java.util.SimpleTimeZone._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.util.SimpleTimeZone.staticClass, "toString", "()Ljava/lang/String;", ref global::java.util.SimpleTimeZone._m1) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m2; public override int hashCode() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.SimpleTimeZone.staticClass, "hashCode", "()I", ref global::java.util.SimpleTimeZone._m2); } private static global::MonoJavaBridge.MethodId _m3; public override global::java.lang.Object clone() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.SimpleTimeZone.staticClass, "clone", "()Ljava/lang/Object;", ref global::java.util.SimpleTimeZone._m3) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m4; public override int getOffset(long arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.SimpleTimeZone.staticClass, "getOffset", "(J)I", ref global::java.util.SimpleTimeZone._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; public override int getOffset(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.SimpleTimeZone.staticClass, "getOffset", "(IIIIII)I", ref global::java.util.SimpleTimeZone._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } public new int RawOffset { get { return getRawOffset(); } set { setRawOffset(value); } } private static global::MonoJavaBridge.MethodId _m6; public override int getRawOffset() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.SimpleTimeZone.staticClass, "getRawOffset", "()I", ref global::java.util.SimpleTimeZone._m6); } private static global::MonoJavaBridge.MethodId _m7; public override bool hasSameRules(java.util.TimeZone arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.SimpleTimeZone.staticClass, "hasSameRules", "(Ljava/util/TimeZone;)Z", ref global::java.util.SimpleTimeZone._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m8; public override void setRawOffset(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.SimpleTimeZone.staticClass, "setRawOffset", "(I)V", ref global::java.util.SimpleTimeZone._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int DSTSavings { get { return getDSTSavings(); } set { setDSTSavings(value); } } private static global::MonoJavaBridge.MethodId _m9; public override int getDSTSavings() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.SimpleTimeZone.staticClass, "getDSTSavings", "()I", ref global::java.util.SimpleTimeZone._m9); } private static global::MonoJavaBridge.MethodId _m10; public override bool useDaylightTime() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.SimpleTimeZone.staticClass, "useDaylightTime", "()Z", ref global::java.util.SimpleTimeZone._m10); } private static global::MonoJavaBridge.MethodId _m11; public override bool inDaylightTime(java.util.Date arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.SimpleTimeZone.staticClass, "inDaylightTime", "(Ljava/util/Date;)Z", ref global::java.util.SimpleTimeZone._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int StartYear { set { setStartYear(value); } } private static global::MonoJavaBridge.MethodId _m12; public virtual void setStartYear(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.SimpleTimeZone.staticClass, "setStartYear", "(I)V", ref global::java.util.SimpleTimeZone._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m13; public virtual void setStartRule(int arg0, int arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.SimpleTimeZone.staticClass, "setStartRule", "(III)V", ref global::java.util.SimpleTimeZone._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m14; public virtual void setStartRule(int arg0, int arg1, int arg2, int arg3, bool arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.SimpleTimeZone.staticClass, "setStartRule", "(IIIIZ)V", ref global::java.util.SimpleTimeZone._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m15; public virtual void setStartRule(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.SimpleTimeZone.staticClass, "setStartRule", "(IIII)V", ref global::java.util.SimpleTimeZone._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m16; public virtual void setEndRule(int arg0, int arg1, int arg2, int arg3, bool arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.SimpleTimeZone.staticClass, "setEndRule", "(IIIIZ)V", ref global::java.util.SimpleTimeZone._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m17; public virtual void setEndRule(int arg0, int arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.SimpleTimeZone.staticClass, "setEndRule", "(III)V", ref global::java.util.SimpleTimeZone._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m18; public virtual void setEndRule(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.SimpleTimeZone.staticClass, "setEndRule", "(IIII)V", ref global::java.util.SimpleTimeZone._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m19; public virtual void setDSTSavings(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.SimpleTimeZone.staticClass, "setDSTSavings", "(I)V", ref global::java.util.SimpleTimeZone._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m20; public SimpleTimeZone(int arg0, java.lang.String arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.SimpleTimeZone._m20.native == global::System.IntPtr.Zero) global::java.util.SimpleTimeZone._m20 = @__env.GetMethodIDNoThrow(global::java.util.SimpleTimeZone.staticClass, "<init>", "(ILjava/lang/String;IIIIIIII)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.SimpleTimeZone.staticClass, global::java.util.SimpleTimeZone._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg9)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m21; public SimpleTimeZone(int arg0, java.lang.String arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.SimpleTimeZone._m21.native == global::System.IntPtr.Zero) global::java.util.SimpleTimeZone._m21 = @__env.GetMethodIDNoThrow(global::java.util.SimpleTimeZone.staticClass, "<init>", "(ILjava/lang/String;IIIIIIIII)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.SimpleTimeZone.staticClass, global::java.util.SimpleTimeZone._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg9), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg10)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m22; public SimpleTimeZone(int arg0, java.lang.String arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.SimpleTimeZone._m22.native == global::System.IntPtr.Zero) global::java.util.SimpleTimeZone._m22 = @__env.GetMethodIDNoThrow(global::java.util.SimpleTimeZone.staticClass, "<init>", "(ILjava/lang/String;IIIIIIIIIII)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.SimpleTimeZone.staticClass, global::java.util.SimpleTimeZone._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg9), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg10), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg11), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg12)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m23; public SimpleTimeZone(int arg0, java.lang.String arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.SimpleTimeZone._m23.native == global::System.IntPtr.Zero) global::java.util.SimpleTimeZone._m23 = @__env.GetMethodIDNoThrow(global::java.util.SimpleTimeZone.staticClass, "<init>", "(ILjava/lang/String;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.SimpleTimeZone.staticClass, global::java.util.SimpleTimeZone._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } public static int WALL_TIME { get { return 0; } } public static int STANDARD_TIME { get { return 1; } } public static int UTC_TIME { get { return 2; } } static SimpleTimeZone() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.SimpleTimeZone.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/SimpleTimeZone")); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq.Expressions; using Xunit; namespace System.Linq.Tests { public class GroupJoinTests : EnumerableBasedTests { public struct CustomerRec { public string name; public int? custID; } public struct OrderRec { public int? orderID; public int? custID; public int? total; } public struct AnagramRec { public string name; public int? orderID; public int? total; } public struct JoinRec : IEquatable<JoinRec> { public string name; public int?[] orderID; public int?[] total; public override int GetHashCode() { // Not great, but it'll serve. return name.GetHashCode() ^ orderID.Length ^ (total.Length * 31); } public bool Equals(JoinRec other) { if (!string.Equals(name, other.name)) return false; if (orderID == null) { if (other.orderID != null) return false; } else { if (other.orderID == null) return false; if (orderID.Length != other.orderID.Length) return false; for (int i = 0; i != other.orderID.Length; ++i) if (orderID[i] != other.orderID[i]) return false; } if (total == null) { if (other.total != null) return false; } else { if (other.total == null) return false; if (total.Length != other.total.Length) return false; for (int i = 0; i != other.total.Length; ++i) if (total[i] != other.total[i]) return false; } return true; } public override bool Equals(object obj) { return obj is JoinRec && Equals((JoinRec)obj); } } [Fact] public void OuterEmptyInnerNonEmpty() { CustomerRec[] outer = { }; OrderRec[] inner = new [] { new OrderRec{ orderID = 45321, custID = 98022, total = 50 }, new OrderRec{ orderID = 97865, custID = 32103, total = 25 } }; Assert.Empty(outer.AsQueryable().GroupJoin(inner.AsQueryable(), e => e.custID, e => e.custID, (cr, orIE) => new JoinRec { name = cr.name, orderID = orIE.Select(o => o.orderID).ToArray(), total = orIE.Select(o => o.total).ToArray() })); } [Fact] public void CustomComparer() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new [] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Tim", orderID = new int?[]{ 93489 }, total = new int?[]{ 45 } }, new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Robert", orderID = new int?[]{ 93483 }, total = new int?[]{ 19 } } }; Assert.Equal(expected, outer.AsQueryable().GroupJoin(inner.AsQueryable(), e => e.name, e => e.name, (cr, arIE) => new JoinRec { name = cr.name, orderID = arIE.Select(o => o.orderID).ToArray(), total = arIE.Select(o => o.total).ToArray() }, new AnagramEqualityComparer())); } [Fact] public void OuterNull() { IQueryable<CustomerRec> outer = null; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("outer", () => outer.GroupJoin(inner.AsQueryable(), e => e.name, e => e.name, (cr, arIE) => new JoinRec { name = cr.name, orderID = arIE.Select(o => o.orderID).ToArray(), total = arIE.Select(o => o.total).ToArray() }, new AnagramEqualityComparer())); } [Fact] public void InnerNull() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; IQueryable<AnagramRec> inner = null; Assert.Throws<ArgumentNullException>("inner", () => outer.AsQueryable().GroupJoin(inner, e => e.name, e => e.name, (cr, arIE) => new JoinRec { name = cr.name, orderID = arIE.Select(o => o.orderID).ToArray(), total = arIE.Select(o => o.total).ToArray() }, new AnagramEqualityComparer())); } [Fact] public void OuterKeySelectorNull() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("outerKeySelector", () => outer.AsQueryable().GroupJoin(inner.AsQueryable(), null, e => e.name, (cr, arIE) => new JoinRec { name = cr.name, orderID = arIE.Select(o => o.orderID).ToArray(), total = arIE.Select(o => o.total).ToArray() }, new AnagramEqualityComparer())); } [Fact] public void InnerKeySelectorNull() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("innerKeySelector", () => outer.AsQueryable().GroupJoin(inner.AsQueryable(), e => e.name, null, (cr, arIE) => new JoinRec { name = cr.name, orderID = arIE.Select(o => o.orderID).ToArray(), total = arIE.Select(o => o.total).ToArray() }, new AnagramEqualityComparer())); } [Fact] public void ResultSelectorNull() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("resultSelector", () => outer.AsQueryable().GroupJoin(inner.AsQueryable(), e => e.name, e => e.name, (Expression<Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec>>)null, new AnagramEqualityComparer())); } [Fact] public void OuterNullNoComparer() { IQueryable<CustomerRec> outer = null; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("outer", () => outer.GroupJoin(inner.AsQueryable(), e => e.name, e => e.name, (cr, arIE) => new JoinRec { name = cr.name, orderID = arIE.Select(o => o.orderID).ToArray(), total = arIE.Select(o => o.total).ToArray() })); } [Fact] public void InnerNullNoComparer() { CustomerRec[] outer = new[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; IQueryable<AnagramRec> inner = null; Assert.Throws<ArgumentNullException>("inner", () => outer.AsQueryable().GroupJoin(inner, e => e.name, e => e.name, (cr, arIE) => new JoinRec { name = cr.name, orderID = arIE.Select(o => o.orderID).ToArray(), total = arIE.Select(o => o.total).ToArray() })); } [Fact] public void OuterKeySelectorNullNoComparer() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("outerKeySelector", () => outer.AsQueryable().GroupJoin(inner.AsQueryable(), null, e => e.name, (cr, arIE) => new JoinRec { name = cr.name, orderID = arIE.Select(o => o.orderID).ToArray(), total = arIE.Select(o => o.total).ToArray() })); } [Fact] public void InnerKeySelectorNullNoComparer() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("innerKeySelector", () => outer.AsQueryable().GroupJoin(inner.AsQueryable(), e => e.name, null, (cr, arIE) => new JoinRec { name = cr.name, orderID = arIE.Select(o => o.orderID).ToArray(), total = arIE.Select(o => o.total).ToArray() })); } [Fact] public void ResultSelectorNullNoComparer() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; Assert.Throws<ArgumentNullException>("resultSelector", () => outer.AsQueryable().GroupJoin(inner.AsQueryable(), e => e.name, e => e.name, (Expression<Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec>>)null)); } [Fact] public void NullComparer() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new [] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Robert", orderID = new int?[]{ 93483 }, total = new int?[]{ 19 } } }; Assert.Equal(expected, outer.AsQueryable().GroupJoin(inner.AsQueryable(), e => e.name, e => e.name, (cr, arIE) => new JoinRec { name = cr.name, orderID = arIE.Select(o => o.orderID).ToArray(), total = arIE.Select(o => o.total).ToArray() }, null)); } [Fact] public void GroupJoin1() { var count = (new int[] { 0, 1, 2 }).AsQueryable().GroupJoin(new int[] { 1, 2, 3 }, n1 => n1, n2 => n2, (n1, n2) => n1).Count(); Assert.Equal(3, count); } [Fact] public void GroupJoin2() { var count = (new int[] { 0, 1, 2 }).AsQueryable().GroupJoin(new int[] { 1, 2, 3 }, n1 => n1, n2 => n2, (n1, n2) => n1, EqualityComparer<int>.Default).Count(); Assert.Equal(3, count); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Linq; #if ASPNETWEBAPI using System.Web.Http.Routing.Constraints; #else using System.Web.Mvc.Routing.Constraints; using System.Web.Routing; #endif using Microsoft.TestCommon; #if ASPNETWEBAPI namespace System.Web.Http.Routing #else namespace System.Web.Mvc.Routing #endif { public class InlineRouteTemplateParserTests { #if ASPNETWEBAPI private static readonly RouteParameter OptionalParameter = RouteParameter.Optional; #else private static readonly UrlParameter OptionalParameter = UrlParameter.Optional; #endif [Fact] public void ParseRouteTemplate_ChainedConstraintAndDefault() { var result = Act(@"hello/{param:int=111111}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.Equal("111111", result.Defaults["param"]); Assert.IsType<IntRouteConstraint>(result.Constraints["param"]); } [Fact] public void ParseRouteTemplate_ChainedConstraintWithArgumentsAndDefault() { var result = Act(@"hello/{param:regex(\d+)=111111}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.Equal("111111", result.Defaults["param"]); Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]); Assert.Equal(@"\d+", ((RegexRouteConstraint)result.Constraints["param"]).Pattern); } [Fact] public void ParseRouteTemplate_ChainedConstraintAndOptional() { var result = Act(@"hello/{param:int?}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.Equal(OptionalParameter, result.Defaults["param"]); Assert.IsType<OptionalRouteConstraint>(result.Constraints["param"]); var constraint = (OptionalRouteConstraint)result.Constraints["param"]; Assert.IsType<IntRouteConstraint>(constraint.InnerConstraint); } [Fact] public void ParseRouteTemplate_ChainedConstraintWithArgumentsAndOptional() { var result = Act(@"hello/{param:regex(\d+)?}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.Equal(OptionalParameter, result.Defaults["param"]); Assert.IsType<OptionalRouteConstraint>(result.Constraints["param"]); var constraint = (OptionalRouteConstraint)result.Constraints["param"]; Assert.Equal(@"\d+", ((RegexRouteConstraint)constraint.InnerConstraint).Pattern); } [Fact] public void ParseRouteTemplate_ChainedConstraints() { var result = Act(@"hello/{param:regex(\d+):regex(\w+)}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.IsType<CompoundRouteConstraint>(result.Constraints["param"]); CompoundRouteConstraint constraint = (CompoundRouteConstraint)result.Constraints["param"]; Assert.Equal(@"\d+", ((RegexRouteConstraint)constraint.Constraints.ElementAt(0)).Pattern); Assert.Equal(@"\w+", ((RegexRouteConstraint)constraint.Constraints.ElementAt(1)).Pattern); } [Fact] public void ParseRouteTemplate_Constraint() { var result = Act(@"hello/{param:regex(\d+)}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]); Assert.Equal(@"\d+", ((RegexRouteConstraint)result.Constraints["param"]).Pattern); } [Fact] public void ParseRouteTemplate_ConstraintsDefaultsAndOptionalsInMultipleSections() { var result = Act(@"some/url-{p1:alpha:length(3)=hello}/{p2=abc}/{p3?}"); Assert.Equal("some/url-{p1}/{p2}/{p3}", result.RouteUrl); Assert.Equal("hello", result.Defaults["p1"]); Assert.Equal("abc", result.Defaults["p2"]); Assert.Equal(OptionalParameter, result.Defaults["p3"]); Assert.IsType<CompoundRouteConstraint>(result.Constraints["p1"]); CompoundRouteConstraint constraint = (CompoundRouteConstraint)result.Constraints["p1"]; Assert.IsType<AlphaRouteConstraint>(constraint.Constraints.ElementAt(0)); Assert.IsType<LengthRouteConstraint>(constraint.Constraints.ElementAt(1)); } [Fact] public void ParseRouteTemplate_NoTokens() { var result = Act("hello/world"); Assert.Equal("hello/world", result.RouteUrl); } [Fact] public void ParseRouteTemplate_OptionalParam() { var result = Act("hello/{param?}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.Equal(OptionalParameter, result.Defaults["param"]); } [Fact] public void ParseRouteTemplate_ParamDefault() { var result = Act("hello/{param=world}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.Equal("world", result.Defaults["param"]); } [Fact] public void ParseRouteTemplate_RegexConstraintWithClosingBraceInPattern() { var result = Act(@"hello/{param:regex(\})}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]); Assert.Equal(@"\}", ((RegexRouteConstraint)result.Constraints["param"]).Pattern); } [Fact] public void ParseRouteTemplate_RegexConstraintWithClosingParenInPattern() { var result = Act(@"hello/{param:regex(\))}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]); Assert.Equal(@"\)", ((RegexRouteConstraint)result.Constraints["param"]).Pattern); } [Fact] public void ParseRouteTemplate_RegexConstraintWithColonInPattern() { var result = Act(@"hello/{param:regex(:)}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]); Assert.Equal(@":", ((RegexRouteConstraint)result.Constraints["param"]).Pattern); } [Fact] public void ParseRouteTemplate_RegexConstraintWithCommaInPattern() { var result = Act(@"hello/{param:regex(\w,\w)}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]); Assert.Equal(@"\w,\w", ((RegexRouteConstraint)result.Constraints["param"]).Pattern); } [Fact] public void ParseRouteTemplate_RegexConstraintWithEqualsSignInPattern() { var result = Act(@"hello/{param:regex(=)}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.DoesNotContain("param", result.Defaults.Keys); Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]); Assert.Equal(@"=", ((RegexRouteConstraint)result.Constraints["param"]).Pattern); } [Fact] public void ParseRouteTemplate_RegexConstraintWithOpenBraceInPattern() { var result = Act(@"hello/{param:regex(\{)}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]); Assert.Equal(@"\{", ((RegexRouteConstraint)result.Constraints["param"]).Pattern); } [Fact] public void ParseRouteTemplate_RegexConstraintWithOpenParenInPattern() { var result = Act(@"hello/{param:regex(\()}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]); Assert.Equal(@"\(", ((RegexRouteConstraint)result.Constraints["param"]).Pattern); } [Fact] public void ParseRouteTemplate_RegexConstraintWithQuestionMarkInPattern() { var result = Act(@"hello/{param:regex(\?)}"); Assert.Equal("hello/{param}", result.RouteUrl); Assert.DoesNotContain("param", result.Defaults.Keys); Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]); Assert.Equal(@"\?", ((RegexRouteConstraint)result.Constraints["param"]).Pattern); } private ParseResult Act(string template) { var result = new ParseResult(); #if ASPNETWEBAPI result.Constraints = new HttpRouteValueDictionary(); result.Defaults = new HttpRouteValueDictionary(); #else result.Constraints = new RouteValueDictionary(); result.Defaults = new RouteValueDictionary(); #endif result.RouteUrl = InlineRouteTemplateParser.ParseRouteTemplate(template, result.Defaults, result.Constraints, new DefaultInlineConstraintResolver()); return result; } struct ParseResult { public string RouteUrl; #if ASPNETWEBAPI public HttpRouteValueDictionary Defaults; public HttpRouteValueDictionary Constraints; #else public RouteValueDictionary Defaults; public RouteValueDictionary Constraints; #endif } } }
// suppress "Missing XML comment for publicly visible type or member" #pragma warning disable 1591 #region ReSharper warnings // ReSharper disable PartialTypeWithSinglePart // ReSharper disable RedundantNameQualifier // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable UnusedParameter.Local // ReSharper disable RedundantUsingDirective #endregion namespace Test { using System.Collections.Generic; [System.CodeDom.Compiler.GeneratedCode("gbc", "0.12.1.0")] public enum TestEnum { EnumVal1, EnumVal2, EnumVal3, } [global::Bond.Schema] [System.CodeDom.Compiler.GeneratedCode("gbc", "0.12.1.0")] public partial class Simple { [global::Bond.Id(0)] public int someInt; [global::Bond.Id(1)] public int anotherInt; [global::Bond.Id(2), global::Bond.Type(typeof(global::Bond.Tag.wstring))] public string someString = ""; public Simple( int someInt, int anotherInt, string someString) { this.someInt = someInt; this.anotherInt = anotherInt; this.someString = someString; } public Simple() { } } [global::Bond.Schema] [System.CodeDom.Compiler.GeneratedCode("gbc", "0.12.1.0")] public partial class Foo { [global::Bond.Id(0), global::Bond.Type(typeof(global::Bond.Tag.wstring))] public string someText = "BaseText1"; public Foo( string someText) { this.someText = someText; } public Foo() { } } [global::Bond.Schema] [System.CodeDom.Compiler.GeneratedCode("gbc", "0.12.1.0")] public partial class Bar : Foo { [global::Bond.Id(0)] public TestEnum testEnum = TestEnum.Val2; [global::Bond.Id(1), global::Bond.Type(typeof(global::Bond.Tag.wstring))] new public string someText = "DerivedText1"; [global::Bond.Id(2)] public int someInt; [global::Bond.Id(3), global::Bond.Type(typeof(global::Bond.Tag.wstring))] public string moreText = ""; [global::Bond.Id(4)] public List<Simple> someList = new List<Simple>(); [global::Bond.Id(5), global::Bond.Type(typeof(Dictionary<global::Bond.Tag.wstring, double>))] public Dictionary<string, double> someMap = new Dictionary<string, double>(); [global::Bond.Id(6), global::Bond.Type(typeof(HashSet<global::Bond.Tag.wstring>))] public HashSet<string> someSet = new HashSet<string>(); public Bar( // Base class parameters string someText, // This class parameters TestEnum testEnum, string someText0, int someInt, string moreText, List<Simple> someList, Dictionary<string, double> someMap, HashSet<string> someSet ) : base( someText) { this.testEnum = testEnum; this.someText = someText0; this.someInt = someInt; this.moreText = moreText; this.someList = someList; this.someMap = someMap; this.someSet = someSet; } public Bar() { } } [global::Bond.Schema] [System.CodeDom.Compiler.GeneratedCode("gbc", "0.12.1.0")] public partial class Baz : Bar { [global::Bond.Id(0), global::Bond.Type(typeof(global::Bond.Tag.wstring))] new public string someText = ""; [global::Bond.Id(1), global::Bond.Type(typeof(global::Bond.Tag.wstring))] public string evenMoreText = ""; [global::Bond.Id(2), global::Bond.Type(typeof(global::Bond.Tag.wstring))] public string someText1 = ""; public Baz( // Base class parameters string someText, TestEnum testEnum, string someText0, int someInt, string moreText, List<Simple> someList, Dictionary<string, double> someMap, HashSet<string> someSet, // This class parameters string someText1, string evenMoreText, string someText10 ) : base( someText, testEnum, someText0, someInt, moreText, someList, someMap, someSet) { this.someText = someText1; this.evenMoreText = evenMoreText; this.someText1 = someText10; } public Baz() { } } [global::Bond.Schema] [System.CodeDom.Compiler.GeneratedCode("gbc", "0.12.1.0")] public partial class DerivedEmpty : Foo { public DerivedEmpty( // Base class parameters string someText ) : base( someText) { } public DerivedEmpty() { } } } // Test
using System; using System.Collections.Generic; using System.ComponentModel; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Publishing; namespace Umbraco.Core.Services { /// <summary> /// Defines the ContentService, which is an easy access to operations involving <see cref="IContent"/> /// </summary> public interface IContentService : IService { /// <summary> /// Rebuilds all xml content in the cmsContentXml table for all documents /// </summary> /// <param name="contentTypeIds"> /// Only rebuild the xml structures for the content type ids passed in, if none then rebuilds the structures /// for all content /// </param> void RebuildXmlStructures(params int[] contentTypeIds); int CountPublished(string contentTypeAlias = null); int Count(string contentTypeAlias = null); int CountChildren(int parentId, string contentTypeAlias = null); int CountDescendants(int parentId, string contentTypeAlias = null); /// <summary> /// Used to bulk update the permissions set for a content item. This will replace all permissions /// assigned to an entity with a list of user id & permission pairs. /// </summary> /// <param name="permissionSet"></param> void ReplaceContentPermissions(EntityPermissionSet permissionSet); /// <summary> /// Assigns a single permission to the current content item for the specified user ids /// </summary> /// <param name="entity"></param> /// <param name="permission"></param> /// <param name="userIds"></param> void AssignContentPermission(IContent entity, char permission, IEnumerable<int> userIds); /// <summary> /// Gets the list of permissions for the content item /// </summary> /// <param name="content"></param> /// <returns></returns> IEnumerable<EntityPermission> GetPermissionsForEntity(IContent content); bool SendToPublication(IContent content, int userId = 0); IEnumerable<IContent> GetByIds(IEnumerable<int> ids); /// <summary> /// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IContent without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new content objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parentId">Id of Parent for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContent(string name, int parentId, string contentTypeAlias, int userId = 0); /// <summary> /// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IContent without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new content objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parent">Parent <see cref="IContent"/> object for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContent(string name, IContent parent, string contentTypeAlias, int userId = 0); /// <summary> /// Gets an <see cref="IContent"/> object by Id /// </summary> /// <param name="id">Id of the Content to retrieve</param> /// <returns><see cref="IContent"/></returns> IContent GetById(int id); /// <summary> /// Gets an <see cref="IContent"/> object by its 'UniqueId' /// </summary> /// <param name="key">Guid key of the Content to retrieve</param> /// <returns><see cref="IContent"/></returns> IContent GetById(Guid key); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by the Id of the <see cref="IContentType"/> /// </summary> /// <param name="id">Id of the <see cref="IContentType"/></param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentOfContentType(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Level /// </summary> /// <param name="level">The level to retrieve Content from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetByLevel(int level); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetChildren(int id); [Obsolete("Use the overload with 'long' parameter types instead")] [EditorBrowsable(EditorBrowsableState.Never)] IEnumerable<IContent> GetPagedChildren(int id, int pageIndex, int pageSize, out int totalRecords, string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="filter">Search text filter</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords, string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = ""); [Obsolete("Use the overload with 'long' parameter types instead")] [EditorBrowsable(EditorBrowsableState.Never)] IEnumerable<IContent> GetPagedDescendants(int id, int pageIndex, int pageSize, out int totalRecords, string orderBy = "Path", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Descendants from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="filter">Search text filter</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords, string orderBy = "Path", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets a collection of an <see cref="IContent"/> objects versions by its Id /// </summary> /// <param name="id"></param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetVersions(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which reside at the first level / root /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetRootContent(); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which has an expiration date greater then today /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentForExpiration(); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which has a release date greater then today /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentForRelease(); /// <summary> /// Gets a collection of an <see cref="IContent"/> objects, which resides in the Recycle Bin /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentInRecycleBin(); /// <summary> /// Saves a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to save</param> /// <param name="userId">Optional Id of the User saving the Content</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> Attempt<OperationStatus> SaveWithStatus(IContent content, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves a collection of <see cref="IContent"/> objects. /// </summary> /// <param name="contents">Collection of <see cref="IContent"/> to save</param> /// <param name="userId">Optional Id of the User saving the Content</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> Attempt<OperationStatus> SaveWithStatus(IEnumerable<IContent> contents, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to save</param> /// <param name="userId">Optional Id of the User saving the Content</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use SaveWithStatus instead, that method will provide more detailed information on the outcome")] void Save(IContent content, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves a collection of <see cref="IContent"/> objects. /// </summary> /// <param name="contents">Collection of <see cref="IContent"/> to save</param> /// <param name="userId">Optional Id of the User saving the Content</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use SaveWithStatus instead, that method will provide more detailed information on the outcome")] void Save(IEnumerable<IContent> contents, int userId = 0, bool raiseEvents = true); /// <summary> /// Deletes all content of specified type. All children of deleted content is moved to Recycle Bin. /// </summary> /// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks> /// <param name="contentTypeId">Id of the <see cref="IContentType"/></param> /// <param name="userId">Optional Id of the user issueing the delete operation</param> void DeleteContentOfType(int contentTypeId, int userId = 0); /// <summary> /// Permanently deletes versions from an <see cref="IContent"/> object prior to a specific date. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> object to delete versions from</param> /// <param name="versionDate">Latest version date</param> /// <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersions(int id, DateTime versionDate, int userId = 0); /// <summary> /// Permanently deletes a specific version from an <see cref="IContent"/> object. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> object to delete a version from</param> /// <param name="versionId">Id of the version to delete</param> /// <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param> /// <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersion(int id, Guid versionId, bool deletePriorVersions, int userId = 0); /// <summary> /// Deletes an <see cref="IContent"/> object by moving it to the Recycle Bin /// </summary> /// <remarks>Move an item to the Recycle Bin will result in the item being unpublished</remarks> /// <param name="content">The <see cref="IContent"/> to delete</param> /// <param name="userId">Optional Id of the User deleting the Content</param> void MoveToRecycleBin(IContent content, int userId = 0); /// <summary> /// Moves an <see cref="IContent"/> object to a new location /// </summary> /// <param name="content">The <see cref="IContent"/> to move</param> /// <param name="parentId">Id of the Content's new Parent</param> /// <param name="userId">Optional Id of the User moving the Content</param> void Move(IContent content, int parentId, int userId = 0); /// <summary> /// Empties the Recycle Bin by deleting all <see cref="IContent"/> that resides in the bin /// </summary> void EmptyRecycleBin(); /// <summary> /// Rollback an <see cref="IContent"/> object to a previous version. /// This will create a new version, which is a copy of all the old data. /// </summary> /// <param name="id">Id of the <see cref="IContent"/>being rolled back</param> /// <param name="versionId">Id of the version to rollback to</param> /// <param name="userId">Optional Id of the User issueing the rollback of the Content</param> /// <returns>The newly created <see cref="IContent"/> object</returns> IContent Rollback(int id, Guid versionId, int userId = 0); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by its name or partial name /// </summary> /// <param name="parentId">Id of the Parent to retrieve Children from</param> /// <param name="name">Full or partial name of the children</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetChildrenByName(int parentId, string name); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Descendants from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetDescendants(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="content"><see cref="IContent"/> item to retrieve Descendants from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetDescendants(IContent content); /// <summary> /// Gets a specific version of an <see cref="IContent"/> item. /// </summary> /// <param name="versionId">Id of the version to retrieve</param> /// <returns>An <see cref="IContent"/> item</returns> IContent GetByVersion(Guid versionId); /// <summary> /// Gets the published version of an <see cref="IContent"/> item /// </summary> /// <param name="id">Id of the <see cref="IContent"/> to retrieve version from</param> /// <returns>An <see cref="IContent"/> item</returns> IContent GetPublishedVersion(int id); /// <summary> /// Gets the published version of a <see cref="IContent"/> item. /// </summary> /// <param name="content">The content item.</param> /// <returns>The published version, if any; otherwise, null.</returns> IContent GetPublishedVersion(IContent content); /// <summary> /// Checks whether an <see cref="IContent"/> item has any children /// </summary> /// <param name="id">Id of the <see cref="IContent"/></param> /// <returns>True if the content has any children otherwise False</returns> bool HasChildren(int id); /// <summary> /// Checks whether an <see cref="IContent"/> item has any published versions /// </summary> /// <param name="id">Id of the <see cref="IContent"/></param> /// <returns>True if the content has any published version otherwise False</returns> bool HasPublishedVersion(int id); /// <summary> /// Re-Publishes all Content /// </summary> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if publishing succeeded, otherwise False</returns> bool RePublishAll(int userId = 0); /// <summary> /// Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if publishing succeeded, otherwise False</returns> bool Publish(IContent content, int userId = 0); /// <summary> /// Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>The published status attempt</returns> Attempt<PublishStatus> PublishWithStatus(IContent content, int userId = 0); /// <summary> /// Publishes a <see cref="IContent"/> object and all its children /// </summary> /// <param name="content">The <see cref="IContent"/> to publish along with its children</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if publishing succeeded, otherwise False</returns> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use PublishWithChildrenWithStatus instead, that method will provide more detailed information on the outcome and also allows the includeUnpublished flag")] bool PublishWithChildren(IContent content, int userId = 0); /// <summary> /// Publishes a <see cref="IContent"/> object and all its children /// </summary> /// <param name="content">The <see cref="IContent"/> to publish along with its children</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <param name="includeUnpublished"></param> /// <returns>The list of statuses for all published items</returns> IEnumerable<Attempt<PublishStatus>> PublishWithChildrenWithStatus(IContent content, int userId = 0, bool includeUnpublished = false); /// <summary> /// UnPublishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if unpublishing succeeded, otherwise False</returns> bool UnPublish(IContent content, int userId = 0); /// <summary> /// Saves and Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to save and publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param> /// <returns>True if publishing succeeded, otherwise False</returns> [Obsolete("Use SaveAndPublishWithStatus instead, that method will provide more detailed information on the outcome")] [EditorBrowsable(EditorBrowsableState.Never)] bool SaveAndPublish(IContent content, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves and Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to save and publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param> /// <returns>True if publishing succeeded, otherwise False</returns> Attempt<PublishStatus> SaveAndPublishWithStatus(IContent content, int userId = 0, bool raiseEvents = true); /// <summary> /// Permanently deletes an <see cref="IContent"/> object. /// </summary> /// <remarks> /// This method will also delete associated media files, child content and possibly associated domains. /// </remarks> /// <remarks>Please note that this method will completely remove the Content from the database</remarks> /// <param name="content">The <see cref="IContent"/> to delete</param> /// <param name="userId">Optional Id of the User deleting the Content</param> void Delete(IContent content, int userId = 0); /// <summary> /// Copies an <see cref="IContent"/> object by creating a new Content object of the same type and copies all data from the current /// to the new copy which is returned. /// </summary> /// <param name="content">The <see cref="IContent"/> to copy</param> /// <param name="parentId">Id of the Content's new Parent</param> /// <param name="relateToOriginal">Boolean indicating whether the copy should be related to the original</param> /// <param name="userId">Optional Id of the User copying the Content</param> /// <returns>The newly created <see cref="IContent"/> object</returns> IContent Copy(IContent content, int parentId, bool relateToOriginal, int userId = 0); /// <summary> /// Checks if the passed in <see cref="IContent"/> can be published based on the anscestors publish state. /// </summary> /// <param name="content"><see cref="IContent"/> to check if anscestors are published</param> /// <returns>True if the Content can be published, otherwise False</returns> bool IsPublishable(IContent content); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which are ancestors of the current content. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetAncestors(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which are ancestors of the current content. /// </summary> /// <param name="content"><see cref="IContent"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetAncestors(IContent content); /// <summary> /// Sorts a collection of <see cref="IContent"/> objects by updating the SortOrder according /// to the ordering of items in the passed in <see cref="IEnumerable{T}"/>. /// </summary> /// <remarks> /// Using this method will ensure that the Published-state is maintained upon sorting /// so the cache is updated accordingly - as needed. /// </remarks> /// <param name="items"></param> /// <param name="userId"></param> /// <param name="raiseEvents"></param> /// <returns>True if sorting succeeded, otherwise False</returns> bool Sort(IEnumerable<IContent> items, int userId = 0, bool raiseEvents = true); /// <summary> /// Gets the parent of the current content as an <see cref="IContent"/> item. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> to retrieve the parent from</param> /// <returns>Parent <see cref="IContent"/> object</returns> IContent GetParent(int id); /// <summary> /// Gets the parent of the current content as an <see cref="IContent"/> item. /// </summary> /// <param name="content"><see cref="IContent"/> to retrieve the parent from</param> /// <returns>Parent <see cref="IContent"/> object</returns> IContent GetParent(IContent content); /// <summary> /// Creates and saves an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IContent"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parent">Parent <see cref="IContent"/> object for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContentWithIdentity(string name, IContent parent, string contentTypeAlias, int userId = 0); /// <summary> /// Creates and saves an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IContent"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parentId">Id of Parent for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContentWithIdentity(string name, int parentId, string contentTypeAlias, int userId = 0); } }
namespace FogBugzCaseTracker { partial class FilterDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FilterDialog)); this.btnOk = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.SearchResultBox = new System.Windows.Forms.GroupBox(); this.chkIncludeNoEstimate = new System.Windows.Forms.CheckBox(); this.listTestResults = new System.Windows.Forms.ListBox(); this.lblBaseSearch = new System.Windows.Forms.Label(); this.chkIgnoreBaseSearch = new System.Windows.Forms.CheckBox(); this.txtBaseSearch = new System.Windows.Forms.TextBox(); this.cmboNarrowSearch = new System.Windows.Forms.ComboBox(); this.lnkSearchHelp = new System.Windows.Forms.LinkLabel(); this.btnTest = new System.Windows.Forms.Button(); this.lblNarrowSearch = new System.Windows.Forms.Label(); this.SearchResultBox.SuspendLayout(); this.SuspendLayout(); // // btnOk // this.btnOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOk.Location = new System.Drawing.Point(511, 348); this.btnOk.Name = "btnOk"; this.btnOk.Size = new System.Drawing.Size(75, 23); this.btnOk.TabIndex = 1; this.btnOk.Text = "Ok"; this.btnOk.UseVisualStyleBackColor = true; this.btnOk.Click += new System.EventHandler(this.btnOk_Click); this.btnOk.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDown); // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(592, 348); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 23); this.btnCancel.TabIndex = 2; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDown); // // SearchResultBox // this.SearchResultBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.SearchResultBox.Controls.Add(this.chkIncludeNoEstimate); this.SearchResultBox.Controls.Add(this.listTestResults); this.SearchResultBox.Controls.Add(this.lblBaseSearch); this.SearchResultBox.Controls.Add(this.chkIgnoreBaseSearch); this.SearchResultBox.Controls.Add(this.txtBaseSearch); this.SearchResultBox.Location = new System.Drawing.Point(15, 66); this.SearchResultBox.Name = "SearchResultBox"; this.SearchResultBox.Size = new System.Drawing.Size(652, 276); this.SearchResultBox.TabIndex = 3; this.SearchResultBox.TabStop = false; this.SearchResultBox.Text = "Search Results"; // // chkIncludeNoEstimate // this.chkIncludeNoEstimate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.chkIncludeNoEstimate.AutoSize = true; this.chkIncludeNoEstimate.Location = new System.Drawing.Point(469, 251); this.chkIncludeNoEstimate.Name = "chkIncludeNoEstimate"; this.chkIncludeNoEstimate.Size = new System.Drawing.Size(171, 17); this.chkIncludeNoEstimate.TabIndex = 17; this.chkIncludeNoEstimate.Text = "Include cases without estimate"; this.chkIncludeNoEstimate.UseVisualStyleBackColor = true; this.chkIncludeNoEstimate.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDown); // // listTestResults // this.listTestResults.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listTestResults.DisplayMember = "LongDescription"; this.listTestResults.FormattingEnabled = true; this.listTestResults.Location = new System.Drawing.Point(20, 28); this.listTestResults.Name = "listTestResults"; this.listTestResults.Size = new System.Drawing.Size(614, 186); this.listTestResults.TabIndex = 2; // // lblBaseSearch // this.lblBaseSearch.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.lblBaseSearch.AutoSize = true; this.lblBaseSearch.Location = new System.Drawing.Point(17, 229); this.lblBaseSearch.Name = "lblBaseSearch"; this.lblBaseSearch.Size = new System.Drawing.Size(147, 13); this.lblBaseSearch.TabIndex = 11; this.lblBaseSearch.Text = "Base Search (recommended):"; // // chkIgnoreBaseSearch // this.chkIgnoreBaseSearch.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.chkIgnoreBaseSearch.AutoSize = true; this.chkIgnoreBaseSearch.Location = new System.Drawing.Point(469, 228); this.chkIgnoreBaseSearch.Name = "chkIgnoreBaseSearch"; this.chkIgnoreBaseSearch.Size = new System.Drawing.Size(117, 17); this.chkIgnoreBaseSearch.TabIndex = 15; this.chkIgnoreBaseSearch.Text = "Ignore base search"; this.chkIgnoreBaseSearch.UseVisualStyleBackColor = true; this.chkIgnoreBaseSearch.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDown); // // txtBaseSearch // this.txtBaseSearch.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtBaseSearch.Location = new System.Drawing.Point(170, 226); this.txtBaseSearch.Name = "txtBaseSearch"; this.txtBaseSearch.ReadOnly = true; this.txtBaseSearch.Size = new System.Drawing.Size(293, 20); this.txtBaseSearch.TabIndex = 12; this.txtBaseSearch.TabStop = false; this.txtBaseSearch.Text = "AssignedTo:\"Me\""; // // cmboNarrowSearch // this.cmboNarrowSearch.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.cmboNarrowSearch.FormattingEnabled = true; this.cmboNarrowSearch.Location = new System.Drawing.Point(62, 12); this.cmboNarrowSearch.Name = "cmboNarrowSearch"; this.cmboNarrowSearch.Size = new System.Drawing.Size(524, 21); this.cmboNarrowSearch.TabIndex = 16; this.cmboNarrowSearch.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtSearch_KeyPress); this.cmboNarrowSearch.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDown); // // lnkSearchHelp // this.lnkSearchHelp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.lnkSearchHelp.AutoSize = true; this.lnkSearchHelp.Location = new System.Drawing.Point(428, 36); this.lnkSearchHelp.Name = "lnkSearchHelp"; this.lnkSearchHelp.Size = new System.Drawing.Size(158, 13); this.lnkSearchHelp.TabIndex = 14; this.lnkSearchHelp.TabStop = true; this.lnkSearchHelp.Text = "what\'s the search syntax again?"; this.lnkSearchHelp.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkSearchHelp_LinkClicked); // // btnTest // this.btnTest.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnTest.Location = new System.Drawing.Point(592, 10); this.btnTest.Name = "btnTest"; this.btnTest.Size = new System.Drawing.Size(75, 23); this.btnTest.TabIndex = 10; this.btnTest.Text = "Go"; this.btnTest.UseVisualStyleBackColor = true; this.btnTest.Click += new System.EventHandler(this.btnTest_Click); this.btnTest.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDown); // // lblNarrowSearch // this.lblNarrowSearch.AutoSize = true; this.lblNarrowSearch.Location = new System.Drawing.Point(12, 15); this.lblNarrowSearch.Name = "lblNarrowSearch"; this.lblNarrowSearch.Size = new System.Drawing.Size(44, 13); this.lblNarrowSearch.TabIndex = 13; this.lblNarrowSearch.Text = "Search:"; // // FilterDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(679, 381); this.Controls.Add(this.cmboNarrowSearch); this.Controls.Add(this.lnkSearchHelp); this.Controls.Add(this.lblNarrowSearch); this.Controls.Add(this.btnTest); this.Controls.Add(this.SearchResultBox); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOk); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(687, 408); this.Name = "FilterDialog"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Search Filter"; this.Load += new System.EventHandler(this.SearchForm_Load); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDown); this.SearchResultBox.ResumeLayout(false); this.SearchResultBox.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnOk; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.GroupBox SearchResultBox; private System.Windows.Forms.ListBox listTestResults; private System.Windows.Forms.CheckBox chkIncludeNoEstimate; private System.Windows.Forms.ComboBox cmboNarrowSearch; private System.Windows.Forms.CheckBox chkIgnoreBaseSearch; private System.Windows.Forms.LinkLabel lnkSearchHelp; private System.Windows.Forms.Button btnTest; private System.Windows.Forms.TextBox txtBaseSearch; private System.Windows.Forms.Label lblBaseSearch; private System.Windows.Forms.Label lblNarrowSearch; } }
using System; using System.Linq; using System.Collections.Generic; using Blueprint41; using Blueprint41.Core; using Blueprint41.Query; using Blueprint41.DatastoreTemplates; using q = Domain.Data.Query; namespace Domain.Data.Manipulation { public interface IProductInventoryOriginalData : ISchemaBaseOriginalData { string Shelf { get; } string Bin { get; } int Quantity { get; } string rowguid { get; } Location Location { get; } Product Product { get; } } public partial class ProductInventory : OGM<ProductInventory, ProductInventory.ProductInventoryData, System.String>, ISchemaBase, INeo4jBase, IProductInventoryOriginalData { #region Initialize static ProductInventory() { Register.Types(); } protected override void RegisterGeneratedStoredQueries() { #region LoadByKeys RegisterQuery(nameof(LoadByKeys), (query, alias) => query. Where(alias.Uid.In(Parameter.New<System.String>(Param0)))); #endregion AdditionalGeneratedStoredQueries(); } partial void AdditionalGeneratedStoredQueries(); public static Dictionary<System.String, ProductInventory> LoadByKeys(IEnumerable<System.String> uids) { return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item); } protected static void RegisterQuery(string name, Func<IMatchQuery, q.ProductInventoryAlias, IWhereQuery> query) { q.ProductInventoryAlias alias; IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.ProductInventory.Alias(out alias)); IWhereQuery partial = query.Invoke(matchQuery, alias); ICompiled compiled = partial.Return(alias).Compile(); RegisterQuery(name, compiled); } public override string ToString() { return $"ProductInventory => Shelf : {this.Shelf}, Bin : {this.Bin}, Quantity : {this.Quantity}, rowguid : {this.rowguid}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}"; } public override int GetHashCode() { return base.GetHashCode(); } protected override void LazySet() { base.LazySet(); if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged) { if ((object)InnerData == (object)OriginalData) OriginalData = new ProductInventoryData(InnerData); } } #endregion #region Validations protected override void ValidateSave() { bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged); #pragma warning disable CS0472 if (InnerData.Shelf == null) throw new PersistenceException(string.Format("Cannot save ProductInventory with key '{0}' because the Shelf cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.Bin == null) throw new PersistenceException(string.Format("Cannot save ProductInventory with key '{0}' because the Bin cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.Quantity == null) throw new PersistenceException(string.Format("Cannot save ProductInventory with key '{0}' because the Quantity cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.rowguid == null) throw new PersistenceException(string.Format("Cannot save ProductInventory with key '{0}' because the rowguid cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.ModifiedDate == null) throw new PersistenceException(string.Format("Cannot save ProductInventory with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>")); #pragma warning restore CS0472 } protected override void ValidateDelete() { } #endregion #region Inner Data public class ProductInventoryData : Data<System.String> { public ProductInventoryData() { } public ProductInventoryData(ProductInventoryData data) { Shelf = data.Shelf; Bin = data.Bin; Quantity = data.Quantity; rowguid = data.rowguid; Location = data.Location; Product = data.Product; ModifiedDate = data.ModifiedDate; Uid = data.Uid; } #region Initialize Collections protected override void InitializeCollections() { NodeType = "ProductInventory"; Location = new EntityCollection<Location>(Wrapper, Members.Location); Product = new EntityCollection<Product>(Wrapper, Members.Product); } public string NodeType { get; private set; } sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); } sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); } #endregion #region Map Data sealed public override IDictionary<string, object> MapTo() { IDictionary<string, object> dictionary = new Dictionary<string, object>(); dictionary.Add("Shelf", Shelf); dictionary.Add("Bin", Bin); dictionary.Add("Quantity", Conversion<int, long>.Convert(Quantity)); dictionary.Add("rowguid", rowguid); dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate)); dictionary.Add("Uid", Uid); return dictionary; } sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties) { object value; if (properties.TryGetValue("Shelf", out value)) Shelf = (string)value; if (properties.TryGetValue("Bin", out value)) Bin = (string)value; if (properties.TryGetValue("Quantity", out value)) Quantity = Conversion<long, int>.Convert((long)value); if (properties.TryGetValue("rowguid", out value)) rowguid = (string)value; if (properties.TryGetValue("ModifiedDate", out value)) ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("Uid", out value)) Uid = (string)value; } #endregion #region Members for interface IProductInventory public string Shelf { get; set; } public string Bin { get; set; } public int Quantity { get; set; } public string rowguid { get; set; } public EntityCollection<Location> Location { get; private set; } public EntityCollection<Product> Product { get; private set; } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get; set; } #endregion #region Members for interface INeo4jBase public string Uid { get; set; } #endregion } #endregion #region Outer Data #region Members for interface IProductInventory public string Shelf { get { LazyGet(); return InnerData.Shelf; } set { if (LazySet(Members.Shelf, InnerData.Shelf, value)) InnerData.Shelf = value; } } public string Bin { get { LazyGet(); return InnerData.Bin; } set { if (LazySet(Members.Bin, InnerData.Bin, value)) InnerData.Bin = value; } } public int Quantity { get { LazyGet(); return InnerData.Quantity; } set { if (LazySet(Members.Quantity, InnerData.Quantity, value)) InnerData.Quantity = value; } } public string rowguid { get { LazyGet(); return InnerData.rowguid; } set { if (LazySet(Members.rowguid, InnerData.rowguid, value)) InnerData.rowguid = value; } } public Location Location { get { return ((ILookupHelper<Location>)InnerData.Location).GetItem(null); } set { if (LazySet(Members.Location, ((ILookupHelper<Location>)InnerData.Location).GetItem(null), value)) ((ILookupHelper<Location>)InnerData.Location).SetItem(value, null); } } public Product Product { get { return ((ILookupHelper<Product>)InnerData.Product).GetItem(null); } set { if (LazySet(Members.Product, ((ILookupHelper<Product>)InnerData.Product).GetItem(null), value)) ((ILookupHelper<Product>)InnerData.Product).SetItem(value, null); } } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } } #endregion #region Members for interface INeo4jBase public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } } #endregion #region Virtual Node Type public string NodeType { get { return InnerData.NodeType; } } #endregion #endregion #region Reflection private static ProductInventoryMembers members = null; public static ProductInventoryMembers Members { get { if (members == null) { lock (typeof(ProductInventory)) { if (members == null) members = new ProductInventoryMembers(); } } return members; } } public class ProductInventoryMembers { internal ProductInventoryMembers() { } #region Members for interface IProductInventory public Property Shelf { get; } = Datastore.AdventureWorks.Model.Entities["ProductInventory"].Properties["Shelf"]; public Property Bin { get; } = Datastore.AdventureWorks.Model.Entities["ProductInventory"].Properties["Bin"]; public Property Quantity { get; } = Datastore.AdventureWorks.Model.Entities["ProductInventory"].Properties["Quantity"]; public Property rowguid { get; } = Datastore.AdventureWorks.Model.Entities["ProductInventory"].Properties["rowguid"]; public Property Location { get; } = Datastore.AdventureWorks.Model.Entities["ProductInventory"].Properties["Location"]; public Property Product { get; } = Datastore.AdventureWorks.Model.Entities["ProductInventory"].Properties["Product"]; #endregion #region Members for interface ISchemaBase public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]; #endregion #region Members for interface INeo4jBase public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]; #endregion } private static ProductInventoryFullTextMembers fullTextMembers = null; public static ProductInventoryFullTextMembers FullTextMembers { get { if (fullTextMembers == null) { lock (typeof(ProductInventory)) { if (fullTextMembers == null) fullTextMembers = new ProductInventoryFullTextMembers(); } } return fullTextMembers; } } public class ProductInventoryFullTextMembers { internal ProductInventoryFullTextMembers() { } } sealed public override Entity GetEntity() { if (entity == null) { lock (typeof(ProductInventory)) { if (entity == null) entity = Datastore.AdventureWorks.Model.Entities["ProductInventory"]; } } return entity; } private static ProductInventoryEvents events = null; public static ProductInventoryEvents Events { get { if (events == null) { lock (typeof(ProductInventory)) { if (events == null) events = new ProductInventoryEvents(); } } return events; } } public class ProductInventoryEvents { #region OnNew private bool onNewIsRegistered = false; private EventHandler<ProductInventory, EntityEventArgs> onNew; public event EventHandler<ProductInventory, EntityEventArgs> OnNew { add { lock (this) { if (!onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; Entity.Events.OnNew += onNewProxy; onNewIsRegistered = true; } onNew += value; } } remove { lock (this) { onNew -= value; if (onNew == null && onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; onNewIsRegistered = false; } } } } private void onNewProxy(object sender, EntityEventArgs args) { EventHandler<ProductInventory, EntityEventArgs> handler = onNew; if ((object)handler != null) handler.Invoke((ProductInventory)sender, args); } #endregion #region OnDelete private bool onDeleteIsRegistered = false; private EventHandler<ProductInventory, EntityEventArgs> onDelete; public event EventHandler<ProductInventory, EntityEventArgs> OnDelete { add { lock (this) { if (!onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; Entity.Events.OnDelete += onDeleteProxy; onDeleteIsRegistered = true; } onDelete += value; } } remove { lock (this) { onDelete -= value; if (onDelete == null && onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; onDeleteIsRegistered = false; } } } } private void onDeleteProxy(object sender, EntityEventArgs args) { EventHandler<ProductInventory, EntityEventArgs> handler = onDelete; if ((object)handler != null) handler.Invoke((ProductInventory)sender, args); } #endregion #region OnSave private bool onSaveIsRegistered = false; private EventHandler<ProductInventory, EntityEventArgs> onSave; public event EventHandler<ProductInventory, EntityEventArgs> OnSave { add { lock (this) { if (!onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; Entity.Events.OnSave += onSaveProxy; onSaveIsRegistered = true; } onSave += value; } } remove { lock (this) { onSave -= value; if (onSave == null && onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; onSaveIsRegistered = false; } } } } private void onSaveProxy(object sender, EntityEventArgs args) { EventHandler<ProductInventory, EntityEventArgs> handler = onSave; if ((object)handler != null) handler.Invoke((ProductInventory)sender, args); } #endregion #region OnPropertyChange public static class OnPropertyChange { #region OnShelf private static bool onShelfIsRegistered = false; private static EventHandler<ProductInventory, PropertyEventArgs> onShelf; public static event EventHandler<ProductInventory, PropertyEventArgs> OnShelf { add { lock (typeof(OnPropertyChange)) { if (!onShelfIsRegistered) { Members.Shelf.Events.OnChange -= onShelfProxy; Members.Shelf.Events.OnChange += onShelfProxy; onShelfIsRegistered = true; } onShelf += value; } } remove { lock (typeof(OnPropertyChange)) { onShelf -= value; if (onShelf == null && onShelfIsRegistered) { Members.Shelf.Events.OnChange -= onShelfProxy; onShelfIsRegistered = false; } } } } private static void onShelfProxy(object sender, PropertyEventArgs args) { EventHandler<ProductInventory, PropertyEventArgs> handler = onShelf; if ((object)handler != null) handler.Invoke((ProductInventory)sender, args); } #endregion #region OnBin private static bool onBinIsRegistered = false; private static EventHandler<ProductInventory, PropertyEventArgs> onBin; public static event EventHandler<ProductInventory, PropertyEventArgs> OnBin { add { lock (typeof(OnPropertyChange)) { if (!onBinIsRegistered) { Members.Bin.Events.OnChange -= onBinProxy; Members.Bin.Events.OnChange += onBinProxy; onBinIsRegistered = true; } onBin += value; } } remove { lock (typeof(OnPropertyChange)) { onBin -= value; if (onBin == null && onBinIsRegistered) { Members.Bin.Events.OnChange -= onBinProxy; onBinIsRegistered = false; } } } } private static void onBinProxy(object sender, PropertyEventArgs args) { EventHandler<ProductInventory, PropertyEventArgs> handler = onBin; if ((object)handler != null) handler.Invoke((ProductInventory)sender, args); } #endregion #region OnQuantity private static bool onQuantityIsRegistered = false; private static EventHandler<ProductInventory, PropertyEventArgs> onQuantity; public static event EventHandler<ProductInventory, PropertyEventArgs> OnQuantity { add { lock (typeof(OnPropertyChange)) { if (!onQuantityIsRegistered) { Members.Quantity.Events.OnChange -= onQuantityProxy; Members.Quantity.Events.OnChange += onQuantityProxy; onQuantityIsRegistered = true; } onQuantity += value; } } remove { lock (typeof(OnPropertyChange)) { onQuantity -= value; if (onQuantity == null && onQuantityIsRegistered) { Members.Quantity.Events.OnChange -= onQuantityProxy; onQuantityIsRegistered = false; } } } } private static void onQuantityProxy(object sender, PropertyEventArgs args) { EventHandler<ProductInventory, PropertyEventArgs> handler = onQuantity; if ((object)handler != null) handler.Invoke((ProductInventory)sender, args); } #endregion #region Onrowguid private static bool onrowguidIsRegistered = false; private static EventHandler<ProductInventory, PropertyEventArgs> onrowguid; public static event EventHandler<ProductInventory, PropertyEventArgs> Onrowguid { add { lock (typeof(OnPropertyChange)) { if (!onrowguidIsRegistered) { Members.rowguid.Events.OnChange -= onrowguidProxy; Members.rowguid.Events.OnChange += onrowguidProxy; onrowguidIsRegistered = true; } onrowguid += value; } } remove { lock (typeof(OnPropertyChange)) { onrowguid -= value; if (onrowguid == null && onrowguidIsRegistered) { Members.rowguid.Events.OnChange -= onrowguidProxy; onrowguidIsRegistered = false; } } } } private static void onrowguidProxy(object sender, PropertyEventArgs args) { EventHandler<ProductInventory, PropertyEventArgs> handler = onrowguid; if ((object)handler != null) handler.Invoke((ProductInventory)sender, args); } #endregion #region OnLocation private static bool onLocationIsRegistered = false; private static EventHandler<ProductInventory, PropertyEventArgs> onLocation; public static event EventHandler<ProductInventory, PropertyEventArgs> OnLocation { add { lock (typeof(OnPropertyChange)) { if (!onLocationIsRegistered) { Members.Location.Events.OnChange -= onLocationProxy; Members.Location.Events.OnChange += onLocationProxy; onLocationIsRegistered = true; } onLocation += value; } } remove { lock (typeof(OnPropertyChange)) { onLocation -= value; if (onLocation == null && onLocationIsRegistered) { Members.Location.Events.OnChange -= onLocationProxy; onLocationIsRegistered = false; } } } } private static void onLocationProxy(object sender, PropertyEventArgs args) { EventHandler<ProductInventory, PropertyEventArgs> handler = onLocation; if ((object)handler != null) handler.Invoke((ProductInventory)sender, args); } #endregion #region OnProduct private static bool onProductIsRegistered = false; private static EventHandler<ProductInventory, PropertyEventArgs> onProduct; public static event EventHandler<ProductInventory, PropertyEventArgs> OnProduct { add { lock (typeof(OnPropertyChange)) { if (!onProductIsRegistered) { Members.Product.Events.OnChange -= onProductProxy; Members.Product.Events.OnChange += onProductProxy; onProductIsRegistered = true; } onProduct += value; } } remove { lock (typeof(OnPropertyChange)) { onProduct -= value; if (onProduct == null && onProductIsRegistered) { Members.Product.Events.OnChange -= onProductProxy; onProductIsRegistered = false; } } } } private static void onProductProxy(object sender, PropertyEventArgs args) { EventHandler<ProductInventory, PropertyEventArgs> handler = onProduct; if ((object)handler != null) handler.Invoke((ProductInventory)sender, args); } #endregion #region OnModifiedDate private static bool onModifiedDateIsRegistered = false; private static EventHandler<ProductInventory, PropertyEventArgs> onModifiedDate; public static event EventHandler<ProductInventory, PropertyEventArgs> OnModifiedDate { add { lock (typeof(OnPropertyChange)) { if (!onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; Members.ModifiedDate.Events.OnChange += onModifiedDateProxy; onModifiedDateIsRegistered = true; } onModifiedDate += value; } } remove { lock (typeof(OnPropertyChange)) { onModifiedDate -= value; if (onModifiedDate == null && onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; onModifiedDateIsRegistered = false; } } } } private static void onModifiedDateProxy(object sender, PropertyEventArgs args) { EventHandler<ProductInventory, PropertyEventArgs> handler = onModifiedDate; if ((object)handler != null) handler.Invoke((ProductInventory)sender, args); } #endregion #region OnUid private static bool onUidIsRegistered = false; private static EventHandler<ProductInventory, PropertyEventArgs> onUid; public static event EventHandler<ProductInventory, PropertyEventArgs> OnUid { add { lock (typeof(OnPropertyChange)) { if (!onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; Members.Uid.Events.OnChange += onUidProxy; onUidIsRegistered = true; } onUid += value; } } remove { lock (typeof(OnPropertyChange)) { onUid -= value; if (onUid == null && onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; onUidIsRegistered = false; } } } } private static void onUidProxy(object sender, PropertyEventArgs args) { EventHandler<ProductInventory, PropertyEventArgs> handler = onUid; if ((object)handler != null) handler.Invoke((ProductInventory)sender, args); } #endregion } #endregion } #endregion #region IProductInventoryOriginalData public IProductInventoryOriginalData OriginalVersion { get { return this; } } #region Members for interface IProductInventory string IProductInventoryOriginalData.Shelf { get { return OriginalData.Shelf; } } string IProductInventoryOriginalData.Bin { get { return OriginalData.Bin; } } int IProductInventoryOriginalData.Quantity { get { return OriginalData.Quantity; } } string IProductInventoryOriginalData.rowguid { get { return OriginalData.rowguid; } } Location IProductInventoryOriginalData.Location { get { return ((ILookupHelper<Location>)OriginalData.Location).GetOriginalItem(null); } } Product IProductInventoryOriginalData.Product { get { return ((ILookupHelper<Product>)OriginalData.Product).GetOriginalItem(null); } } #endregion #region Members for interface ISchemaBase ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } } System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } } #endregion #region Members for interface INeo4jBase INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } } string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } } #endregion #endregion } }
/*************************************************************************** * Body.cs * ------------------- * begin : May 1, 2002 * copyright : (C) The RunUO Software Team * email : info@runuo.com * * $Id: Body.cs 844 2012-03-07 13:47:33Z mark $ * ***************************************************************************/ /*************************************************************************** * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * ***************************************************************************/ using System; using System.IO; namespace Server { public enum BodyType : byte { Empty, Monster, Sea, Animal, Human, Equipment } public struct Body { private int m_BodyID; private static BodyType[] m_Types; static Body() { if ( File.Exists( "Data/bodyTable.cfg" ) ) { using ( StreamReader ip = new StreamReader( "Data/bodyTable.cfg" ) ) { m_Types = new BodyType[0x1000]; string line; while ( (line = ip.ReadLine()) != null ) { if ( line.Length == 0 || line.StartsWith( "#" ) ) continue; string[] split = line.Split( '\t' ); #if Framework_4_0 BodyType type; int bodyID; if( int.TryParse( split[0], out bodyID ) && Enum.TryParse( split[1], true, out type ) && bodyID >= 0 && bodyID < m_Types.Length ) { m_Types[bodyID] = type; } else { Console.WriteLine( "Warning: Invalid bodyTable entry:" ); Console.WriteLine( line ); } #else try { int bodyID = int.Parse( split[0] ); BodyType type = (BodyType)Enum.Parse( typeof( BodyType ), split[1], true ); if ( bodyID >= 0 && bodyID < m_Types.Length ) m_Types[bodyID] = type; } catch { Console.WriteLine( "Warning: Invalid bodyTable entry:" ); Console.WriteLine( line ); } #endif } } } else { Console.WriteLine( "Warning: Data/bodyTable.cfg does not exist" ); m_Types = new BodyType[0]; } } public Body( int bodyID ) { m_BodyID = bodyID; } public BodyType Type { get { if ( m_BodyID >= 0 && m_BodyID < m_Types.Length ) return m_Types[m_BodyID]; else return BodyType.Empty; } } public bool IsHuman { get { return m_BodyID >= 0 && m_BodyID < m_Types.Length && m_Types[m_BodyID] == BodyType.Human && m_BodyID != 402 && m_BodyID != 403 && m_BodyID != 607 && m_BodyID != 608 && m_BodyID != 970; } } public bool IsMale { get { return m_BodyID == 183 || m_BodyID == 185 || m_BodyID == 400 || m_BodyID == 402 || m_BodyID == 605 || m_BodyID == 607 || m_BodyID == 750; } } public bool IsFemale { get { return m_BodyID == 184 || m_BodyID == 186 || m_BodyID == 401 || m_BodyID == 403 || m_BodyID == 606 || m_BodyID == 608 || m_BodyID == 751; } } public bool IsGhost { get { return m_BodyID == 402 || m_BodyID == 403 || m_BodyID == 607 || m_BodyID == 608 || m_BodyID == 970; } } public bool IsMonster { get { return m_BodyID >= 0 && m_BodyID < m_Types.Length && m_Types[m_BodyID] == BodyType.Monster; } } public bool IsAnimal { get { return m_BodyID >= 0 && m_BodyID < m_Types.Length && m_Types[m_BodyID] == BodyType.Animal; } } public bool IsEmpty { get { return m_BodyID >= 0 && m_BodyID < m_Types.Length && m_Types[m_BodyID] == BodyType.Empty; } } public bool IsSea { get { return m_BodyID >= 0 && m_BodyID < m_Types.Length && m_Types[m_BodyID] == BodyType.Sea; } } public bool IsEquipment { get { return m_BodyID >= 0 && m_BodyID < m_Types.Length && m_Types[m_BodyID] == BodyType.Equipment; } } public int BodyID { get { return m_BodyID; } } public static implicit operator int( Body a ) { return a.m_BodyID; } public static implicit operator Body( int a ) { return new Body( a ); } public override string ToString() { return string.Format( "0x{0:X}", m_BodyID ); } public override int GetHashCode() { return m_BodyID; } public override bool Equals( object o ) { if ( o == null || !(o is Body) ) return false; return ((Body)o).m_BodyID == m_BodyID; } public static bool operator == ( Body l, Body r ) { return l.m_BodyID == r.m_BodyID; } public static bool operator != ( Body l, Body r ) { return l.m_BodyID != r.m_BodyID; } public static bool operator > ( Body l, Body r ) { return l.m_BodyID > r.m_BodyID; } public static bool operator >= ( Body l, Body r ) { return l.m_BodyID >= r.m_BodyID; } public static bool operator < ( Body l, Body r ) { return l.m_BodyID < r.m_BodyID; } public static bool operator <= ( Body l, Body r ) { return l.m_BodyID <= r.m_BodyID; } } }
using System; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using Argotic.Common; using Argotic.Syndication.Specialized; using HeyRed.MarkdownSharp; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; using Umbraco.Web; using Umbraco.Web.Routing; namespace Articulate.ImportExport { public class BlogMlExporter { private readonly ArticulateTempFileSystem _fileSystem; private readonly IContentService _contentService; private readonly IContentTypeService _contentTypeService; private readonly IDataTypeService _dataTypeService; private readonly ITagService _tagService; private readonly ILogger _logger; private readonly IUmbracoContextAccessor _umbracoContextAccessor; public BlogMlExporter(IUmbracoContextAccessor umbracoContextAccessor, ArticulateTempFileSystem fileSystem, IContentService contentService, IContentTypeService contentTypeService, IDataTypeService dataTypeService, ITagService tagService, ILogger logger) { _umbracoContextAccessor = umbracoContextAccessor; _fileSystem = fileSystem; _contentService = contentService; _contentTypeService = contentTypeService; _dataTypeService = dataTypeService; _tagService = tagService; _logger = logger; } public void Export( string fileName, int blogRootNode) { var root = _contentService.GetById(blogRootNode); if (root == null) { throw new InvalidOperationException("No node found with id " + blogRootNode); } if (!root.ContentType.Alias.InvariantEquals("Articulate")) { throw new InvalidOperationException("The node with id " + blogRootNode + " is not an Articulate root node"); } var postType = _contentTypeService.Get("ArticulateRichText"); if (postType == null) { throw new InvalidOperationException("Articulate is not installed properly, the ArticulateRichText doc type could not be found"); } var archiveContentType = _contentTypeService.Get(ArticulateConstants.ArticulateArchiveContentTypeAlias); var archiveNodes = _contentService.GetPagedOfType(archiveContentType.Id, 0, int.MaxValue, out long totalArchive, null); var authorsContentType = _contentTypeService.Get(ArticulateConstants.ArticulateAuthorsContentTypeAlias); var authorsNodes = _contentService.GetPagedOfType(authorsContentType.Id, 0, int.MaxValue, out long totalAuthors, null); if (totalArchive == 0) { throw new InvalidOperationException("No ArticulateArchive found under the blog root node"); } if (totalAuthors == 0) { throw new InvalidOperationException("No ArticulateAuthors found under the blog root node"); } var categoryDataType = _dataTypeService.GetDataType("Articulate Categories"); if (categoryDataType == null) { throw new InvalidOperationException("No Articulate Categories data type found"); } var categoryConfiguration = categoryDataType.ConfigurationAs<TagConfiguration>(); var categoryGroup = categoryConfiguration.Group; var tagDataType = _dataTypeService.GetDataType("Articulate Tags"); if (tagDataType == null) { throw new InvalidOperationException("No Articulate Tags data type found"); } var tagConfiguration = tagDataType.ConfigurationAs<TagConfiguration>(); var tagGroup = tagConfiguration.Group; //TODO: See: http://argotic.codeplex.com/wikipage?title=Generating%20portable%20web%20log%20content&referringTitle=Home var blogMlDoc = new BlogMLDocument { RootUrl = new Uri(_umbracoContextAccessor.UmbracoContext.UrlProvider.GetUrl(root.Id), UriKind.RelativeOrAbsolute), GeneratedOn = DateTime.Now, Title = new BlogMLTextConstruct(root.GetValue<string>("blogTitle")), Subtitle = new BlogMLTextConstruct(root.GetValue<string>("blogDescription")) }; foreach (var authorsNode in authorsNodes) { AddBlogAuthors(authorsNode, blogMlDoc); } AddBlogCategories(blogMlDoc, categoryGroup); foreach (var archiveNode in archiveNodes) { AddBlogPosts(archiveNode, blogMlDoc, categoryGroup, tagGroup); } WriteFile(blogMlDoc); } private void WriteFile(BlogMLDocument blogMlDoc) { using (var stream = new MemoryStream()) { blogMlDoc.Save(stream, new SyndicationResourceSaveSettings() { CharacterEncoding = Encoding.UTF8 }); stream.Position = 0; _fileSystem.AddFile("BlogMlExport.xml", stream, true); } } private void AddBlogCategories(BlogMLDocument blogMlDoc, string tagGroup) { var categories = _tagService.GetAllContentTags(tagGroup); foreach (var category in categories) { if (category.NodeCount == 0) continue; var blogMlCategory = new BlogMLCategory(); blogMlCategory.Id = category.Id.ToString(); blogMlCategory.CreatedOn = category.CreateDate; blogMlCategory.LastModifiedOn = category.UpdateDate; blogMlCategory.ApprovalStatus = BlogMLApprovalStatus.Approved; blogMlCategory.ParentId = "0"; blogMlCategory.Title = new BlogMLTextConstruct(category.Text); blogMlDoc.Categories.Add(blogMlCategory); } } private void AddBlogAuthors(IContent authorsNode, BlogMLDocument blogMlDoc) { foreach (var author in _contentService.GetPagedChildren(authorsNode.Id, 0, int.MaxValue, out long totalAuthors)) { var blogMlAuthor = new BlogMLAuthor(); blogMlAuthor.Id = author.Key.ToString(); blogMlAuthor.CreatedOn = author.CreateDate; blogMlAuthor.LastModifiedOn = author.UpdateDate; blogMlAuthor.ApprovalStatus = BlogMLApprovalStatus.Approved; blogMlAuthor.Title = new BlogMLTextConstruct(author.Name); blogMlDoc.Authors.Add(blogMlAuthor); } } private void AddBlogPosts(IContent archiveNode, BlogMLDocument blogMlDoc, string categoryGroup, string tagGroup) { // TODO: This won't work for variants var md = new Markdown(); const int pageSize = 1000; var pageIndex = 0; IContent[] posts; do { posts = _contentService.GetPagedChildren(archiveNode.Id, pageIndex, pageSize, out long _ , ordering: Ordering.By("createDate")).ToArray(); foreach (var child in posts) { if (!child.Published) continue; string content = ""; if (child.ContentType.Alias.InvariantEquals("ArticulateRichText")) { //TODO: this would also need to export all macros content = child.GetValue<string>("richText"); } else if (child.ContentType.Alias.InvariantEquals("ArticulateMarkdown")) { content = md.Transform(child.GetValue<string>("markdown")); } var postUrl = new Uri(_umbracoContextAccessor.UmbracoContext.UrlProvider.GetUrl(child.Id), UriKind.RelativeOrAbsolute); var postAbsoluteUrl = new Uri(_umbracoContextAccessor.UmbracoContext.UrlProvider.GetUrl(child.Id, UrlMode.Absolute), UriKind.Absolute); var blogMlPost = new BlogMLPost() { Id = child.Key.ToString(), Name = new BlogMLTextConstruct(child.Name), Title = new BlogMLTextConstruct(child.Name), ApprovalStatus = BlogMLApprovalStatus.Approved, PostType = BlogMLPostType.Normal, CreatedOn = child.CreateDate, LastModifiedOn = child.UpdateDate, Content = new BlogMLTextConstruct(content, BlogMLContentType.Html), Excerpt = new BlogMLTextConstruct(child.GetValue<string>("excerpt")), Url = postUrl }; var author = blogMlDoc.Authors.FirstOrDefault(x => x.Title != null && x.Title.Content.InvariantEquals(child.GetValue<string>("author"))); if (author != null) { blogMlPost.Authors.Add(author.Id); } var categories = _tagService.GetTagsForEntity(child.Id, categoryGroup); foreach (var category in categories) { blogMlPost.Categories.Add(category.Id.ToString()); } var tags = _tagService.GetTagsForEntity(child.Id, tagGroup).Select(t =>t.Text).ToList(); if (tags?.Any() == true) { blogMlPost.AddExtension( new Syndication.BlogML.TagsSyndicationExtension() { Context = {Tags = new Collection<string>(tags)} }); } //add the image attached if there is one if (child.HasProperty("postImage")) { try { var val = child.GetValue<string>("postImage"); var json = JsonConvert.DeserializeObject<JObject>(val); var src = json.Value<string>("src"); var mime = ImageMimeType(src); if (!mime.IsNullOrWhiteSpace()) { var imageUrl = new Uri(postAbsoluteUrl.GetLeftPart(UriPartial.Authority) + src.EnsureStartsWith('/'), UriKind.Absolute); blogMlPost.Attachments.Add(new BlogMLAttachment { Content = string.Empty, //this is used for embedded resources Url = imageUrl, ExternalUri = imageUrl, IsEmbedded = false, MimeType = mime }); } } catch (Exception ex) { _logger.Error<BlogMlExporter>(ex, "Could not add the file to the blogML post attachments"); } } blogMlDoc.AddPost(blogMlPost); } pageIndex++; } while (posts.Length == pageSize); } private string ImageMimeType(string src) { var ext = Path.GetExtension(src)?.ToLowerInvariant(); switch (ext) { case ".jpg": return "image/jpeg"; case ".png": return "image/png"; case ".gif": return "image/gif"; default: return null; } } } }
/* * 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.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Asset { /// <summary> /// Cenome memory asset cache. /// </summary> /// <remarks> /// <para> /// Cache is enabled by setting "AssetCaching" configuration to value "CenomeMemoryAssetCache". /// When cache is successfully enable log should have message /// "[ASSET CACHE]: Cenome asset cache enabled (MaxSize = XXX bytes, MaxCount = XXX, ExpirationTime = XXX)". /// </para> /// <para> /// Cache's size is limited by two parameters: /// maximal allowed size in bytes and maximal allowed asset count. When new asset /// is added to cache that have achieved either size or count limitation, cache /// will automatically remove less recently used assets from cache. Additionally /// asset's lifetime is controlled by expiration time. /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Configuration</term> /// <description>Description</description> /// </listheader> /// <item> /// <term>MaxSize</term> /// <description>Maximal size of the cache in bytes. Default value: 128MB (134 217 728 bytes).</description> /// </item> /// <item> /// <term>MaxCount</term> /// <description>Maximal count of assets stored to cache. Default value: 4096 assets.</description> /// </item> /// <item> /// <term>ExpirationTime</term> /// <description>Asset's expiration time in minutes. Default value: 30 minutes.</description> /// </item> /// </list> /// </para> /// </remarks> /// <example> /// Enabling Cenome Asset Cache: /// <code> /// [Modules] /// AssetCaching = "CenomeMemoryAssetCache" /// </code> /// Setting size and expiration time limitations: /// <code> /// [AssetCache] /// ; 256 MB (default: 134217728) /// MaxSize = 268435456 /// ; How many assets it is possible to store cache (default: 4096) /// MaxCount = 16384 /// ; Expiration time - 1 hour (default: 30 minutes) /// ExpirationTime = 60 /// </code> /// </example> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "CenomeMemoryAssetCache")] public class CenomeMemoryAssetCache : IAssetCache, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Cache's default maximal asset count. /// </summary> /// <remarks> /// <para> /// Assuming that average asset size is about 32768 bytes. /// </para> /// </remarks> public const int DefaultMaxCount = 4096; /// <summary> /// Default maximal size of the cache in bytes /// </summary> /// <remarks> /// <para> /// 128MB = 128 * 1024^2 = 134 217 728 bytes. /// </para> /// </remarks> public const long DefaultMaxSize = 134217728; /// <summary> /// Asset's default expiration time in the cache. /// </summary> public static readonly TimeSpan DefaultExpirationTime = TimeSpan.FromMinutes(30.0); /// <summary> /// Cache object. /// </summary> private ICnmCache<string, AssetBase> m_cache; /// <summary> /// Count of cache commands /// </summary> private int m_cachedCount; /// <summary> /// How many gets before dumping statistics /// </summary> /// <remarks> /// If 0 or less, then disabled. /// </remarks> private int m_debugEpoch; /// <summary> /// Is Cenome asset cache enabled. /// </summary> private bool m_enabled; /// <summary> /// Count of get requests /// </summary> private int m_getCount; /// <summary> /// How many hits /// </summary> private int m_hitCount; /// <summary> /// Initialize asset cache module, with custom parameters. /// </summary> /// <param name="maximalSize"> /// Cache's maximal size in bytes. /// </param> /// <param name="maximalCount"> /// Cache's maximal count of assets. /// </param> /// <param name="expirationTime"> /// Asset's expiration time. /// </param> protected void Initialize(long maximalSize, int maximalCount, TimeSpan expirationTime) { if (maximalSize <= 0 || maximalCount <= 0) { //m_log.Debug("[ASSET CACHE]: Cenome asset cache is not enabled."); m_enabled = false; return; } if (expirationTime <= TimeSpan.Zero) { // Disable expiration time expirationTime = TimeSpan.MaxValue; } // Create cache and add synchronization wrapper over it m_cache = CnmSynchronizedCache<string, AssetBase>.Synchronized(new CnmMemoryCache<string, AssetBase>( maximalSize, maximalCount, expirationTime)); m_enabled = true; m_log.DebugFormat( "[ASSET CACHE]: Cenome asset cache enabled (MaxSize = {0} bytes, MaxCount = {1}, ExpirationTime = {2})", maximalSize, maximalCount, expirationTime); } #region IAssetCache Members public bool Check(string id) { AssetBase asset; // XXX:This is probably not an efficient implementation. return m_cache.TryGetValue(id, out asset); } /// <summary> /// Cache asset. /// </summary> /// <param name="asset"> /// The asset that is being cached. /// </param> public void Cache(AssetBase asset) { if (asset != null) { // m_log.DebugFormat("[CENOME ASSET CACHE]: Caching asset {0}", asset.ID); long size = asset.Data != null ? asset.Data.Length : 1; m_cache.Set(asset.ID, asset, size); m_cachedCount++; } } public void CacheNegative(string id) { // We don't do negative caching } /// <summary> /// Clear asset cache. /// </summary> public void Clear() { m_cache.Clear(); } /// <summary> /// Expire (remove) asset stored to cache. /// </summary> /// <param name="id"> /// The expired asset's id. /// </param> public void Expire(string id) { m_cache.Remove(id); } /// <summary> /// Get asset stored /// </summary> /// <param name="id"> /// The asset's id. /// </param> /// <returns> /// Asset if it is found from cache; otherwise <see langword="null"/>. /// </returns> /// <remarks> /// <para> /// Caller should always check that is return value <see langword="null"/>. /// Cache doesn't guarantee in any situation that asset is stored to it. /// </para> /// </remarks> public bool Get(string id, out AssetBase assetBase) { m_getCount++; if (m_cache.TryGetValue(id, out assetBase)) m_hitCount++; if (m_getCount == m_debugEpoch) { m_log.DebugFormat( "[ASSET CACHE]: Cached = {0}, Get = {1}, Hits = {2}%, Size = {3} bytes, Avg. A. Size = {4} bytes", m_cachedCount, m_getCount, ((double) m_hitCount / m_getCount) * 100.0, m_cache.Size, m_cache.Size / m_cache.Count); m_getCount = 0; m_hitCount = 0; m_cachedCount = 0; } // if (null == assetBase) // m_log.DebugFormat("[CENOME ASSET CACHE]: Asset {0} not in cache", id); return true; } #endregion #region ISharedRegionModule Members /// <summary> /// Gets region module's name. /// </summary> public string Name { get { return "CenomeMemoryAssetCache"; } } public Type ReplaceableInterface { get { return null; } } /// <summary> /// New region is being added to server. /// </summary> /// <param name="scene"> /// Region's scene. /// </param> public void AddRegion(Scene scene) { if (m_enabled) scene.RegisterModuleInterface<IAssetCache>(this); } /// <summary> /// Close region module. /// </summary> public void Close() { if (m_enabled) { m_enabled = false; m_cache.Clear(); m_cache = null; } } /// <summary> /// Initialize region module. /// </summary> /// <param name="source"> /// Configuration source. /// </param> public void Initialise(IConfigSource source) { m_cache = null; m_enabled = false; IConfig moduleConfig = source.Configs[ "Modules" ]; if (moduleConfig == null) return; string name = moduleConfig.GetString("AssetCaching"); //m_log.DebugFormat("[XXX] name = {0} (this module's name: {1}", name, Name); if (name != Name) return; long maxSize = DefaultMaxSize; int maxCount = DefaultMaxCount; TimeSpan expirationTime = DefaultExpirationTime; IConfig assetConfig = source.Configs["AssetCache"]; if (assetConfig != null) { // Get optional configurations maxSize = assetConfig.GetLong("MaxSize", DefaultMaxSize); maxCount = assetConfig.GetInt("MaxCount", DefaultMaxCount); expirationTime = TimeSpan.FromMinutes(assetConfig.GetInt("ExpirationTime", (int)DefaultExpirationTime.TotalMinutes)); // Debugging purposes only m_debugEpoch = assetConfig.GetInt("DebugEpoch", 0); } Initialize(maxSize, maxCount, expirationTime); } /// <summary> /// Initialization post handling. /// </summary> /// <remarks> /// <para> /// Modules can use this to initialize connection with other modules. /// </para> /// </remarks> public void PostInitialise() { } /// <summary> /// Region has been loaded. /// </summary> /// <param name="scene"> /// Region's scene. /// </param> /// <remarks> /// <para> /// This is needed for all module types. Modules will register /// Interfaces with scene in AddScene, and will also need a means /// to access interfaces registered by other modules. Without /// this extra method, a module attempting to use another modules' /// interface would be successful only depending on load order, /// which can't be depended upon, or modules would need to resort /// to ugly kludges to attempt to request interfaces when needed /// and unnecessary caching logic repeated in all modules. /// The extra function stub is just that much cleaner. /// </para> /// </remarks> public void RegionLoaded(Scene scene) { } /// <summary> /// Region is being removed. /// </summary> /// <param name="scene"> /// Region scene that is being removed. /// </param> public void RemoveRegion(Scene scene) { } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Security; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Globalization { public partial class CompareInfo { private unsafe void InitSort(CultureInfo culture) { _sortName = culture.SortName; m_name = culture._name; _sortName = culture.SortName; if (_invariantMode) { _sortHandle = IntPtr.Zero; } else { const uint LCMAP_SORTHANDLE = 0x20000000; IntPtr handle; int ret = Interop.Kernel32.LCMapStringEx(_sortName, LCMAP_SORTHANDLE, null, 0, &handle, IntPtr.Size, null, null, IntPtr.Zero); _sortHandle = ret > 0 ? handle : IntPtr.Zero; } } private static unsafe int FindStringOrdinal( uint dwFindStringOrdinalFlags, string stringSource, int offset, int cchSource, string value, int cchValue, bool bIgnoreCase) { Debug.Assert(!GlobalizationMode.Invariant); fixed (char* pSource = stringSource) fixed (char* pValue = value) { int ret = Interop.Kernel32.FindStringOrdinal( dwFindStringOrdinalFlags, pSource + offset, cchSource, pValue, cchValue, bIgnoreCase ? 1 : 0); return ret < 0 ? ret : ret + offset; } } internal static int IndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(source != null); Debug.Assert(value != null); return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase); } internal static int LastIndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(source != null); Debug.Assert(value != null); return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase); } private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(source != null); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); if (source.Length == 0) { return 0; } int flags = GetNativeCompareFlags(options); int tmpHash = 0; #if CORECLR tmpHash = InternalGetGlobalizedHashCode(_sortHandle, _sortName, source, source.Length, flags); #else fixed (char* pSource = source) { if (Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, LCMAP_HASH | (uint)flags, pSource, source.Length, &tmpHash, sizeof(int), null, null, _sortHandle) == 0) { Environment.FailFast("LCMapStringEx failed!"); } } #endif return tmpHash; } private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2) { Debug.Assert(!GlobalizationMode.Invariant); // Use the OS to compare and then convert the result to expected value by subtracting 2 return Interop.Kernel32.CompareStringOrdinal(string1, count1, string2, count2, true) - 2; } // TODO https://github.com/dotnet/coreclr/issues/13827: // This method shouldn't be necessary, as we should be able to just use the overload // that takes two spans. But due to this issue, that's adding significant overhead. private unsafe int CompareString(ReadOnlySpan<char> string1, string string2, CompareOptions options) { Debug.Assert(string2 != null); Debug.Assert(!_invariantMode); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; fixed (char* pLocaleName = localeName) fixed (char* pString1 = &MemoryMarshal.GetReference(string1)) fixed (char* pString2 = &string2.GetRawStringData()) { int result = Interop.Kernel32.CompareStringEx( pLocaleName, (uint)GetNativeCompareFlags(options), pString1, string1.Length, pString2, string2.Length, null, null, _sortHandle); if (result == 0) { Environment.FailFast("CompareStringEx failed"); } // Map CompareStringEx return value to -1, 0, 1. return result - 2; } } private unsafe int CompareString(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; fixed (char* pLocaleName = localeName) fixed (char* pString1 = &MemoryMarshal.GetReference(string1)) fixed (char* pString2 = &MemoryMarshal.GetReference(string2)) { int result = Interop.Kernel32.CompareStringEx( pLocaleName, (uint)GetNativeCompareFlags(options), pString1, string1.Length, pString2, string2.Length, null, null, _sortHandle); if (result == 0) { Environment.FailFast("CompareStringEx failed"); } // Map CompareStringEx return value to -1, 0, 1. return result - 2; } } private unsafe int FindString( uint dwFindNLSStringFlags, ReadOnlySpan<char> lpStringSource, ReadOnlySpan<char> lpStringValue, int* pcchFound) { Debug.Assert(!_invariantMode); string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; fixed (char* pLocaleName = localeName) fixed (char* pSource = &MemoryMarshal.GetReference(lpStringSource)) fixed (char* pValue = &MemoryMarshal.GetReference(lpStringValue)) { return Interop.Kernel32.FindNLSStringEx( pLocaleName, dwFindNLSStringFlags, pSource, lpStringSource.Length, pValue, lpStringValue.Length, pcchFound, null, null, _sortHandle); } } private unsafe int FindString( uint dwFindNLSStringFlags, string lpStringSource, int startSource, int cchSource, string lpStringValue, int startValue, int cchValue, int* pcchFound) { Debug.Assert(!_invariantMode); string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; fixed (char* pLocaleName = localeName) fixed (char* pSource = lpStringSource) fixed (char* pValue = lpStringValue) { char* pS = pSource + startSource; char* pV = pValue + startValue; return Interop.Kernel32.FindNLSStringEx( pLocaleName, dwFindNLSStringFlags, pS, cchSource, pV, cchValue, pcchFound, null, null, _sortHandle); } } internal unsafe int IndexOfCore(String source, String target, int startIndex, int count, CompareOptions options, int* matchLengthPtr) { Debug.Assert(!_invariantMode); Debug.Assert(source != null); Debug.Assert(target != null); Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); if (target.Length == 0) { if (matchLengthPtr != null) *matchLengthPtr = 0; return startIndex; } if (source.Length == 0) { return -1; } if ((options & CompareOptions.Ordinal) != 0) { int retValue = FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: false); if (retValue >= 0) { if (matchLengthPtr != null) *matchLengthPtr = target.Length; } return retValue; } else { int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options), source, startIndex, count, target, 0, target.Length, matchLengthPtr); if (retValue >= 0) { return retValue + startIndex; } } return -1; } private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(target != null); Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); // TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for // and add a precondition that target is not empty. if (target.Length == 0) return startIndex; // keep Whidbey compatibility if ((options & CompareOptions.Ordinal) != 0) { return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: true); } else { int retValue = FindString(FIND_FROMEND | (uint)GetNativeCompareFlags(options), source, startIndex - count + 1, count, target, 0, target.Length, null); if (retValue >= 0) { return retValue + startIndex - (count - 1); } } return -1; } private unsafe bool StartsWith(string source, string prefix, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(!string.IsNullOrEmpty(prefix)); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length, prefix, 0, prefix.Length, null) >= 0; } private unsafe bool StartsWith(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(!source.IsEmpty); Debug.Assert(!prefix.IsEmpty); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, prefix, null) >= 0; } private unsafe bool EndsWith(string source, string suffix, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(!string.IsNullOrEmpty(suffix)); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length, suffix, 0, suffix.Length, null) >= 0; } private unsafe bool EndsWith(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(!source.IsEmpty); Debug.Assert(!suffix.IsEmpty); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, suffix, null) >= 0; } // PAL ends here [NonSerialized] private IntPtr _sortHandle; private const uint LCMAP_SORTKEY = 0x00000400; private const uint LCMAP_HASH = 0x00040000; private const int FIND_STARTSWITH = 0x00100000; private const int FIND_ENDSWITH = 0x00200000; private const int FIND_FROMSTART = 0x00400000; private const int FIND_FROMEND = 0x00800000; // TODO: Instead of this method could we just have upstack code call IndexOfOrdinal with ignoreCase = false? private static unsafe int FastIndexOfString(string source, string target, int startIndex, int sourceCount, int targetCount, bool findLastIndex) { int retValue = -1; int sourceStartIndex = findLastIndex ? startIndex - sourceCount + 1 : startIndex; fixed (char* pSource = source, spTarget = target) { char* spSubSource = pSource + sourceStartIndex; if (findLastIndex) { int startPattern = (sourceCount - 1) - targetCount + 1; if (startPattern < 0) return -1; char patternChar0 = spTarget[0]; for (int ctrSrc = startPattern; ctrSrc >= 0; ctrSrc--) { if (spSubSource[ctrSrc] != patternChar0) continue; int ctrPat; for (ctrPat = 1; ctrPat < targetCount; ctrPat++) { if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat]) break; } if (ctrPat == targetCount) { retValue = ctrSrc; break; } } if (retValue >= 0) { retValue += startIndex - sourceCount + 1; } } else { int endPattern = (sourceCount - 1) - targetCount + 1; if (endPattern < 0) return -1; char patternChar0 = spTarget[0]; for (int ctrSrc = 0; ctrSrc <= endPattern; ctrSrc++) { if (spSubSource[ctrSrc] != patternChar0) continue; int ctrPat; for (ctrPat = 1; ctrPat < targetCount; ctrPat++) { if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat]) break; } if (ctrPat == targetCount) { retValue = ctrSrc; break; } } if (retValue >= 0) { retValue += startIndex; } } } return retValue; } private unsafe SortKey CreateSortKey(String source, CompareOptions options) { Debug.Assert(!_invariantMode); if (source == null) { throw new ArgumentNullException(nameof(source)); } if ((options & ValidSortkeyCtorMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } byte [] keyData = null; if (source.Length == 0) { keyData = Array.Empty<byte>(); } else { fixed (char *pSource = source) { int result = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, LCMAP_SORTKEY | (uint) GetNativeCompareFlags(options), pSource, source.Length, null, 0, null, null, _sortHandle); if (result == 0) { throw new ArgumentException(SR.Argument_InvalidFlag, "source"); } keyData = new byte[result]; fixed (byte* pBytes = keyData) { result = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, LCMAP_SORTKEY | (uint) GetNativeCompareFlags(options), pSource, source.Length, pBytes, keyData.Length, null, null, _sortHandle); } } } return new SortKey(Name, source, options, keyData); } private static unsafe bool IsSortable(char* text, int length) { Debug.Assert(!GlobalizationMode.Invariant); return Interop.Kernel32.IsNLSDefinedString(Interop.Kernel32.COMPARE_STRING, 0, IntPtr.Zero, text, length); } private const int COMPARE_OPTIONS_ORDINAL = 0x40000000; // Ordinal private const int NORM_IGNORECASE = 0x00000001; // Ignores case. (use LINGUISTIC_IGNORECASE instead) private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal. private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. (use LINGUISTIC_IGNOREDIACRITIC instead) private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols. private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character. private const int NORM_LINGUISTIC_CASING = 0x08000000; // use linguistic rules for casing private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols. private static int GetNativeCompareFlags(CompareOptions options) { // Use "linguistic casing" by default (load the culture's casing exception tables) int nativeCompareFlags = NORM_LINGUISTIC_CASING; if ((options & CompareOptions.IgnoreCase) != 0) { nativeCompareFlags |= NORM_IGNORECASE; } if ((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; } if ((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; } if ((options & CompareOptions.IgnoreSymbols) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS; } if ((options & CompareOptions.IgnoreWidth) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH; } if ((options & CompareOptions.StringSort) != 0) { nativeCompareFlags |= SORT_STRINGSORT; } // TODO: Can we try for GetNativeCompareFlags to never // take Ordinal or OrdinalIgnoreCase. This value is not part of Win32, we just handle it special // in some places. // Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; } Debug.Assert(((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreWidth | CompareOptions.StringSort)) == 0) || (options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled"); return nativeCompareFlags; } private unsafe SortVersion GetSortVersion() { Debug.Assert(!_invariantMode); Interop.Kernel32.NlsVersionInfoEx nlsVersion = new Interop.Kernel32.NlsVersionInfoEx(); nlsVersion.dwNLSVersionInfoSize = Marshal.SizeOf(typeof(Interop.Kernel32.NlsVersionInfoEx)); Interop.Kernel32.GetNLSVersionEx(Interop.Kernel32.COMPARE_STRING, _sortName, &nlsVersion); return new SortVersion( nlsVersion.dwNLSVersion, nlsVersion.dwEffectiveId == 0 ? LCID : nlsVersion.dwEffectiveId, nlsVersion.guidCustomVersion); } #if CORECLR // Get a locale sensitive sort hash code from native code -- COMNlsInfo::InternalGetGlobalizedHashCode [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern int InternalGetGlobalizedHashCode(IntPtr handle, string localeName, string source, int length, int dwFlags); #endif } }
using System.Collections.Generic; using System.Linq; using System; public abstract class Animal : Organism { protected int sleepRemaining; protected Animal(string name, Point location, int size) : base(location, size) { this.Name = name; this.sleepRemaining = 0; } public AnimalState State { get; protected set; } public string Name { get; private set; } public virtual int GetMeatFromKillQuantity() { this.IsAlive = false; return this.Size; } public void GoTo(Point destination) { this.Location = destination; if (this.State == AnimalState.Sleeping) { this.Awake(); } } public void Sleep(int time) { this.sleepRemaining = time; this.State = AnimalState.Sleeping; } public override void Update(int timeElapsed) { if (this.sleepRemaining == 0) { this.Awake(); } } public override string ToString() { return base.ToString() + " " + this.Name; } protected void Awake() { this.sleepRemaining = 0; this.State = AnimalState.Awake; } } public enum AnimalState { Sleeping, Awake } class Boar : Animal, ICarnivore, IHerbivore { private const int BiteSize = 2; private const int BoarSize = 4; public Boar(string name, Point location) : base(name, location, BoarSize) { } public int EatPlant(Plant plant) { if (plant != null) { this.Size += 1; return plant.GetEatenQuantity(BiteSize); } return 0; } public int TryEatAnimal(Animal animal) { if (animal != null) { if (this.Size >= animal.Size) { return animal.GetMeatFromKillQuantity(); } } return 0; } } public class Bush : Plant { public Bush(Point location) : base(location, 4) { } } public class Deer : Animal, IHerbivore { private int biteSize; public Deer(string name, Point location) : base(name, location, 3) { this.biteSize = 1; } public override void Update(int timeElapsed) { if (this.State == AnimalState.Sleeping) { if (timeElapsed >= this.sleepRemaining) { this.Awake(); } else { this.sleepRemaining -= timeElapsed; } } base.Update(timeElapsed); } public int EatPlant(Plant p) { if (p != null) { return p.GetEatenQuantity(this.biteSize); } return 0; } } public class Engine { protected static readonly char[] separators = new char[] { ' ' }; protected List<Organism> allOrganisms; protected List<Plant> plants; protected List<Animal> animals; public Engine() { this.allOrganisms = new List<Organism>(); this.plants = new List<Plant>(); this.animals = new List<Animal>(); } public void AddOrganism(Organism organism) { this.allOrganisms.Add(organism); var organismAsAnimal = organism as Animal; var organismAsPlant = organism as Plant; if (organismAsAnimal != null) { this.animals.Add(organismAsAnimal); } if (organismAsPlant != null) { this.plants.Add(organismAsPlant); } } public void ExecuteCommand(string command) { string[] commandWords = command.Split(Engine.separators, StringSplitOptions.RemoveEmptyEntries); if (commandWords[0] == "birth") { this.ExecuteBirthCommand(commandWords); } else { this.ExecuteAnimalCommand(commandWords); } this.RemoveAndReportDead(); } protected virtual void ExecuteBirthCommand(string[] commandWords) { switch (commandWords[1]) { case "deer": { string name = commandWords[2]; Point position = Point.Parse(commandWords[3]); this.AddOrganism(new Deer(name, position)); break; } case "tree": { Point position = Point.Parse(commandWords[2]); this.AddOrganism(new Tree(position)); break; } case "bush": { Point position = Point.Parse(commandWords[2]); this.AddOrganism(new Bush(position)); break; } } } protected virtual void ExecuteAnimalCommand(string[] commandWords) { switch (commandWords[0]) { case "go": { string name = commandWords[1]; Point destination = Point.Parse(commandWords[2]); destination = this.HandleGo(name, destination); break; } case "sleep": { string name = commandWords[1]; int sleepTime = int.Parse(commandWords[2]); this.HandleSleep(name, sleepTime); break; } } } protected virtual void RemoveAndReportDead() { foreach (var organism in this.allOrganisms) { if (!organism.IsAlive) { Console.WriteLine("{0} is dead ;(", organism); } } this.allOrganisms.RemoveAll(o => !o.IsAlive); this.plants.RemoveAll(o => !o.IsAlive); this.animals.RemoveAll(o => !o.IsAlive); } protected virtual void UpdateAll(int timeElapsed) { foreach (var organism in this.allOrganisms) { organism.Update(timeElapsed); } } private Point HandleGo(string name, Point destination) { Animal current = this.GetAnimalByName(name); if (current != null) { int travelTime = Point.GetManhattanDistance(current.Location, destination); this.UpdateAll(travelTime); current.GoTo(destination); this.HandleEncounters(current); } return destination; } private void HandleEncounters(Animal current) { List<Organism> allEncountered = new List<Organism>(); foreach (var organism in this.allOrganisms) { if (organism.Location == current.Location && !(organism == current)) { allEncountered.Add(organism); } } var currentAsHerbivore = current as IHerbivore; if (currentAsHerbivore != null) { foreach (var encountered in allEncountered) { int eatenQuantity = currentAsHerbivore.EatPlant(encountered as Plant); if (eatenQuantity != 0) { Console.WriteLine("{0} ate {1} from {2}", current, eatenQuantity, encountered); } } } allEncountered.RemoveAll(o => !o.IsAlive); var currentAsCarnivore = current as ICarnivore; if (currentAsCarnivore != null) { foreach (var encountered in allEncountered) { int eatenQuantity = currentAsCarnivore.TryEatAnimal(encountered as Animal); if (eatenQuantity != 0) { Console.WriteLine("{0} ate {1} from {2}", current, eatenQuantity, encountered); } } } this.RemoveAndReportDead(); } private void HandleSleep(string name, int sleepTime) { Animal current = this.GetAnimalByName(name); if (current != null) { current.Sleep(sleepTime); } } private Animal GetAnimalByName(string name) { Animal current = null; foreach (var animal in this.animals) { if (animal.Name == name) { current = animal; break; } } return current; } } class ExtendedEngine : Engine { protected override void ExecuteBirthCommand(string[] commandWords) { switch (commandWords[1]) { case "wolf": { string name = commandWords[2]; Point position = Point.Parse(commandWords[3]); this.AddOrganism(new Wolf(name, position)); break; } case "lion": { string name = commandWords[2]; Point position = Point.Parse(commandWords[3]); this.AddOrganism(new Lion(name, position)); break; } case "grass": { Point position = Point.Parse(commandWords[2]); this.AddOrganism(new Grass(position)); break; } case "boar": { string name = commandWords[2]; Point position = Point.Parse(commandWords[3]); this.AddOrganism(new Boar(name, position)); break; } case "zombie": { string name = commandWords[2]; Point position = Point.Parse(commandWords[3]); this.AddOrganism(new Zombie(name, position)); break; } default: { base.ExecuteBirthCommand(commandWords); break; } } } } class Grass : Plant { private const int GrassSize = 2; public Grass(Point location) : base(location, GrassSize) { } public override void Update(int time) { if (this.IsAlive) { this.Size += time; } } } public interface ICarnivore { int TryEatAnimal(Animal animal); } public interface IHerbivore { int EatPlant(Plant plant); } public interface IOrganism { bool IsAlive { get; } Point Location { get; } int Size { get; } void Update(int timeElapsed); } class Lion : Animal, ICarnivore { private const int LionSize = 6; public Lion(string name, Point location) : base(name, location, LionSize) { } public int TryEatAnimal(Animal animal) { if (animal != null) { if (this.Size >= animal.Size / 2) { this.Size += 1; return animal.GetMeatFromKillQuantity(); } } return 0; } } public abstract class Organism : IOrganism { public Organism(Point location, int size) { this.Location = location; this.Size = size; this.IsAlive = true; } public bool IsAlive { get; protected set; } public Point Location { get; protected set; } public int Size { get; protected set; } public virtual void Update(int time) { } public virtual void RespondTo(IOrganism organism) { } public override string ToString() { return this.GetType().Name; } } public abstract class Plant : Organism { protected Plant(Point location, int size) : base(location, size) { } public int GetEatenQuantity(int biteSize) { if (biteSize > this.Size) { this.IsAlive = false; this.Size = 0; return this.Size; } else { this.Size -= biteSize; return biteSize; } } public override string ToString() { return base.ToString() + " " + this.Location; } } public struct Point { public readonly int X; public readonly int Y; public Point(int x, int y) { this.X = x; this.Y = y; } public Point(string xString, string yString) { this.X = int.Parse(xString); this.Y = int.Parse(yString); } public static Point Parse(string pointString) { string coordinatesPairString = pointString.Substring(1, pointString.Length - 2); string[] coordinates = coordinatesPairString.Split(','); return new Point(coordinates[0], coordinates[1]); } public static int GetManhattanDistance(Point a, Point b) { return Math.Abs(a.X - b.X) + Math.Abs(a.Y - b.Y); } public override int GetHashCode() { return this.X * 7 + this.Y; } public override string ToString() { return String.Format("({0},{1})", this.X, this.Y); } public static bool operator ==(Point a, Point b) { return a.X == b.X && a.Y == b.Y; } public static bool operator !=(Point a, Point b) { return !(a == b); } } class Program { static Engine GetEngineInstance() { return new ExtendedEngine(); } static void Main(string[] args) { Engine engine = GetEngineInstance(); string command = Console.ReadLine(); while (command != "end") { engine.ExecuteCommand(command); command = Console.ReadLine(); } } } public class Tree : Plant { public Tree(Point location) : base(location, 15) { } } class Wolf : Animal, ICarnivore { private const int WolfSize = 4; public Wolf(string name, Point location) : base(name, location, WolfSize) { } public int TryEatAnimal(Animal animal) { if (animal != null) { if (this.Size >= animal.Size || animal.State.Equals(AnimalState.Sleeping)) { return animal.GetMeatFromKillQuantity(); } } return 0; } } class Zombie : Animal { private const int ZombieSize = 0; private const int MeatUnits = 10; public Zombie(string name, Point location) : base(name, location, ZombieSize) { } public override int GetMeatFromKillQuantity() { return MeatUnits; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: The contract class allows for expressing preconditions, ** postconditions, and object invariants about methods in source ** code for runtime checking & static analysis. ** ** Two classes (Contract and ContractHelper) are split into partial classes ** in order to share the public front for multiple platforms (this file) ** while providing separate implementation details for each platform. ** ===========================================================*/ #define DEBUG // The behavior of this contract library should be consistent regardless of build type. using System.Collections.Generic; using System.Reflection; namespace System.Diagnostics.Contracts { #region Attributes /// <summary> /// Methods and classes marked with this attribute can be used within calls to Contract methods. Such methods not make any visible state changes. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public sealed class PureAttribute : Attribute { } /// <summary> /// Types marked with this attribute specify that a separate type contains the contracts for this type. /// </summary> [Conditional("CONTRACTS_FULL")] [Conditional("DEBUG")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class ContractClassAttribute : Attribute { private Type _typeWithContracts; public ContractClassAttribute(Type typeContainingContracts) { _typeWithContracts = typeContainingContracts; } public Type TypeContainingContracts { get { return _typeWithContracts; } } } /// <summary> /// Types marked with this attribute specify that they are a contract for the type that is the argument of the constructor. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class ContractClassForAttribute : Attribute { private Type _typeIAmAContractFor; public ContractClassForAttribute(Type typeContractsAreFor) { _typeIAmAContractFor = typeContractsAreFor; } public Type TypeContractsAreFor { get { return _typeIAmAContractFor; } } } /// <summary> /// This attribute is used to mark a method as being the invariant /// method for a class. The method can have any name, but it must /// return "void" and take no parameters. The body of the method /// must consist solely of one or more calls to the method /// Contract.Invariant. A suggested name for the method is /// "ObjectInvariant". /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class ContractInvariantMethodAttribute : Attribute { } /// <summary> /// Attribute that specifies that an assembly is a reference assembly with contracts. /// </summary> [AttributeUsage(AttributeTargets.Assembly)] public sealed class ContractReferenceAssemblyAttribute : Attribute { } /// <summary> /// Methods (and properties) marked with this attribute can be used within calls to Contract methods, but have no runtime behavior associated with them. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class ContractRuntimeIgnoredAttribute : Attribute { } /// <summary> /// Instructs downstream tools whether to assume the correctness of this assembly, type or member without performing any verification or not. /// Can use [ContractVerification(false)] to explicitly mark assembly, type or member as one to *not* have verification performed on it. /// Most specific element found (member, type, then assembly) takes precedence. /// (That is useful if downstream tools allow a user to decide which polarity is the default, unmarked case.) /// </summary> /// <remarks> /// Apply this attribute to a type to apply to all members of the type, including nested types. /// Apply this attribute to an assembly to apply to all types and members of the assembly. /// Apply this attribute to a property to apply to both the getter and setter. /// </remarks> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] public sealed class ContractVerificationAttribute : Attribute { private bool _value; public ContractVerificationAttribute(bool value) { _value = value; } public bool Value { get { return _value; } } } /// <summary> /// Allows a field f to be used in the method contracts for a method m when f has less visibility than m. /// For instance, if the method is public, but the field is private. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Field)] public sealed class ContractPublicPropertyNameAttribute : Attribute { private string _publicName; public ContractPublicPropertyNameAttribute(string name) { _publicName = name; } public string Name { get { return _publicName; } } } /// <summary> /// Enables factoring legacy if-then-throw into separate methods for reuse and full control over /// thrown exception and arguments /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractArgumentValidatorAttribute : Attribute { } /// <summary> /// Enables writing abbreviations for contracts that get copied to other methods /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractAbbreviatorAttribute : Attribute { } /// <summary> /// Allows setting contract and tool options at assembly, type, or method granularity. /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractOptionAttribute : Attribute { private string _category; private string _setting; private bool _enabled; private string _value; public ContractOptionAttribute(string category, string setting, bool enabled) { _category = category; _setting = setting; _enabled = enabled; } public ContractOptionAttribute(string category, string setting, string value) { _category = category; _setting = setting; _value = value; } public string Category { get { return _category; } } public string Setting { get { return _setting; } } public bool Enabled { get { return _enabled; } } public string Value { get { return _value; } } } #endregion Attributes /// <summary> /// Contains static methods for representing program contracts such as preconditions, postconditions, and invariants. /// </summary> /// <remarks> /// WARNING: A binary rewriter must be used to insert runtime enforcement of these contracts. /// Otherwise some contracts like Ensures can only be checked statically and will not throw exceptions during runtime when contracts are violated. /// Please note this class uses conditional compilation to help avoid easy mistakes. Defining the preprocessor /// symbol CONTRACTS_PRECONDITIONS will include all preconditions expressed using Contract.Requires in your /// build. The symbol CONTRACTS_FULL will include postconditions and object invariants, and requires the binary rewriter. /// </remarks> public static partial class Contract { #region User Methods #region Assume /// <summary> /// Instructs code analysis tools to assume the expression <paramref name="condition"/> is true even if it can not be statically proven to always be true. /// </summary> /// <param name="condition">Expression to assume will always be true.</param> /// <remarks> /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Contract.Assert(bool)"/>. /// </remarks> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] public static void Assume(bool condition) { if (!condition) { ReportFailure(ContractFailureKind.Assume, null, null, null); } } /// <summary> /// Instructs code analysis tools to assume the expression <paramref name="condition"/> is true even if it can not be statically proven to always be true. /// </summary> /// <param name="condition">Expression to assume will always be true.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Contract.Assert(bool)"/>. /// </remarks> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] public static void Assume(bool condition, string userMessage) { if (!condition) { ReportFailure(ContractFailureKind.Assume, userMessage, null, null); } } #endregion Assume #region Assert /// <summary> /// In debug builds, perform a runtime check that <paramref name="condition"/> is true. /// </summary> /// <param name="condition">Expression to check to always be true.</param> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] public static void Assert(bool condition) { if (!condition) ReportFailure(ContractFailureKind.Assert, null, null, null); } /// <summary> /// In debug builds, perform a runtime check that <paramref name="condition"/> is true. /// </summary> /// <param name="condition">Expression to check to always be true.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] public static void Assert(bool condition, string userMessage) { if (!condition) ReportFailure(ContractFailureKind.Assert, userMessage, null, null); } #endregion Assert #region Requires /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when backward compatibility does not force you to throw a particular exception. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] public static void Requires(bool condition) { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when backward compatibility does not force you to throw a particular exception. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] public static void Requires(bool condition, string userMessage) { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when you want to throw a particular exception. /// </remarks> [Pure] public static void Requires<TException>(bool condition) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when you want to throw a particular exception. /// </remarks> [Pure] public static void Requires<TException>(bool condition, string userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>"); } #endregion Requires #region Ensures /// <summary> /// Specifies a public contract such that the expression <paramref name="condition"/> will be true when the enclosing method or property returns normally. /// </summary> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] public static void Ensures(bool condition) { AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures"); } /// <summary> /// Specifies a public contract such that the expression <paramref name="condition"/> will be true when the enclosing method or property returns normally. /// </summary> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] public static void Ensures(bool condition, string userMessage) { AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures"); } /// <summary> /// Specifies a contract such that if an exception of type <typeparamref name="TException"/> is thrown then the expression <paramref name="condition"/> will be true when the enclosing method or property terminates abnormally. /// </summary> /// <typeparam name="TException">Type of exception related to this postcondition.</typeparam> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] public static void EnsuresOnThrow<TException>(bool condition) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow"); } /// <summary> /// Specifies a contract such that if an exception of type <typeparamref name="TException"/> is thrown then the expression <paramref name="condition"/> will be true when the enclosing method or property terminates abnormally. /// </summary> /// <typeparam name="TException">Type of exception related to this postcondition.</typeparam> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] public static void EnsuresOnThrow<TException>(bool condition, string userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow"); } #region Old, Result, and Out Parameters /// <summary> /// Represents the result (a.k.a. return value) of a method or property. /// </summary> /// <typeparam name="T">Type of return value of the enclosing method or property.</typeparam> /// <returns>Return value of the enclosing method or property.</returns> /// <remarks> /// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract. /// </remarks> [Pure] public static T Result<T>() { return default; } /// <summary> /// Represents the final (output) value of an out parameter when returning from a method. /// </summary> /// <typeparam name="T">Type of the out parameter.</typeparam> /// <param name="value">The out parameter.</param> /// <returns>The output value of the out parameter.</returns> /// <remarks> /// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract. /// </remarks> [Pure] public static T ValueAtReturn<T>(out T value) { value = default; return value; } /// <summary> /// Represents the value of <paramref name="value"/> as it was at the start of the method or property. /// </summary> /// <typeparam name="T">Type of <paramref name="value"/>. This can be inferred.</typeparam> /// <param name="value">Value to represent. This must be a field or parameter.</param> /// <returns>Value of <paramref name="value"/> at the start of the method or property.</returns> /// <remarks> /// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract. /// </remarks> [Pure] public static T OldValue<T>(T value) { return default; } #endregion Old, Result, and Out Parameters #endregion Ensures #region Invariant /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> will be true after every method or property on the enclosing class. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <remarks> /// This contact can only be specified in a dedicated invariant method declared on a class. /// This contract is not exposed to clients so may reference members less visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this invariant. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] public static void Invariant(bool condition) { AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> will be true after every method or property on the enclosing class. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This contact can only be specified in a dedicated invariant method declared on a class. /// This contract is not exposed to clients so may reference members less visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this invariant. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] public static void Invariant(bool condition, string userMessage) { AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant"); } #endregion Invariant #region Quantifiers #region ForAll /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for all integers starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1. /// </summary> /// <param name="fromInclusive">First integer to pass to <paramref name="predicate"/>.</param> /// <param name="toExclusive">One greater than the last integer to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</param> /// <returns><c>true</c> if <paramref name="predicate"/> returns <c>true</c> for all integers /// starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.TrueForAll"/> [Pure] public static bool ForAll(int fromInclusive, int toExclusive, Predicate<int> predicate) { if (fromInclusive > toExclusive) throw new ArgumentException(SR.Argument_ToExclusiveLessThanFromExclusive); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); for (int i = fromInclusive; i < toExclusive; i++) if (!predicate(i)) return false; return true; } /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for all elements in the <paramref name="collection"/>. /// </summary> /// <param name="collection">The collection from which elements will be drawn from to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated on elements from <paramref name="collection"/>.</param> /// <returns><c>true</c> if and only if <paramref name="predicate"/> returns <c>true</c> for all elements in /// <paramref name="collection"/>.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.TrueForAll"/> [Pure] public static bool ForAll<T>(IEnumerable<T> collection, Predicate<T> predicate) { if (collection == null) throw new ArgumentNullException(nameof(collection)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); foreach (T t in collection) if (!predicate(t)) return false; return true; } #endregion ForAll #region Exists /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for any integer starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1. /// </summary> /// <param name="fromInclusive">First integer to pass to <paramref name="predicate"/>.</param> /// <param name="toExclusive">One greater than the last integer to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</param> /// <returns><c>true</c> if <paramref name="predicate"/> returns <c>true</c> for any integer /// starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.Exists"/> [Pure] public static bool Exists(int fromInclusive, int toExclusive, Predicate<int> predicate) { if (fromInclusive > toExclusive) throw new ArgumentException(SR.Argument_ToExclusiveLessThanFromExclusive); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); for (int i = fromInclusive; i < toExclusive; i++) if (predicate(i)) return true; return false; } /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for any element in the <paramref name="collection"/>. /// </summary> /// <param name="collection">The collection from which elements will be drawn from to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated on elements from <paramref name="collection"/>.</param> /// <returns><c>true</c> if and only if <paramref name="predicate"/> returns <c>true</c> for an element in /// <paramref name="collection"/>.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.Exists"/> [Pure] public static bool Exists<T>(IEnumerable<T> collection, Predicate<T> predicate) { if (collection == null) throw new ArgumentNullException(nameof(collection)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); foreach (T t in collection) if (predicate(t)) return true; return false; } #endregion Exists #endregion Quantifiers #region Pointers #endregion #region Misc. /// <summary> /// Marker to indicate the end of the contract section of a method. /// </summary> [Conditional("CONTRACTS_FULL")] public static void EndContractBlock() { } #endregion #endregion User Methods #region Private Methods /// <summary> /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// </summary> private static void AssertMustUseRewriter(ContractFailureKind kind, string contractKind) { // For better diagnostics, report which assembly is at fault. Walk up stack and // find the first non-mscorlib assembly. Assembly thisAssembly = typeof(Contract).Assembly; // In case we refactor mscorlib, use Contract class instead of Object. StackTrace stack = new StackTrace(); Assembly probablyNotRewritten = null; for (int i = 0; i < stack.FrameCount; i++) { Assembly caller = stack.GetFrame(i).GetMethod()?.DeclaringType.Assembly; if (caller != null && caller != thisAssembly) { probablyNotRewritten = caller; break; } } if (probablyNotRewritten == null) probablyNotRewritten = thisAssembly; string simpleName = probablyNotRewritten.GetName().Name; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null); } #endregion Private Methods #region Failure Behavior /// <summary> /// Without contract rewriting, failing Assert/Assumes end up calling this method. /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// </summary> [System.Diagnostics.DebuggerNonUserCode] private static void ReportFailure(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message var displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); if (displayMessage == null) return; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException); } /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) /// to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust, because it will inform you of bugs in the appdomain and because the event handler /// could allow you to continue execution. /// </summary> public static event EventHandler<ContractFailedEventArgs> ContractFailed { add { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value; } remove { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value; } } #endregion Failure Behavior } [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public enum ContractFailureKind { Precondition, Postcondition, PostconditionOnException, Invariant, Assert, Assume, } } // namespace System.Runtime.CompilerServices
using System.Collections.Generic; using System.Linq; using FluentNHibernate.Mapping; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.ClassBased; using FluentNHibernate.MappingModel.Collections; using FluentNHibernate.Utils; using FluentNHibernate.Visitors; using NUnit.Framework; namespace FluentNHibernate.Testing.Visitors { [TestFixture] public class when_the_component_column_prefix_visitor_processes_a_reference_component_with_a_prefix_using_the_property_alias : ComponentColumnPrefixVisitorSpec { PersistenceModel model; IEnumerable<HibernateMapping> mappings; ClassMapping target_mapping; private const string column_prefix = "{property}_"; public override void establish_context() { model = new PersistenceModel(); var comp_map = new ComponentMap<ComponentTarget>(); comp_map.Map(x => x.Property); model.Add(comp_map); var map = new ClassMap<Target>(); map.Id(x => x.Id); map.Component(x => x.Component) .ColumnPrefix(column_prefix); model.Add(map); } public override void because() { mappings = model.BuildMappings(); target_mapping = mappings .SelectMany(x => x.Classes) .FirstOrDefault(x => x.Type == typeof(Target)); } [Test] public void should_prefix_property_columns() { target_mapping.Components.Single() .Properties.SelectMany(x => x.Columns) .Each(x => x.Name.ShouldStartWith("Component_")); } } [TestFixture] public class when_the_component_column_prefix_visitor_processes_a_reference_component_with_an_inner_reference_component_with_its_own_prefix : ComponentColumnPrefixVisitorSpec { PersistenceModel model; IEnumerable<HibernateMapping> mappings; ClassMapping target_mapping; private const string first_prefix = "first_"; private const string second_prefix = "second_"; public override void establish_context() { model = new PersistenceModel(); var comp_map = new ComponentMap<ComponentTarget>(); comp_map.Map(x => x.Property); comp_map.Component(x => x.Component) .ColumnPrefix(second_prefix); model.Add(comp_map); var comp2_map = new ComponentMap<Child>(); comp2_map.Map(x => x.Property); model.Add(comp2_map); var map = new ClassMap<Target>(); map.Id(x => x.Id); map.Component(x => x.Component) .ColumnPrefix(first_prefix); model.Add(map); } public override void because() { mappings = model.BuildMappings(); target_mapping = mappings .SelectMany(x => x.Classes) .FirstOrDefault(x => x.Type == typeof(Target)); } [Test] public void should_prefix_sub_component_columns_with_both_prefixes() { target_mapping .Components.Single() .Components.Single() .Properties.SelectMany(x => x.Columns) .Each(x => x.Name.ShouldStartWith(first_prefix + second_prefix)); } } [TestFixture] public class when_the_component_column_prefix_visitor_processes_a_reference_component_after_already_processed_another : ComponentColumnPrefixVisitorSpec { private const string column_prefix = "prefix_"; private ComponentColumnPrefixVisitor visitor; private ReferenceComponentMapping reference_with_a_prefix; private ReferenceComponentMapping reference_without_a_prefix; public override void establish_context() { visitor = new ComponentColumnPrefixVisitor(); reference_with_a_prefix = new ReferenceComponentMapping(ComponentType.Component, new DummyPropertyInfo("PROPERTY", typeof(Target)).ToMember(), typeof(ComponentTarget), typeof(Target), column_prefix); reference_with_a_prefix.AssociateExternalMapping(new ExternalComponentMapping(ComponentType.Component)); reference_without_a_prefix = new ReferenceComponentMapping(ComponentType.Component, new DummyPropertyInfo("PROPERTY", typeof(Target)).ToMember(), typeof(ComponentTarget), typeof(Target), null); var external_mapping = new ExternalComponentMapping(ComponentType.Component); external_mapping.AddProperty(property_with_column("propertyColumn")); reference_without_a_prefix.AssociateExternalMapping(external_mapping); } public override void because() { visitor.Visit(reference_with_a_prefix); visitor.Visit(reference_without_a_prefix); } [Test] public void shouldnt_use_the_original_prefix() { reference_without_a_prefix.Properties.SelectMany(x => x.Columns) .Each(x => x.Name.ShouldNotStartWith(column_prefix)); } } [TestFixture] public class when_the_component_column_prefix_visitor_processes_a_reference_component_with_a_prefix : ComponentColumnPrefixVisitorSpec { PersistenceModel model; IEnumerable<HibernateMapping> mappings; ClassMapping target_mapping; private const string column_prefix = "prefix_"; public override void establish_context() { model = new PersistenceModel(); var comp_map = new ComponentMap<ComponentTarget>(); comp_map.Map(x => x.Property); comp_map.HasMany(x => x.Children); comp_map.Component(x => x.Component, c => c.Map(x => x.Property)); model.Add(comp_map); var map = new ClassMap<Target>(); map.Id(x => x.Id); map.Component(x => x.Component) .ColumnPrefix(column_prefix); model.Add(map); } public override void because() { mappings = model.BuildMappings(); target_mapping = mappings .SelectMany(x => x.Classes) .FirstOrDefault(x => x.Type == typeof(Target)); } [Test] public void should_prefix_collection_columns() { target_mapping.Components.Single().Collections.ShouldHaveCount(1); target_mapping.Components.Single().Collections .SelectMany(x => x.Key.Columns) .Each(x => x.Name.ShouldStartWith(column_prefix)); } [Test] public void should_prefix_columns_inside_an_inner_component() { target_mapping.Components.ShouldHaveCount(1); target_mapping.Components.SelectMany(x => x.Components).ShouldHaveCount(1); target_mapping.Components .SelectMany(x => x.Components) .SelectMany(x => x.Properties) .SelectMany(x => x.Columns) .Each(x => x.Name.ShouldStartWith(column_prefix)); } [Test] public void should_prefix_property_columns() { target_mapping.Components.Single().Properties.ShouldHaveCount(1); target_mapping.Components.Single() .Properties.SelectMany(x => x.Columns) .Each(x => x.Name.ShouldStartWith(column_prefix)); } } [TestFixture] public class when_the_component_column_prefix_visitor_processes_a_component_with_a_prefix_using_field_alias : ComponentColumnPrefixVisitorSpec { PersistenceModel model; IEnumerable<HibernateMapping> mappings; ClassMapping targetMapping; const string columnPrefix = "{property}"; public override void establish_context() { model = new PersistenceModel(); var componentMap = new ComponentMap<FieldComponent>(); componentMap.Map(x => x.X); componentMap.Map(x => x.Y); model.Add(componentMap); var classMapping = new ClassMap<Root>(); classMapping.Id(r => r.Id); classMapping.Component(Reveal.Member<Root, FieldComponent>("component"), cpt => cpt.Access.Field().ColumnPrefix(columnPrefix)); model.Add(classMapping); } public override void because() { mappings = model.BuildMappings().ToList(); targetMapping = mappings.SelectMany(x => x.Classes).FirstOrDefault(x => x.Type == typeof(Root)); } [Test] public void should_prefix_field_columns() { targetMapping.Components.Single() .Properties.SelectMany(x => x.Columns) .Each(c => c.Name.ShouldStartWith("component")); } } class Root { FieldComponent component; public int Id { get; set; } } class FieldComponent { public string X { get; set; } public int? Y { get; set; } } public abstract class ComponentColumnPrefixVisitorSpec : Specification { protected AnyMapping any_with_column(string column) { var any = new AnyMapping(); any.AddIdentifierColumn(Layer.Defaults, new ColumnMapping(column)); any.AddTypeColumn(Layer.Defaults, new ColumnMapping(column)); return any; } protected CollectionMapping collection_with_column(string column) { var collection = CollectionMapping.Bag(); collection.Set(x => x.Key, Layer.Defaults, new KeyMapping()); collection.Key.AddColumn(Layer.Defaults, new ColumnMapping(column)); return collection; } protected PropertyMapping property_with_column(string column) { var property = new PropertyMapping(); property.AddColumn(Layer.Defaults, new ColumnMapping("propertyColumn")); return property; } protected ManyToOneMapping reference_with_column(string column) { var reference = new ManyToOneMapping(); reference.AddColumn(Layer.Defaults, new ColumnMapping("propertyColumn")); return reference; } protected class ComponentTarget { public string Property { get; set; } public IList<Child> Children { get; set; } public Child Component { get; set; } } protected class Child { public string Property { get; set; } } protected class Target { public int Id { get; set; } public ComponentTarget Component { get; set; } } } }
/****************************************************************************/ /* Command.cs */ /****************************************************************************/ /* AUTHOR: Vance Morrison * Date : 11/3/2005 */ /****************************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.IO; using System.Reflection; using System.Diagnostics; // for StackTrace; Process /// <summary> /// CommandOptions is a helper class for the Command class. It stores options /// that affect the behavior of the execution of Commands and is passes as a /// parapeter to the constuctor of a Command. /// /// It is useful for these options be be on a separate class (rather than /// on Command itself), because it is reasonably common to want to have a set /// of options passed to several commands, which is not easily possible otherwise. /// </summary> public sealed class CommandOptions { /// <summary> /// Can be assigned to the Timeout Property to indicate infinite timeout. /// </summary> public const int Infinite = System.Threading.Timeout.Infinite; /// <summary> /// CommanOptions holds a set of options that can be passed to the constructor /// to the Command Class as well as Command.Run* /// </summary> public CommandOptions() { timeoutMSec = 600000; } /// <summary> /// Return a copy an existing set of command options /// </summary> /// <returns>The copy of the command options</returns> public CommandOptions Clone() { return (CommandOptions)MemberwiseClone(); } /// <summary> /// Normally commands will throw if the subprocess returns a non-zero /// exit code. NoThrow suppresses this. /// </summary> public bool NoThrow { get { return noThrow; } set { noThrow = value; } } /// <summary> /// Updates the NoThrow propery and returns the updated commandOptions. /// <returns>Updated command options</returns> public CommandOptions AddNoThrow() { this.noThrow = true; return this; } /// <summary> /// Normally commands are launched with CreateProcess. However it is /// also possible use the Shell Start API. This causes Command to look /// up the executable differnetly as well as no wait for the command to /// compete before returning. /// </summary> public bool Start { get { return start; } set { start = value; } } /// <summary> /// Updates the Start propery and returns the updated commandOptions. /// </summary> public CommandOptions AddStart() { this.start = true; return this; } /// <summary> /// By default commands have a 10 minute timeout (600,000 msec), If this /// is inappropriate, the Timeout property can change this. Like all /// timouts in .NET, it is in units of milliseconds, and you can use /// CommandOptions.Infinite to indicate no timeout. /// </summary> public int Timeout { get { return timeoutMSec; } set { timeoutMSec = value; } } /// <summary> /// Updates the Timeout propery and returns the updated commandOptions. /// </summary> public CommandOptions AddTimeout(int milliseconds) { this.timeoutMSec = milliseconds; return this; } /// <summary> /// Indicates the string will be sent to Console.In for the subprocess. /// </summary> public string Input { get { return input; } set { input = value; } } /// <summary> /// Updates the Input propery and returns the updated commandOptions. /// </summary> public CommandOptions AddInput(string input) { this.input = input; return this; } /// <summary> /// Indicates the current directory the subProcess will have. /// </summary> public string CurrentDirectory { get { return currentDirectory; } set { currentDirectory = value; } } /// <summary> /// Updates the CurrentDirectory propery and returns the updated commandOptions. /// </summary> public CommandOptions AddCurrentDirectory(string directoryPath) { this.currentDirectory = directoryPath; return this; } // TODO add a capability to return a enumerator of output lines. (and/or maybe a delegate callback) /// <summary> /// Indicates the standard output and error of the command should be redirected /// to a archiveFile rather than being stored in memory in the 'Output' property of the /// command. /// </summary> public string OutputFile { get { return outputFile; } set { if (outputStream != null || outputHandler != null) throw new Exception("Only one of OutputFile, OutputStream and OutputHandler can be set"); outputFile = value; } } /// <summary> /// Updates the OutputFile propery and returns the updated commandOptions. /// </summary> public CommandOptions AddOutputFile(string outputFile) { OutputFile = outputFile; return this; } /// <summary> /// Indicates the standard output and error of the command should be redirected /// to a a TextWriter rather than being stored in memory in the 'Output' property /// of the command. /// </summary> public TextWriter OutputStream { get { return outputStream; } set { if (outputFile != null || outputHandler != null) throw new Exception("Only one of OutputFile, OutputStream and OutputHandler can be set"); outputStream = value; } } public DataReceivedEventHandler OutputHandler { get { return outputHandler; } set { if (outputStream != null || outputFile != null) throw new Exception("Only one of OutputFile, OutputStream and OutputHandler can be set"); outputHandler = value; } } /// <summary> /// Updates the OutputStream propery and returns the updated commandOptions. /// </summary> public CommandOptions AddOutputStream(TextWriter outputStream) { OutputStream = outputStream; return this; } /// <summary> /// Gets the Environment variables that will be set in the subprocess that /// differ from current process's environment variables. Any time a string /// of the form %VAR% is found in a value of a environment variable it is /// replaced with the value of the environment variable at the time the /// command is launched. This is useful for example to update the PATH /// environment variable eg. "%PATH%;someNewPath" /// </summary> public Dictionary<string, string> EnvironmentVariables { get { if (environmentVariables == null) environmentVariables = new Dictionary<string, string>(); return environmentVariables; } } /// <summary> /// Adds the environment variable with the give value to the set of /// environmetn variables to be passed to the sub-process and returns the /// updated commandOptions. Any time a string /// of the form %VAR% is found in a value of a environment variable it is /// replaced with the value of the environment variable at the time the /// command is launched. This is useful for example to update the PATH /// environment variable eg. "%PATH%;someNewPath" /// </summary> public CommandOptions AddEnvironmentVariable(string variable, string value) { EnvironmentVariables[variable] = value; return this; } // We ar friends with the Command class // TODO implement // internal bool showCommand; // Show the command before running it. internal bool noThrow; internal bool start; internal int timeoutMSec; internal string input; internal string outputFile; internal TextWriter outputStream; internal DataReceivedEventHandler outputHandler; internal string currentDirectory; internal Dictionary<string, string> environmentVariables; }; /// <summary> /// Command represents a running of a command lineNumber process. It is basically /// a wrapper over System.Diagnostics.Process, which hides the complexitity /// of System.Diagnostics.Process, and knows how to capture output and otherwise /// makes calling commands very easy. /// </summary> public sealed class Command { /// <summary> /// The time the process started. /// </summary> public DateTime StartTime { get { return process.StartTime; } } /// <summary> /// returns true if the process has exited. /// </summary> public bool HasExited { get { return process.HasExited; } } /// <summary> /// The time the processed Exited. (HasExited should be true before calling) /// </summary> public DateTime ExitTime { get { return process.ExitTime; } } /// <summary> /// The duration of the command (HasExited should be true before calling) /// </summary> public TimeSpan Duration { get { return ExitTime - StartTime; } } /// <summary> /// The operating system ID for the subprocess. /// </summary> public int Id { get { return process.Id; } } /// <summary> /// The process exit code for the subprocess. (HasExited should be true before calling) /// Often this does not need to be checked because Command.Run will throw an exception /// if it is not zero. However it is useful if the CommandOptions.NoThrow property /// was set. /// </summary> public int ExitCode { get { return process.ExitCode; } } /// <summary> /// The standard output and standard error output from the command. This /// is accumulated in real time so it can vary if the process is still running. /// /// This property is NOT available if the CommandOptions.OutputFile or CommandOptions.OutputStream /// is specified since the output is being redirected there. If a large amoutn of output is /// expected (> 1Meg), the Run.AddOutputStream(Stream) is recommended for retrieving it since /// the large string is never materialized at one time. /// </summary> public string Output { get { if (outputStream != null) throw new Exception("Output not available if redirected to file or stream"); return output.ToString(); } } /// <summary> /// Returns that CommandOptions structure that holds all the options that affect /// the running of the command (like Timeout, Input ...) /// </summary> public CommandOptions Options { get { return options; } } /// <summary> /// Run 'commandLine', sending the output to the console, and wait for the command to complete. /// This simulates what batch filedo when executing their commands. It is a bit more verbose /// by default, however /// </summary> /// <param variable="commandLine">The command lineNumber to run as a subprocess</param> /// <param variable="options">Additional qualifiers that control how the process is run</param> /// <returns>A Command structure that can be queried to determine ExitCode, Output, etc.</returns> public static Command RunToConsole(string commandLine, CommandOptions options) { return Run(commandLine, options.Clone().AddOutputStream(Console.Out)); } public static Command RunToConsole(string commandLine) { return RunToConsole(commandLine, new CommandOptions()); } /// <summary> /// Run 'commandLine' as a subprocess and waits for the command to complete. /// Output is captured and placed in the 'Output' property of the returned Command /// structure. /// </summary> /// <param variable="commandLine">The command lineNumber to run as a subprocess</param> /// <param variable="options">Additional qualifiers that control how the process is run</param> /// <returns>A Command structure that can be queried to determine ExitCode, Output, etc.</returns> public static Command Run(string commandLine, CommandOptions options) { Command run = new Command(commandLine, options); run.Wait(); return run; } public static Command Run(string commandLine) { return Run(commandLine, new CommandOptions()); } /// <summary> /// Launch a new command and returns the Command object that can be used to monitor /// the restult. It does not wait for the command to complete, however you /// can call 'Wait' to do that, or use the 'Run' or 'RunToConsole' methods. */ /// </summary> /// <param variable="commandLine">The command lineNumber to run as a subprocess</param> /// <param variable="options">Additional qualifiers that control how the process is run</param> /// <returns>A Command structure that can be queried to determine ExitCode, Output, etc.</returns> public Command(string commandLine, CommandOptions options) { this.options = options; this.commandLine = commandLine; // See if the command is quoted and match it in that case Match m = Regex.Match(commandLine, "^\\s*\"(.*?)\"\\s*(.*)"); if (!m.Success) m = Regex.Match(commandLine, @"\s*(\S*)\s*(.*)"); // thing before first space is command ProcessStartInfo startInfo = new ProcessStartInfo(m.Groups[1].Value, m.Groups[2].Value); process = new Process(); process.StartInfo = startInfo; if (options.start) { startInfo.UseShellExecute = true; } else { if (options.input != null) startInfo.RedirectStandardInput = true; startInfo.UseShellExecute = false; startInfo.RedirectStandardError = true; startInfo.RedirectStandardOutput = true; startInfo.ErrorDialog = false; startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.CreateNoWindow = true; output = new StringBuilder(); if (options.OutputHandler != null) { process.OutputDataReceived += options.outputHandler; process.ErrorDataReceived += options.outputHandler; } else { process.OutputDataReceived += new DataReceivedEventHandler(OnProcessOutput); process.ErrorDataReceived += new DataReceivedEventHandler(OnProcessOutput); } } if (options.environmentVariables != null) { // copy over the environment variables to the process startInfo options. foreach (string key in options.environmentVariables.Keys) { // look for %VAR% strings in the value and subtitute the appropriate environment variable. string value = options.environmentVariables[key]; if (value != null) { int startAt = 0; for (; ; ) { m = new Regex(@"%(\w+)%").Match(value, startAt); if (!m.Success) break; string varName = m.Groups[1].Value; string varValue; if (startInfo.EnvironmentVariables.ContainsKey(varName)) varValue = startInfo.EnvironmentVariables[varName]; else { varValue = Environment.GetEnvironmentVariable(varName); if (varValue == null) varValue = ""; } // replace this instance of the variable with its definition. int varStart = m.Groups[1].Index - 1; // -1 becasue % chars are not in the group int varEnd = varStart + m.Groups[1].Length + 2; // +2 because % chars are not in the group value = value.Substring(0, varStart) + varValue + value.Substring(varEnd, value.Length - varEnd); startAt = varStart + varValue.Length; } } startInfo.EnvironmentVariables[key] = value; } } startInfo.WorkingDirectory = options.currentDirectory; outputStream = options.outputStream; if (options.outputFile != null) { outputStream = File.CreateText(options.outputFile); } #if false if (options.showCommand && outputStream != null) { // TODO why only for output streams? outputStream.WriteLine("RUN CMD: " + commandLine); } #endif try { process.Start(); } catch (Exception e) { string msg = "Failure starting Process\r\n" + " Exception: " + e.Message + "\r\n" + " Cmd: " + commandLine + "\r\n"; if (Regex.IsMatch(startInfo.FileName, @"^(copy|dir|del|color|set|cd|cdir|md|mkdir|prompt|pushd|popd|start|assoc|ftype)", RegexOptions.IgnoreCase)) msg += " Cmd " + startInfo.FileName + " implemented by Cmd.exe, fix by prefixing with 'cmd /c'."; throw new Exception(msg, e); } if (!startInfo.UseShellExecute) { // startInfo asyncronously collecting output process.BeginOutputReadLine(); process.BeginErrorReadLine(); } // Send any input to the command if (options.input != null) { process.StandardInput.Write(options.input); process.StandardInput.Close(); } } /// <summary> /// Create a subprocess to run 'commandLine' with no special options. /// <param variable="commandLine">The command lineNumber to run as a subprocess</param> /// </summary> public Command(string commandLine) : this(commandLine, new CommandOptions()) { } /// <summary> /// Wait for a started process to complete (HasExited will be true on return) /// </summary> /// <returns>Wait returns that 'this' pointer.</returns> public Command Wait() { // shell execute processes you don't wait for if (process.StartInfo.UseShellExecute) return this; process.WaitForExit(options.timeoutMSec); // TODO : HACK we see to have a race in the async process stuff // If you do Run("cmd /c set") you get truncated output at the // Looks like the problem in the framework. for (int i = 0; i < 10; i++) System.Threading.Thread.Sleep(1); if (!process.HasExited) { Kill(); throw new Exception("Timeout of " + (options.timeoutMSec / 1000) + " sec exceeded\r\n Cmd: " + commandLine); } // If we created the output stream, we should close it. if (outputStream != null && options.outputFile != null) outputStream.Close(); outputStream = null; if (process.ExitCode != 0 && !options.noThrow) ThrowCommandFailure(null); return this; } /// <summary> /// Throw a error if the command exited with a non-zero exit code /// printing useful diagnostic information along with the thrown message. /// This is useful when NoThrow is specified, and after post-processing /// you determine that the command really did fail, and an normal /// Command.Run failure was the appropriate action. /// </summary> /// <param name="message">An additional message to print in the throw (can be null)</param> public void ThrowCommandFailure(string message) { if (process.ExitCode != 0) { string outSpec = ""; if (outputStream == null) { string outStr = output.ToString(); // Only show the first lineNumber the last two lines if there are alot of output. Match m = Regex.Match(outStr, @"^(\s*\n)?(.+\n)(.|\n)*?(.+\n.*\S)\s*$"); if (m.Success) outStr = m.Groups[2].Value + " <<< Omitted output ... >>>\r\n" + m.Groups[4].Value; else outStr = outStr.Trim(); // Indent the output outStr = outStr.Replace("\n", "\n "); outSpec = "\r\n Output: {\r\n " + outStr + "\r\n }"; } if (message == null) message = ""; else if (message.Length > 0) message += "\r\n"; throw new Exception(message + "Process returned exit code 0x" + process.ExitCode.ToString("x") + "\r\n" + " Cmd: " + commandLine + outSpec); } } /// <summary> /// Get the underlying process object. Generally not used. /// </summary> public System.Diagnostics.Process Process { get { return process; } } /// <summary> /// Kill the process (and any child processses (recursively) associated with the /// running command). Note that it may not be able to kill everything it should /// if the child-parent' chain is broken by a child that creates a subprocess and /// then dies itself. This is reasonably uncommon, however. /// </summary> public void Kill(bool quiet) { // We use taskkill because it is built into windows, and knows // how to kill all subchildren of a process, which important. // TODO (should we use WMI instead?) if (!quiet) Console.WriteLine("Killing process tree " + Id + " Cmd: " + commandLine); try { Command.Run("taskkill /f /t /pid " + process.Id); } catch (Exception e) { Console.WriteLine(e.Message); } int ticks = 0; do { System.Threading.Thread.Sleep(10); ticks++; if (ticks > 100) { Console.WriteLine("ERROR: process is not dead 1 sec after killing " + process.Id); Console.WriteLine("Cmd: " + commandLine); } } while (!process.HasExited); // If we created the output stream, we should close it. if (outputStream != null && options.outputFile != null) outputStream.Close(); outputStream = null; } /// <summary> /// Kill the process (and any child processses (recursively) associated with the /// running command). Note that it may not be able to kill everything it should /// if the child-parent' chain is broken by a child that creates a subprocess and /// then dies itself. This is reasonably uncommon, however. /// </summary> public void Kill() { Kill(false); } /* called data comes to either StdErr or Stdout */ private void OnProcessOutput(object sender, DataReceivedEventArgs e) { if (outputStream != null) outputStream.WriteLine(e.Data); else output.AppendLine(e.Data); } /* private state */ private string commandLine; private Process process; private StringBuilder output; private CommandOptions options; private TextWriter outputStream; }
// // 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. // namespace NLog.Layouts { using Config; using System.Collections.Generic; using System.Text; /// <summary> /// A specialized layout that renders JSON-formatted events. /// </summary> [Layout("JsonLayout")] [ThreadAgnostic] [AppDomainFixedOutput] public class JsonLayout : Layout { /// <summary> /// Initializes a new instance of the <see cref="JsonLayout"/> class. /// </summary> public JsonLayout() { this.Attributes = new List<JsonAttribute>(); this.RenderEmptyObject = true; this.IncludeAllProperties = false; this.ExcludeProperties = new HashSet<string>(); } /// <summary> /// Gets the array of attributes' configurations. /// </summary> /// <docgen category='CSV Options' order='10' /> [ArrayParameter(typeof(JsonAttribute), "attribute")] public IList<JsonAttribute> Attributes { get; private set; } /// <summary> /// Gets or sets the option to suppress the extra spaces in the output json /// </summary> public bool SuppressSpaces { get; set; } /// <summary> /// Gets or sets the option to render the empty object value {} /// </summary> public bool RenderEmptyObject { get; set; } /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> public bool IncludeAllProperties { get; set; } /// <summary> /// List of property names to exclude when <see cref="IncludeAllProperties"/> is true /// </summary> #if NET3_5 public HashSet<string> ExcludeProperties { get; set; } #else public ISet<string> ExcludeProperties { get; set; } #endif /// <summary> /// Formats the log event as a JSON document for writing. /// </summary> /// <param name="logEvent">The log event to be formatted.</param> /// <returns>A JSON string representation of the log event.</returns> protected override string GetFormattedMessage(LogEventInfo logEvent) { StringBuilder sb = null; //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.Attributes.Count; i++) { var attrib = this.Attributes[i]; string text = attrib.LayoutWrapper.Render(logEvent); if (!string.IsNullOrEmpty(text)) { bool first = sb == null; if (first) { sb = new StringBuilder(attrib.Name.Length + text.Length + 10); sb.Append(SuppressSpaces ? "{" : "{ "); } AppendJsonAttributeValue(attrib, text, sb, first); } } if (this.IncludeAllProperties && logEvent.HasProperties) { JsonAttribute dynAttrib = null; foreach (var prop in logEvent.Properties) { //Determine property name string propName = prop.Key.ToString(); //Skips properties in the ExcludeProperties list if (this.ExcludeProperties.Contains(propName)) continue; if (dynAttrib == null) dynAttrib = new JsonAttribute(); if (prop.Value == null) { dynAttrib.Name = propName; dynAttrib.Encode = false; // Don't put quotes around null values; dynAttrib.Layout = "null"; } else { System.Type objType = prop.Value.GetType(); System.TypeCode objTypeCode = System.Type.GetTypeCode(objType); if (objTypeCode == System.TypeCode.Boolean || IsNumeric(objType, objTypeCode)) { dynAttrib.Name = propName; dynAttrib.Encode = false; //Don't put quotes around numbers or boolean values dynAttrib.Layout = string.Concat("${event-properties:item=", propName, "}"); } else { dynAttrib.Name = propName; dynAttrib.Encode = true; dynAttrib.Layout = string.Concat("${event-properties:item=", propName, "}"); } } string text = dynAttrib.LayoutWrapper.Render(logEvent); if (!string.IsNullOrEmpty(text)) { bool first = sb == null; if (first) { sb = new StringBuilder(dynAttrib.Name.Length + text.Length + 10); sb.Append(SuppressSpaces ? "{" : "{ "); } AppendJsonAttributeValue(dynAttrib, text, sb, first); } } } if (sb == null) { if (!RenderEmptyObject) return string.Empty; else return SuppressSpaces ? "{}" : "{ }"; } sb.Append(SuppressSpaces ? "}" : " }"); return sb.ToString(); } private void AppendJsonAttributeValue(JsonAttribute attrib, string text, StringBuilder sb, bool first) { if (!first) { sb.EnsureCapacity(sb.Length + attrib.Name.Length + text.Length + 12); sb.Append(','); if (!this.SuppressSpaces) sb.Append(' '); } sb.Append('"'); sb.Append(attrib.Name); sb.Append('"'); sb.Append(':'); if (!this.SuppressSpaces) sb.Append(' '); if (attrib.Encode) { // "\"{0}\":{1}\"{2}\"" sb.Append('"'); sb.Append(text); sb.Append('"'); } else { //If encoding is disabled for current attribute, do not escape the value of the attribute. //This enables user to write arbitrary string value (including JSON). // "\"{0}\":{1}{2}"; sb.Append(text); } } private bool IsNumeric(System.Type objType, System.TypeCode typeCode) { if (objType.IsPrimitive && typeCode != System.TypeCode.Object) { return typeCode != System.TypeCode.Char && typeCode != System.TypeCode.Boolean; } else if (typeCode == System.TypeCode.Decimal) { return true; } return false; } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.IO; using System.Linq; using NLog.Config; using NLog.Layouts; using NLog.Targets; using Xunit; namespace NLog.UnitTests.LayoutRenderers { public class VariableLayoutRendererTests : NLogTestBase { [Fact] public void Var_from_xml() { // Arrange var logFactory = CreateConfigFromXml(); var logger = logFactory.GetLogger("A"); // Act logger.Debug("msg"); // Assert logFactory.AssertDebugLastMessage("msg and admin=realgoodpassword"); Assert.Equal(2, logFactory.Configuration.Variables.Count); Assert.Equal(2, logFactory.Configuration.Variables.Keys.Count); Assert.Equal(2, logFactory.Configuration.Variables.Values.Count); Assert.True(logFactory.Configuration.Variables.ContainsKey("uSeR")); Assert.True(logFactory.Configuration.Variables.TryGetValue("passWORD", out var _)); } [Fact] public void Var_from_xml_and_edit() { // Arrange var logFactory = CreateConfigFromXml(); var logger = logFactory.GetLogger("A"); // Act logFactory.Configuration.Variables["password"] = "123"; logger.Debug("msg"); // Assert logFactory.AssertDebugLastMessage("msg and admin=123"); } [Fact] public void Var_from_xml_and_clear() { // Arrange var logFactory = CreateConfigFromXml(); var logger = logFactory.GetLogger("A"); // Act logFactory.Configuration.Variables.Clear(); logger.Debug("msg"); // Assert logFactory.AssertDebugLastMessage("msg and ="); } [Fact] public void Var_with_layout_renderers() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <variable name='user' value='logger=${logger}' /> <variable name='password' value='realgoodpassword' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; logFactory.Configuration.Variables["password"] = "123"; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug", logFactory); Assert.Equal("msg and logger=A=123", lastMessage); } [Theory] [InlineData("myJson", "${MyJson}")] [InlineData("myJson", "${var:myJSON}")] public void Var_with_layout(string variableName, string layoutStyle) { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml($@" <nlog throwExceptions='true'> <variable name='{variableName}' > <layout type='JsonLayout'> <attribute name='short date' layout='${{level}}' /> <attribute name='message' layout='${{message}}' /> </layout> </variable> <targets> <target name='debug' type='Debug' layout='{layoutStyle}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug", logFactory); Assert.Equal("{ \"short date\": \"Debug\", \"message\": \"msg\" }", lastMessage); } [Fact] public void Var_Layout_Target_CallSite() { var logFactory = new LogFactory().Setup() .LoadConfigurationFromXml(@"<nlog throwExceptions='true'> <variable name='myvar' value='${callsite}' /> <targets> <target name='debug' type='Debug' layout='${var:myvar}' /> </targets> <rules> <logger name='*' minLevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; // Act logFactory.GetCurrentClassLogger().Info("Hello"); // Assert logFactory.AssertDebugLastMessage(GetType().ToString() + "." + nameof(Var_Layout_Target_CallSite)); } [Fact] public void Var_with_other_var() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <variable name='user' value='${var:password}=' /> <variable name='password' value='realgoodpassword' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; logFactory.Configuration.Variables["password"] = "123"; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); logFactory.AssertDebugLastMessage("msg and 123==123"); } [Fact] public void Var_from_api() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; logFactory.Configuration.Variables["user"] = "admin"; logFactory.Configuration.Variables["password"] = "123"; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); logFactory.AssertDebugLastMessage("msg and admin=123"); } [Fact] public void Var_default() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <variable name='user' value='admin' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password:default=unknown}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); logFactory.AssertDebugLastMessage("msg and admin=unknown"); } [Fact] public void Var_default_after_clear() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <variable name='user' value='admin' /> <variable name='password' value='realgoodpassword' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password:default=unknown}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logFactory.Configuration.Variables.Remove("password"); logger.Debug("msg"); logFactory.AssertDebugLastMessage("msg and admin=unknown"); } [Fact] public void Var_default_after_set_null() { // Arrange var logFactory = CreateConfigFromXml(); var logger = logFactory.GetLogger("A"); // Act logFactory.Configuration.Variables["password"] = null; logger.Debug("msg"); // Assert logFactory.AssertDebugLastMessage("msg and admin="); } [Fact] public void Var_default_after_set_emptyString() { // Arrange var logFactory = CreateConfigFromXml(); var logger = logFactory.GetLogger("A"); // Act logFactory.Configuration.Variables["password"] = ""; logger.Debug("msg"); // Assert logFactory.AssertDebugLastMessage("msg and admin="); } [Fact] public void Var_default_after_xml_emptyString() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <variable name='user' value='admin' /> <variable name='password' value='' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); logFactory.AssertDebugLastMessage("msg and admin="); } [Fact] public void null_should_be_ok() { Layout l = "${var:var1}"; var config = new LoggingConfiguration(); config.Variables["var1"] = null; l.Initialize(config); var result = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("", result); } [Fact] public void null_should_not_use_default() { Layout l = "${var:var1:default=x}"; var config = new LoggingConfiguration(); config.Variables["var1"] = null; l.Initialize(config); var result = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("", result); } [Fact] public void notset_should_use_default() { Layout l = "${var:var1:default=x}"; var config = new LoggingConfiguration(); l.Initialize(config); var result = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("x", result); } [Fact] public void test_with_mockLogManager() { var logFactory = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(new DebugTarget { Name = "Debug", Layout = "${message}|${var:var1:default=x}" }); builder.Configuration.Variables["var1"] = "my-mocking-manager"; }).LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); logFactory.AssertDebugLastMessage("msg|my-mocking-manager"); } private LogFactory CreateConfigFromXml() { return new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <variable name='user' value='admin' /> <variable name='password' value='realgoodpassword' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Controls.dll // Description: The Windows Forms user interface controls like the map, legend, toolbox, ribbon and others. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/25/2008 2:46:23 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using DotSpatial.Data; using DotSpatial.Symbology; namespace DotSpatial.Controls { /// <summary> /// This is a specialized layer that specifically handles image drawing. /// </summary> public class MapImageLayer : ImageLayer, IMapImageLayer { #region Events /// <summary> /// Fires an event that indicates to the parent map-frame that it should first /// redraw the specified clip. /// </summary> public event EventHandler<ClipArgs> BufferChanged; #endregion #region Private Variables private Color _transparent; #endregion #region Constructors /// <summary> /// Creates a new default instance of a MapImageLayer /// </summary> public MapImageLayer() { } /// <summary> /// Creates a new instance of MapImageLayer. /// </summary> public MapImageLayer(IImageData baseImage) : base(baseImage) { } /// <summary> /// Creates a new instance of a MapImageLayer. /// </summary> /// <param name="baseImage">The image to draw as a layer</param> /// <param name="container">The Layers collection that keeps track of the image layer</param> public MapImageLayer(IImageData baseImage, ICollection<ILayer> container) : base(baseImage, container) { } /// <summary> /// Creates a new instance of a MapImageLayer. /// </summary> /// <param name="baseImage">The image to draw as a layer</param> /// <param name="transparent">The color to make transparent when drawing the image.</param> public MapImageLayer(IImageData baseImage, Color transparent) : base(baseImage) { this._transparent = transparent; } #endregion #region Methods /// <summary> /// This updates the things that depend on the DataSet so that they fit to the changed DataSet. /// </summary> /// <param name="value">DataSet that was changed.</param> protected override void OnDataSetChanged(IImageData value) { base.OnDataSetChanged(value); BufferRectangle = value == null ? Rectangle.Empty : new Rectangle(0, 0, value.Width, value.Height); BufferExtent = value == null ? null : value.Bounds.Extent; MyExtent = value == null ? null : value.Extent; OnFinishedLoading(); } /// <summary> /// This will draw any features that intersect this region. To specify the features directly, use OnDrawFeatures. /// This will not clear existing buffer content. For that call Initialize instead. /// </summary> /// <param name="args">A GeoArgs clarifying the transformation from geographic to image space</param> /// <param name="regions">The geographic regions to draw</param> public void DrawRegions(MapArgs args, List<Extent> regions) { List<Rectangle> clipRects = args.ProjToPixel(regions); for (int i = clipRects.Count - 1; i >= 0; i--) { if (clipRects[i].Width != 0 && clipRects[i].Height != 0) continue; regions.RemoveAt(i); clipRects.RemoveAt(i); } DrawWindows(args, regions, clipRects); } #endregion #region Properties /// <summary> /// Gets or sets the back buffer that will be drawn to as part of the initialization process. /// </summary> public Image BackBuffer { get; set; } /// <summary> /// Gets the current buffer. /// </summary> public Image Buffer { get; set; } /// <summary> /// Gets or sets the geographic region represented by the buffer /// Calling Initialize will set this automatically. /// </summary> public Extent BufferExtent { get; set; } /// <summary> /// Gets or sets the rectangle in pixels to use as the back buffer. /// Calling Initialize will set this automatically. /// </summary> public Rectangle BufferRectangle { get; set; } /// <summary> /// Gets or sets whether the image layer is initialized /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new bool IsInitialized { get; set; } #endregion #region Protected Methods /// <summary> /// Fires the OnBufferChanged event. /// </summary> /// <param name="clipRectangles">The Rectangle in pixels</param> protected virtual void OnBufferChanged(List<Rectangle> clipRectangles) { if (BufferChanged != null) { BufferChanged(this, new ClipArgs(clipRectangles)); } } #endregion #region Private Methods /// <summary> /// This draws to the back buffer. If the Backbuffer doesn't exist, this will create one. /// This will not flip the back buffer to the front. /// </summary> /// <param name="args"></param> /// <param name="regions"></param> /// <param name="clipRectangles"></param> private void DrawWindows(MapArgs args, IList<Extent> regions, IList<Rectangle> clipRectangles) { Graphics g; if (args.Device != null) { g = args.Device; // A device on the MapArgs is optional, but overrides the normal buffering behaviors. } else { if (BackBuffer == null) BackBuffer = new Bitmap(BufferRectangle.Width, BufferRectangle.Height); g = Graphics.FromImage(BackBuffer); } int numBounds = Math.Min(regions.Count, clipRectangles.Count); for (int i = 0; i < numBounds; i++) { // For panning tiles, the region needs to be expanded. // This is not always 1 pixel. When very zoomed in, this could be many pixels, // but should correspond to 1 pixel in the source image. int dx = (int)Math.Ceiling(DataSet.Bounds.AffineCoefficients[1] * clipRectangles[i].Width / regions[i].Width); int dy = (int)Math.Ceiling(-DataSet.Bounds.AffineCoefficients[5] * clipRectangles[i].Height / regions[i].Height); Rectangle r = clipRectangles[i].ExpandBy(dx * 2, dy * 2); if (r.X < 0) r.X = 0; if (r.Y < 0) r.Y = 0; if (r.Width > 2 * clipRectangles[i].Width) r.Width = 2 * clipRectangles[i].Width; if (r.Height > 2 * clipRectangles[i].Height) r.Height = 2 * clipRectangles[i].Height; Extent env = regions[i].Reproportion(clipRectangles[i], r); Bitmap bmp = null; try { bmp = DataSet.GetBitmap(env, r); if (!_transparent.Name.Equals("0")) { bmp.MakeTransparent(_transparent); } } catch { if (bmp != null) bmp.Dispose(); continue; } if (bmp == null) continue; if (this.Symbolizer != null && this.Symbolizer.Opacity < 1) { ColorMatrix matrix = new ColorMatrix(); //draws the image not completely opaque matrix.Matrix33 = Symbolizer.Opacity; using (var attributes = new ImageAttributes()) { attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); g.DrawImage(bmp, r, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, attributes); } } else { g.DrawImage(bmp, r); } bmp.Dispose(); } if (args.Device == null) g.Dispose(); } #endregion } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Runtime.InteropServices; namespace OpenTK { /// <summary> /// Represents a 3x3 matrix containing 3D rotation and scale. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Matrix3 : IEquatable<Matrix3> { #region Fields /// <summary> /// First row of the matrix. /// </summary> public Vector3 Row0; /// <summary> /// Second row of the matrix. /// </summary> public Vector3 Row1; /// <summary> /// Third row of the matrix. /// </summary> public Vector3 Row2; /// <summary> /// The identity matrix. /// </summary> public static readonly Matrix3 Identity = new Matrix3(Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ); /// <summary> /// The zero matrix. /// </summary> public static readonly Matrix3 Zero = new Matrix3(Vector3.Zero, Vector3.Zero, Vector3.Zero); #endregion #region Constructors /// <summary> /// Constructs a new instance. /// </summary> /// <param name="row0">Top row of the matrix</param> /// <param name="row1">Second row of the matrix</param> /// <param name="row2">Bottom row of the matrix</param> public Matrix3(Vector3 row0, Vector3 row1, Vector3 row2) { Row0 = row0; Row1 = row1; Row2 = row2; } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="m00">First item of the first row of the matrix.</param> /// <param name="m01">Second item of the first row of the matrix.</param> /// <param name="m02">Third item of the first row of the matrix.</param> /// <param name="m10">First item of the second row of the matrix.</param> /// <param name="m11">Second item of the second row of the matrix.</param> /// <param name="m12">Third item of the second row of the matrix.</param> /// <param name="m20">First item of the third row of the matrix.</param> /// <param name="m21">Second item of the third row of the matrix.</param> /// <param name="m22">Third item of the third row of the matrix.</param> public Matrix3( float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22) { Row0 = new Vector3(m00, m01, m02); Row1 = new Vector3(m10, m11, m12); Row2 = new Vector3(m20, m21, m22); } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="matrix">A Matrix4 to take the upper-left 3x3 from.</param> public Matrix3(Matrix4 matrix) { Row0 = matrix.Row0.Xyz; Row1 = matrix.Row1.Xyz; Row2 = matrix.Row2.Xyz; } #endregion #region Public Members #region Properties /// <summary> /// Gets the determinant of this matrix. /// </summary> public float Determinant { get { float m11 = Row0.X, m12 = Row0.Y, m13 = Row0.Z, m21 = Row1.X, m22 = Row1.Y, m23 = Row1.Z, m31 = Row2.X, m32 = Row2.Y, m33 = Row2.Z; return m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32 - m13 * m22 * m31 - m11 * m23 * m32 - m12 * m21 * m33; } } /// <summary> /// Gets the first column of this matrix. /// </summary> public Vector3 Column0 { get { return new Vector3(Row0.X, Row1.X, Row2.X); } } /// <summary> /// Gets the second column of this matrix. /// </summary> public Vector3 Column1 { get { return new Vector3(Row0.Y, Row1.Y, Row2.Y); } } /// <summary> /// Gets the third column of this matrix. /// </summary> public Vector3 Column2 { get { return new Vector3(Row0.Z, Row1.Z, Row2.Z); } } /// <summary> /// Gets or sets the value at row 1, column 1 of this instance. /// </summary> public float M11 { get { return Row0.X; } set { Row0.X = value; } } /// <summary> /// Gets or sets the value at row 1, column 2 of this instance. /// </summary> public float M12 { get { return Row0.Y; } set { Row0.Y = value; } } /// <summary> /// Gets or sets the value at row 1, column 3 of this instance. /// </summary> public float M13 { get { return Row0.Z; } set { Row0.Z = value; } } /// <summary> /// Gets or sets the value at row 2, column 1 of this instance. /// </summary> public float M21 { get { return Row1.X; } set { Row1.X = value; } } /// <summary> /// Gets or sets the value at row 2, column 2 of this instance. /// </summary> public float M22 { get { return Row1.Y; } set { Row1.Y = value; } } /// <summary> /// Gets or sets the value at row 2, column 3 of this instance. /// </summary> public float M23 { get { return Row1.Z; } set { Row1.Z = value; } } /// <summary> /// Gets or sets the value at row 3, column 1 of this instance. /// </summary> public float M31 { get { return Row2.X; } set { Row2.X = value; } } /// <summary> /// Gets or sets the value at row 3, column 2 of this instance. /// </summary> public float M32 { get { return Row2.Y; } set { Row2.Y = value; } } /// <summary> /// Gets or sets the value at row 3, column 3 of this instance. /// </summary> public float M33 { get { return Row2.Z; } set { Row2.Z = value; } } /// <summary> /// Gets or sets the values along the main diagonal of the matrix. /// </summary> public Vector3 Diagonal { get { return new Vector3(Row0.X, Row1.Y, Row2.Z); } set { Row0.X = value.X; Row1.Y = value.Y; Row2.Z = value.Z; } } /// <summary> /// Gets the trace of the matrix, the sum of the values along the diagonal. /// </summary> public float Trace { get { return Row0.X + Row1.Y + Row2.Z; } } #endregion #region Indexers /// <summary> /// Gets or sets the value at a specified row and column. /// </summary> public float this[int rowIndex, int columnIndex] { get { if (rowIndex == 0) return Row0[columnIndex]; else if (rowIndex == 1) return Row1[columnIndex]; else if (rowIndex == 2) return Row2[columnIndex]; throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")"); } set { if (rowIndex == 0) Row0[columnIndex] = value; else if (rowIndex == 1) Row1[columnIndex] = value; else if (rowIndex == 2) Row2[columnIndex] = value; else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")"); } } #endregion #region Instance #region public void Invert() /// <summary> /// Converts this instance into its inverse. /// </summary> public void Invert() { this = Matrix3.Invert(this); } #endregion #region public void Transpose() /// <summary> /// Converts this instance into its transpose. /// </summary> public void Transpose() { this = Matrix3.Transpose(this); } #endregion /// <summary> /// Returns a normalised copy of this instance. /// </summary> public Matrix3 Normalized() { Matrix3 m = this; m.Normalize(); return m; } /// <summary> /// Divides each element in the Matrix by the <see cref="Determinant"/>. /// </summary> public void Normalize() { var determinant = this.Determinant; Row0 /= determinant; Row1 /= determinant; Row2 /= determinant; } /// <summary> /// Returns an inverted copy of this instance. /// </summary> public Matrix3 Inverted() { Matrix3 m = this; if (m.Determinant != 0) m.Invert(); return m; } /// <summary> /// Returns a copy of this Matrix3 without scale. /// </summary> public Matrix3 ClearScale() { Matrix3 m = this; m.Row0 = m.Row0.Normalized(); m.Row1 = m.Row1.Normalized(); m.Row2 = m.Row2.Normalized(); return m; } /// <summary> /// Returns a copy of this Matrix3 without rotation. /// </summary> public Matrix3 ClearRotation() { Matrix3 m = this; m.Row0 = new Vector3(m.Row0.Length, 0, 0); m.Row1 = new Vector3(0, m.Row1.Length, 0); m.Row2 = new Vector3(0, 0, m.Row2.Length); return m; } /// <summary> /// Returns the scale component of this instance. /// </summary> public Vector3 ExtractScale() { return new Vector3(Row0.Length, Row1.Length, Row2.Length); } /// <summary> /// Returns the rotation component of this instance. Quite slow. /// </summary> /// <param name="row_normalise">Whether the method should row-normalise (i.e. remove scale from) the Matrix. Pass false if you know it's already normalised.</param> public Quaternion ExtractRotation(bool row_normalise = true) { var row0 = Row0; var row1 = Row1; var row2 = Row2; if (row_normalise) { row0 = row0.Normalized(); row1 = row1.Normalized(); row2 = row2.Normalized(); } // code below adapted from Blender Quaternion q = new Quaternion(); double trace = 0.25 * (row0[0] + row1[1] + row2[2] + 1.0); if (trace > 0) { double sq = Math.Sqrt(trace); q.W = (float)sq; sq = 1.0 / (4.0 * sq); q.X = (float)((row1[2] - row2[1]) * sq); q.Y = (float)((row2[0] - row0[2]) * sq); q.Z = (float)((row0[1] - row1[0]) * sq); } else if (row0[0] > row1[1] && row0[0] > row2[2]) { double sq = 2.0 * Math.Sqrt(1.0 + row0[0] - row1[1] - row2[2]); q.X = (float)(0.25 * sq); sq = 1.0 / sq; q.W = (float)((row2[1] - row1[2]) * sq); q.Y = (float)((row1[0] + row0[1]) * sq); q.Z = (float)((row2[0] + row0[2]) * sq); } else if (row1[1] > row2[2]) { double sq = 2.0 * Math.Sqrt(1.0 + row1[1] - row0[0] - row2[2]); q.Y = (float)(0.25 * sq); sq = 1.0 / sq; q.W = (float)((row2[0] - row0[2]) * sq); q.X = (float)((row1[0] + row0[1]) * sq); q.Z = (float)((row2[1] + row1[2]) * sq); } else { double sq = 2.0 * Math.Sqrt(1.0 + row2[2] - row0[0] - row1[1]); q.Z = (float)(0.25 * sq); sq = 1.0 / sq; q.W = (float)((row1[0] - row0[1]) * sq); q.X = (float)((row2[0] + row0[2]) * sq); q.Y = (float)((row2[1] + row1[2]) * sq); } q.Normalize(); return q; } #endregion #region Static #region CreateFromAxisAngle /// <summary> /// Build a rotation matrix from the specified axis/angle rotation. /// </summary> /// <param name="axis">The axis to rotate about.</param> /// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param> /// <param name="result">A matrix instance.</param> public static void CreateFromAxisAngle(Vector3 axis, float angle, out Matrix3 result) { //normalize and create a local copy of the vector. axis.Normalize(); float axisX = axis.X, axisY = axis.Y, axisZ = axis.Z; //calculate angles float cos = (float)System.Math.Cos(-angle); float sin = (float)System.Math.Sin(-angle); float t = 1.0f - cos; //do the conversion math once float tXX = t * axisX * axisX, tXY = t * axisX * axisY, tXZ = t * axisX * axisZ, tYY = t * axisY * axisY, tYZ = t * axisY * axisZ, tZZ = t * axisZ * axisZ; float sinX = sin * axisX, sinY = sin * axisY, sinZ = sin * axisZ; result.Row0.X = tXX + cos; result.Row0.Y = tXY - sinZ; result.Row0.Z = tXZ + sinY; result.Row1.X = tXY + sinZ; result.Row1.Y = tYY + cos; result.Row1.Z = tYZ - sinX; result.Row2.X = tXZ - sinY; result.Row2.Y = tYZ + sinX; result.Row2.Z = tZZ + cos; } /// <summary> /// Build a rotation matrix from the specified axis/angle rotation. /// </summary> /// <param name="axis">The axis to rotate about.</param> /// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param> /// <returns>A matrix instance.</returns> public static Matrix3 CreateFromAxisAngle(Vector3 axis, float angle) { Matrix3 result; CreateFromAxisAngle(axis, angle, out result); return result; } #endregion #region CreateFromQuaternion /// <summary> /// Build a rotation matrix from the specified quaternion. /// </summary> /// <param name="q">Quaternion to translate.</param> /// <param name="result">Matrix result.</param> public static void CreateFromQuaternion(ref Quaternion q, out Matrix3 result) { Vector3 axis; float angle; q.ToAxisAngle(out axis, out angle); CreateFromAxisAngle(axis, angle, out result); } /// <summary> /// Build a rotation matrix from the specified quaternion. /// </summary> /// <param name="q">Quaternion to translate.</param> /// <returns>A matrix instance.</returns> public static Matrix3 CreateFromQuaternion(Quaternion q) { Matrix3 result; CreateFromQuaternion(ref q, out result); return result; } #endregion #region CreateRotation[XYZ] /// <summary> /// Builds a rotation matrix for a rotation around the x-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3 instance.</param> public static void CreateRotationX(float angle, out Matrix3 result) { float cos = (float)System.Math.Cos(angle); float sin = (float)System.Math.Sin(angle); result = Identity; result.Row1.Y = cos; result.Row1.Z = sin; result.Row2.Y = -sin; result.Row2.Z = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the x-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3 instance.</returns> public static Matrix3 CreateRotationX(float angle) { Matrix3 result; CreateRotationX(angle, out result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the y-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3 instance.</param> public static void CreateRotationY(float angle, out Matrix3 result) { float cos = (float)System.Math.Cos(angle); float sin = (float)System.Math.Sin(angle); result = Identity; result.Row0.X = cos; result.Row0.Z = -sin; result.Row2.X = sin; result.Row2.Z = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the y-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3 instance.</returns> public static Matrix3 CreateRotationY(float angle) { Matrix3 result; CreateRotationY(angle, out result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the z-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3 instance.</param> public static void CreateRotationZ(float angle, out Matrix3 result) { float cos = (float)System.Math.Cos(angle); float sin = (float)System.Math.Sin(angle); result = Identity; result.Row0.X = cos; result.Row0.Y = sin; result.Row1.X = -sin; result.Row1.Y = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the z-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3 instance.</returns> public static Matrix3 CreateRotationZ(float angle) { Matrix3 result; CreateRotationZ(angle, out result); return result; } #endregion #region CreateScale /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Single scale factor for the x, y, and z axes.</param> /// <returns>A scale matrix.</returns> public static Matrix3 CreateScale(float scale) { Matrix3 result; CreateScale(scale, out result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Scale factors for the x, y, and z axes.</param> /// <returns>A scale matrix.</returns> public static Matrix3 CreateScale(Vector3 scale) { Matrix3 result; CreateScale(ref scale, out result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="x">Scale factor for the x axis.</param> /// <param name="y">Scale factor for the y axis.</param> /// <param name="z">Scale factor for the z axis.</param> /// <returns>A scale matrix.</returns> public static Matrix3 CreateScale(float x, float y, float z) { Matrix3 result; CreateScale(x, y, z, out result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Single scale factor for the x, y, and z axes.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(float scale, out Matrix3 result) { result = Identity; result.Row0.X = scale; result.Row1.Y = scale; result.Row2.Z = scale; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Scale factors for the x, y, and z axes.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(ref Vector3 scale, out Matrix3 result) { result = Identity; result.Row0.X = scale.X; result.Row1.Y = scale.Y; result.Row2.Z = scale.Z; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="x">Scale factor for the x axis.</param> /// <param name="y">Scale factor for the y axis.</param> /// <param name="z">Scale factor for the z axis.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(float x, float y, float z, out Matrix3 result) { result = Identity; result.Row0.X = x; result.Row1.Y = y; result.Row2.Z = z; } #endregion #region Multiply Functions /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <returns>A new instance that is the result of the multiplication</returns> public static Matrix3 Mult(Matrix3 left, Matrix3 right) { Matrix3 result; Mult(ref left, ref right, out result); return result; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <param name="result">A new instance that is the result of the multiplication</param> public static void Mult(ref Matrix3 left, ref Matrix3 right, out Matrix3 result) { float lM11 = left.Row0.X, lM12 = left.Row0.Y, lM13 = left.Row0.Z, lM21 = left.Row1.X, lM22 = left.Row1.Y, lM23 = left.Row1.Z, lM31 = left.Row2.X, lM32 = left.Row2.Y, lM33 = left.Row2.Z, rM11 = right.Row0.X, rM12 = right.Row0.Y, rM13 = right.Row0.Z, rM21 = right.Row1.X, rM22 = right.Row1.Y, rM23 = right.Row1.Z, rM31 = right.Row2.X, rM32 = right.Row2.Y, rM33 = right.Row2.Z; result.Row0.X = ((lM11 * rM11) + (lM12 * rM21)) + (lM13 * rM31); result.Row0.Y = ((lM11 * rM12) + (lM12 * rM22)) + (lM13 * rM32); result.Row0.Z = ((lM11 * rM13) + (lM12 * rM23)) + (lM13 * rM33); result.Row1.X = ((lM21 * rM11) + (lM22 * rM21)) + (lM23 * rM31); result.Row1.Y = ((lM21 * rM12) + (lM22 * rM22)) + (lM23 * rM32); result.Row1.Z = ((lM21 * rM13) + (lM22 * rM23)) + (lM23 * rM33); result.Row2.X = ((lM31 * rM11) + (lM32 * rM21)) + (lM33 * rM31); result.Row2.Y = ((lM31 * rM12) + (lM32 * rM22)) + (lM33 * rM32); result.Row2.Z = ((lM31 * rM13) + (lM32 * rM23)) + (lM33 * rM33); } #endregion #region Invert Functions /// <summary> /// Calculate the inverse of the given matrix /// </summary> /// <param name="mat">The matrix to invert</param> /// <param name="result">The inverse of the given matrix if it has one, or the input if it is singular</param> /// <exception cref="InvalidOperationException">Thrown if the Matrix3 is singular.</exception> public static void Invert(ref Matrix3 mat, out Matrix3 result) { int[] colIdx = { 0, 0, 0 }; int[] rowIdx = { 0, 0, 0 }; int[] pivotIdx = { -1, -1, -1 }; float[,] inverse = {{mat.Row0.X, mat.Row0.Y, mat.Row0.Z}, {mat.Row1.X, mat.Row1.Y, mat.Row1.Z}, {mat.Row2.X, mat.Row2.Y, mat.Row2.Z}}; int icol = 0; int irow = 0; for (int i = 0; i < 3; i++) { float maxPivot = 0.0f; for (int j = 0; j < 3; j++) { if (pivotIdx[j] != 0) { for (int k = 0; k < 3; ++k) { if (pivotIdx[k] == -1) { float absVal = System.Math.Abs(inverse[j, k]); if (absVal > maxPivot) { maxPivot = absVal; irow = j; icol = k; } } else if (pivotIdx[k] > 0) { result = mat; return; } } } } ++(pivotIdx[icol]); if (irow != icol) { for (int k = 0; k < 3; ++k) { float f = inverse[irow, k]; inverse[irow, k] = inverse[icol, k]; inverse[icol, k] = f; } } rowIdx[i] = irow; colIdx[i] = icol; float pivot = inverse[icol, icol]; if (pivot == 0.0f) { throw new InvalidOperationException("Matrix is singular and cannot be inverted."); } float oneOverPivot = 1.0f / pivot; inverse[icol, icol] = 1.0f; for (int k = 0; k < 3; ++k) inverse[icol, k] *= oneOverPivot; for (int j = 0; j < 3; ++j) { if (icol != j) { float f = inverse[j, icol]; inverse[j, icol] = 0.0f; for (int k = 0; k < 3; ++k) inverse[j, k] -= inverse[icol, k] * f; } } } for (int j = 2; j >= 0; --j) { int ir = rowIdx[j]; int ic = colIdx[j]; for (int k = 0; k < 3; ++k) { float f = inverse[k, ir]; inverse[k, ir] = inverse[k, ic]; inverse[k, ic] = f; } } result.Row0.X = inverse[0, 0]; result.Row0.Y = inverse[0, 1]; result.Row0.Z = inverse[0, 2]; result.Row1.X = inverse[1, 0]; result.Row1.Y = inverse[1, 1]; result.Row1.Z = inverse[1, 2]; result.Row2.X = inverse[2, 0]; result.Row2.Y = inverse[2, 1]; result.Row2.Z = inverse[2, 2]; } /// <summary> /// Calculate the inverse of the given matrix /// </summary> /// <param name="mat">The matrix to invert</param> /// <returns>The inverse of the given matrix if it has one, or the input if it is singular</returns> /// <exception cref="InvalidOperationException">Thrown if the Matrix4 is singular.</exception> public static Matrix3 Invert(Matrix3 mat) { Matrix3 result; Invert(ref mat, out result); return result; } #endregion #region Transpose /// <summary> /// Calculate the transpose of the given matrix /// </summary> /// <param name="mat">The matrix to transpose</param> /// <returns>The transpose of the given matrix</returns> public static Matrix3 Transpose(Matrix3 mat) { return new Matrix3(mat.Column0, mat.Column1, mat.Column2); } /// <summary> /// Calculate the transpose of the given matrix /// </summary> /// <param name="mat">The matrix to transpose</param> /// <param name="result">The result of the calculation</param> public static void Transpose(ref Matrix3 mat, out Matrix3 result) { result.Row0.X = mat.Row0.X; result.Row0.Y = mat.Row1.X; result.Row0.Z = mat.Row2.X; result.Row1.X = mat.Row0.Y; result.Row1.Y = mat.Row1.Y; result.Row1.Z = mat.Row2.Y; result.Row2.X = mat.Row0.Z; result.Row2.Y = mat.Row1.Z; result.Row2.Z = mat.Row2.Z; } #endregion #endregion #region Operators /// <summary> /// Matrix multiplication /// </summary> /// <param name="left">left-hand operand</param> /// <param name="right">right-hand operand</param> /// <returns>A new Matrix3d which holds the result of the multiplication</returns> public static Matrix3 operator *(Matrix3 left, Matrix3 right) { return Matrix3.Mult(left, right); } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> public static bool operator ==(Matrix3 left, Matrix3 right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equal right; false otherwise.</returns> public static bool operator !=(Matrix3 left, Matrix3 right) { return !left.Equals(right); } #endregion #region Overrides #region public override string ToString() /// <summary> /// Returns a System.String that represents the current Matrix3d. /// </summary> /// <returns>The string representation of the matrix.</returns> public override string ToString() { return String.Format("{0}\n{1}\n{2}", Row0, Row1, Row2); } #endregion #region public override int GetHashCode() /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return Row0.GetHashCode() ^ Row1.GetHashCode() ^ Row2.GetHashCode(); } #endregion #region public override bool Equals(object obj) /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Matrix3)) return false; return this.Equals((Matrix3)obj); } #endregion #endregion #endregion #region IEquatable<Matrix3> Members /// <summary>Indicates whether the current matrix is equal to another matrix.</summary> /// <param name="other">A matrix to compare with this matrix.</param> /// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns> public bool Equals(Matrix3 other) { return Row0 == other.Row0 && Row1 == other.Row1 && Row2 == other.Row2; } #endregion } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// The metrics associated with a physical network interface /// First published in XenServer 4.0. /// </summary> public partial class PIF_metrics : XenObject<PIF_metrics> { #region Constructors public PIF_metrics() { } public PIF_metrics(string uuid, double io_read_kbs, double io_write_kbs, bool carrier, string vendor_id, string vendor_name, string device_id, string device_name, long speed, bool duplex, string pci_bus_path, DateTime last_updated, Dictionary<string, string> other_config) { this.uuid = uuid; this.io_read_kbs = io_read_kbs; this.io_write_kbs = io_write_kbs; this.carrier = carrier; this.vendor_id = vendor_id; this.vendor_name = vendor_name; this.device_id = device_id; this.device_name = device_name; this.speed = speed; this.duplex = duplex; this.pci_bus_path = pci_bus_path; this.last_updated = last_updated; this.other_config = other_config; } /// <summary> /// Creates a new PIF_metrics from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public PIF_metrics(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new PIF_metrics from a Proxy_PIF_metrics. /// </summary> /// <param name="proxy"></param> public PIF_metrics(Proxy_PIF_metrics proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given PIF_metrics. /// </summary> public override void UpdateFrom(PIF_metrics update) { uuid = update.uuid; io_read_kbs = update.io_read_kbs; io_write_kbs = update.io_write_kbs; carrier = update.carrier; vendor_id = update.vendor_id; vendor_name = update.vendor_name; device_id = update.device_id; device_name = update.device_name; speed = update.speed; duplex = update.duplex; pci_bus_path = update.pci_bus_path; last_updated = update.last_updated; other_config = update.other_config; } internal void UpdateFrom(Proxy_PIF_metrics proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; io_read_kbs = Convert.ToDouble(proxy.io_read_kbs); io_write_kbs = Convert.ToDouble(proxy.io_write_kbs); carrier = (bool)proxy.carrier; vendor_id = proxy.vendor_id == null ? null : proxy.vendor_id; vendor_name = proxy.vendor_name == null ? null : proxy.vendor_name; device_id = proxy.device_id == null ? null : proxy.device_id; device_name = proxy.device_name == null ? null : proxy.device_name; speed = proxy.speed == null ? 0 : long.Parse(proxy.speed); duplex = (bool)proxy.duplex; pci_bus_path = proxy.pci_bus_path == null ? null : proxy.pci_bus_path; last_updated = proxy.last_updated; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_PIF_metrics ToProxy() { Proxy_PIF_metrics result_ = new Proxy_PIF_metrics(); result_.uuid = uuid ?? ""; result_.io_read_kbs = io_read_kbs; result_.io_write_kbs = io_write_kbs; result_.carrier = carrier; result_.vendor_id = vendor_id ?? ""; result_.vendor_name = vendor_name ?? ""; result_.device_id = device_id ?? ""; result_.device_name = device_name ?? ""; result_.speed = speed.ToString(); result_.duplex = duplex; result_.pci_bus_path = pci_bus_path ?? ""; result_.last_updated = last_updated; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this PIF_metrics /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("io_read_kbs")) io_read_kbs = Marshalling.ParseDouble(table, "io_read_kbs"); if (table.ContainsKey("io_write_kbs")) io_write_kbs = Marshalling.ParseDouble(table, "io_write_kbs"); if (table.ContainsKey("carrier")) carrier = Marshalling.ParseBool(table, "carrier"); if (table.ContainsKey("vendor_id")) vendor_id = Marshalling.ParseString(table, "vendor_id"); if (table.ContainsKey("vendor_name")) vendor_name = Marshalling.ParseString(table, "vendor_name"); if (table.ContainsKey("device_id")) device_id = Marshalling.ParseString(table, "device_id"); if (table.ContainsKey("device_name")) device_name = Marshalling.ParseString(table, "device_name"); if (table.ContainsKey("speed")) speed = Marshalling.ParseLong(table, "speed"); if (table.ContainsKey("duplex")) duplex = Marshalling.ParseBool(table, "duplex"); if (table.ContainsKey("pci_bus_path")) pci_bus_path = Marshalling.ParseString(table, "pci_bus_path"); if (table.ContainsKey("last_updated")) last_updated = Marshalling.ParseDateTime(table, "last_updated"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(PIF_metrics other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._io_read_kbs, other._io_read_kbs) && Helper.AreEqual2(this._io_write_kbs, other._io_write_kbs) && Helper.AreEqual2(this._carrier, other._carrier) && Helper.AreEqual2(this._vendor_id, other._vendor_id) && Helper.AreEqual2(this._vendor_name, other._vendor_name) && Helper.AreEqual2(this._device_id, other._device_id) && Helper.AreEqual2(this._device_name, other._device_name) && Helper.AreEqual2(this._speed, other._speed) && Helper.AreEqual2(this._duplex, other._duplex) && Helper.AreEqual2(this._pci_bus_path, other._pci_bus_path) && Helper.AreEqual2(this._last_updated, other._last_updated) && Helper.AreEqual2(this._other_config, other._other_config); } internal static List<PIF_metrics> ProxyArrayToObjectList(Proxy_PIF_metrics[] input) { var result = new List<PIF_metrics>(); foreach (var item in input) result.Add(new PIF_metrics(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, PIF_metrics server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { PIF_metrics.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static PIF_metrics get_record(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_record(session.opaque_ref, _pif_metrics); else return new PIF_metrics(session.proxy.pif_metrics_get_record(session.opaque_ref, _pif_metrics ?? "").parse()); } /// <summary> /// Get a reference to the PIF_metrics instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<PIF_metrics> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<PIF_metrics>.Create(session.proxy.pif_metrics_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static string get_uuid(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_uuid(session.opaque_ref, _pif_metrics); else return session.proxy.pif_metrics_get_uuid(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the io/read_kbs field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static double get_io_read_kbs(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_io_read_kbs(session.opaque_ref, _pif_metrics); else return Convert.ToDouble(session.proxy.pif_metrics_get_io_read_kbs(session.opaque_ref, _pif_metrics ?? "").parse()); } /// <summary> /// Get the io/write_kbs field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static double get_io_write_kbs(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_io_write_kbs(session.opaque_ref, _pif_metrics); else return Convert.ToDouble(session.proxy.pif_metrics_get_io_write_kbs(session.opaque_ref, _pif_metrics ?? "").parse()); } /// <summary> /// Get the carrier field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static bool get_carrier(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_carrier(session.opaque_ref, _pif_metrics); else return (bool)session.proxy.pif_metrics_get_carrier(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the vendor_id field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static string get_vendor_id(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_vendor_id(session.opaque_ref, _pif_metrics); else return session.proxy.pif_metrics_get_vendor_id(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the vendor_name field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static string get_vendor_name(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_vendor_name(session.opaque_ref, _pif_metrics); else return session.proxy.pif_metrics_get_vendor_name(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the device_id field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static string get_device_id(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_device_id(session.opaque_ref, _pif_metrics); else return session.proxy.pif_metrics_get_device_id(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the device_name field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static string get_device_name(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_device_name(session.opaque_ref, _pif_metrics); else return session.proxy.pif_metrics_get_device_name(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the speed field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static long get_speed(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_speed(session.opaque_ref, _pif_metrics); else return long.Parse(session.proxy.pif_metrics_get_speed(session.opaque_ref, _pif_metrics ?? "").parse()); } /// <summary> /// Get the duplex field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static bool get_duplex(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_duplex(session.opaque_ref, _pif_metrics); else return (bool)session.proxy.pif_metrics_get_duplex(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the pci_bus_path field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static string get_pci_bus_path(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_pci_bus_path(session.opaque_ref, _pif_metrics); else return session.proxy.pif_metrics_get_pci_bus_path(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the last_updated field of the given PIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static DateTime get_last_updated(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_last_updated(session.opaque_ref, _pif_metrics); else return session.proxy.pif_metrics_get_last_updated(session.opaque_ref, _pif_metrics ?? "").parse(); } /// <summary> /// Get the other_config field of the given PIF_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> public static Dictionary<string, string> get_other_config(Session session, string _pif_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_other_config(session.opaque_ref, _pif_metrics); else return Maps.convert_from_proxy_string_string(session.proxy.pif_metrics_get_other_config(session.opaque_ref, _pif_metrics ?? "").parse()); } /// <summary> /// Set the other_config field of the given PIF_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _pif_metrics, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.pif_metrics_set_other_config(session.opaque_ref, _pif_metrics, _other_config); else session.proxy.pif_metrics_set_other_config(session.opaque_ref, _pif_metrics ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given PIF_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _pif_metrics, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.pif_metrics_add_to_other_config(session.opaque_ref, _pif_metrics, _key, _value); else session.proxy.pif_metrics_add_to_other_config(session.opaque_ref, _pif_metrics ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given PIF_metrics. If the key is not in that Map, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pif_metrics">The opaque_ref of the given pif_metrics</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _pif_metrics, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.pif_metrics_remove_from_other_config(session.opaque_ref, _pif_metrics, _key); else session.proxy.pif_metrics_remove_from_other_config(session.opaque_ref, _pif_metrics ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the PIF_metrics instances known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<PIF_metrics>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_all(session.opaque_ref); else return XenRef<PIF_metrics>.Create(session.proxy.pif_metrics_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the PIF_metrics Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<PIF_metrics>, PIF_metrics> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pif_metrics_get_all_records(session.opaque_ref); else return XenRef<PIF_metrics>.Create<Proxy_PIF_metrics>(session.proxy.pif_metrics_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// Read bandwidth (KiB/s) /// </summary> public virtual double io_read_kbs { get { return _io_read_kbs; } set { if (!Helper.AreEqual(value, _io_read_kbs)) { _io_read_kbs = value; Changed = true; NotifyPropertyChanged("io_read_kbs"); } } } private double _io_read_kbs; /// <summary> /// Write bandwidth (KiB/s) /// </summary> public virtual double io_write_kbs { get { return _io_write_kbs; } set { if (!Helper.AreEqual(value, _io_write_kbs)) { _io_write_kbs = value; Changed = true; NotifyPropertyChanged("io_write_kbs"); } } } private double _io_write_kbs; /// <summary> /// Report if the PIF got a carrier or not /// </summary> public virtual bool carrier { get { return _carrier; } set { if (!Helper.AreEqual(value, _carrier)) { _carrier = value; Changed = true; NotifyPropertyChanged("carrier"); } } } private bool _carrier; /// <summary> /// Report vendor ID /// </summary> public virtual string vendor_id { get { return _vendor_id; } set { if (!Helper.AreEqual(value, _vendor_id)) { _vendor_id = value; Changed = true; NotifyPropertyChanged("vendor_id"); } } } private string _vendor_id = ""; /// <summary> /// Report vendor name /// </summary> public virtual string vendor_name { get { return _vendor_name; } set { if (!Helper.AreEqual(value, _vendor_name)) { _vendor_name = value; Changed = true; NotifyPropertyChanged("vendor_name"); } } } private string _vendor_name = ""; /// <summary> /// Report device ID /// </summary> public virtual string device_id { get { return _device_id; } set { if (!Helper.AreEqual(value, _device_id)) { _device_id = value; Changed = true; NotifyPropertyChanged("device_id"); } } } private string _device_id = ""; /// <summary> /// Report device name /// </summary> public virtual string device_name { get { return _device_name; } set { if (!Helper.AreEqual(value, _device_name)) { _device_name = value; Changed = true; NotifyPropertyChanged("device_name"); } } } private string _device_name = ""; /// <summary> /// Speed of the link (if available) /// </summary> public virtual long speed { get { return _speed; } set { if (!Helper.AreEqual(value, _speed)) { _speed = value; Changed = true; NotifyPropertyChanged("speed"); } } } private long _speed; /// <summary> /// Full duplex capability of the link (if available) /// </summary> public virtual bool duplex { get { return _duplex; } set { if (!Helper.AreEqual(value, _duplex)) { _duplex = value; Changed = true; NotifyPropertyChanged("duplex"); } } } private bool _duplex; /// <summary> /// PCI bus path of the pif (if available) /// </summary> public virtual string pci_bus_path { get { return _pci_bus_path; } set { if (!Helper.AreEqual(value, _pci_bus_path)) { _pci_bus_path = value; Changed = true; NotifyPropertyChanged("pci_bus_path"); } } } private string _pci_bus_path = ""; /// <summary> /// Time at which this information was last updated /// </summary> [JsonConverter(typeof(XenDateTimeConverter))] public virtual DateTime last_updated { get { return _last_updated; } set { if (!Helper.AreEqual(value, _last_updated)) { _last_updated = value; Changed = true; NotifyPropertyChanged("last_updated"); } } } private DateTime _last_updated; /// <summary> /// additional configuration /// First published in XenServer 5.0. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; } }
using MatterHackers.VectorMath; using NeuralNet; using System; using System.Collections.Generic; namespace SmartSweeper { internal class CMinesweeper { private double m_dMaxTurnRate; private int m_WindowWidth; private int m_WindowHeight; //the minesweeper's neural net private CNeuralNet m_ItsBrain; //its position in the world private Vector3 m_vPosition; //direction sweeper is facing private Vector3 m_vLookAt; //its rotation (surprise surprise) private double m_dRotation; private double m_dSpeed; //to store output from the ANN private double m_lTrack, m_rTrack; //the sweeper's fitness score private double m_dFitness; //the scale of the sweeper when drawn private double m_dScale; //index position of closest mine private int m_iClosestMine; public CMinesweeper(int WindowWidth, int WindowHeight, double SweeperScale, double dMaxTurnRate) { m_ItsBrain = new CNeuralNet(4, 2, 1, 6, -1, 1); //m_ItsBrain = new CNeuralNet(4, 2, 3, 8, -1, 1); Random Rand = new Random(); m_WindowWidth = WindowWidth; m_WindowHeight = WindowHeight; m_dMaxTurnRate = dMaxTurnRate; m_dRotation = (Rand.NextDouble() * (System.Math.PI * 2)); m_lTrack = (0.16); m_rTrack = (0.16); m_dFitness = (0); m_dScale = SweeperScale; m_iClosestMine = (0); //create a random start position m_vPosition = new Vector3((Rand.NextDouble() * WindowWidth), (Rand.NextDouble() * WindowHeight), 0); } //updates the ANN with information from the sweepers enviroment public bool Update(List<Vector3> mines) { //this will store all the inputs for the NN List<double> inputs = new List<double>(); //get List to closest mine Vector3 vClosestMine = GetClosestMine(mines); //normalise it vClosestMine.Normalize(); #if false // get the angle to the closest mine Vector3 DeltaToMine = vClosestMine - m_vPosition; Vector2D DeltaToMine2D = new Vector2D(DeltaToMine.x, DeltaToMine.y); Vector2D LookAt2D = new Vector2D(m_vLookAt.x, m_vLookAt.y); double DeltaAngle = LookAt2D.GetDeltaAngle(DeltaToMine2D); inputs.Add(DeltaAngle); inputs.Add(DeltaAngle); inputs.Add(DeltaAngle); inputs.Add(DeltaAngle); #else //add in List to closest mine inputs.Add(vClosestMine.x); inputs.Add(vClosestMine.y); //add in sweepers look at List inputs.Add(m_vLookAt.x); inputs.Add(m_vLookAt.y); #endif //update the brain and get feedback List<double> output = m_ItsBrain.Update(inputs); //make sure there were no errors in calculating the //output if (output.Count < m_ItsBrain.NumOutputs) { return false; } //assign the outputs to the sweepers left & right tracks m_lTrack = output[0]; m_rTrack = output[1]; //calculate steering forces double RotForce = m_lTrack - m_rTrack; //clamp rotation RotForce = System.Math.Min(System.Math.Max(RotForce, -m_dMaxTurnRate), m_dMaxTurnRate); m_dRotation += RotForce; m_dSpeed = (m_lTrack + m_rTrack); //update Look At m_vLookAt.x = (double)-System.Math.Sin(m_dRotation); m_vLookAt.y = (double)System.Math.Cos(m_dRotation); //update position m_vPosition += (m_vLookAt * m_dSpeed); //wrap around window limits if (m_vPosition.x > m_WindowWidth) m_vPosition.x = 0; if (m_vPosition.x < 0) m_vPosition.x = m_WindowWidth; if (m_vPosition.y > m_WindowHeight) m_vPosition.y = 0; if (m_vPosition.y < 0) m_vPosition.y = m_WindowHeight; return true; } //used to transform the sweepers vertices prior to rendering public void WorldTransform(List<Vector3> sweeper) { //create the world transformation matrix Matrix4X4 matTransform = Matrix4X4.Identity; //scale matTransform *= Matrix4X4.CreateScale(m_dScale, m_dScale, 1); //rotate matTransform *= Matrix4X4.CreateRotationZ(m_dRotation); //and translate matTransform *= Matrix4X4.CreateTranslation(m_vPosition.x, m_vPosition.y, 0); //now transform the ships vertices for (int i = 0; i < sweeper.Count; i++) { sweeper[i] = Vector3.Transform(sweeper[i], matTransform); } } //returns a List to the closest mine public Vector3 GetClosestMine(List<Vector3> mines) { double closest_so_far = 99999; Vector3 vClosestObject = new Vector3(0, 0, 0); //cycle through mines to find closest for (int i = 0; i < mines.Count; i++) { double len_to_object = (mines[i] - m_vPosition).Length; if (len_to_object < closest_so_far) { closest_so_far = len_to_object; vClosestObject = m_vPosition - mines[i]; m_iClosestMine = i; } } return vClosestObject; } //checks to see if the minesweeper has 'collected' a mine public int CheckForMine(List<Vector3> mines, double size) { Vector3 DistToObject = m_vPosition - mines[m_iClosestMine]; if (DistToObject.Length < (size + 5)) { return m_iClosestMine; } return -1; } public void Reset() { Random Rand = new Random(); //reset the sweepers positions m_vPosition = new Vector3((Rand.NextDouble() * m_WindowWidth), (Rand.NextDouble() * m_WindowHeight), 0); //and the fitness m_dFitness = 0; //and the rotation m_dRotation = Rand.NextDouble() * (System.Math.PI * 2); return; } //-------------------accessor functions public Vector3 Position() { return m_vPosition; } public void IncrementFitness() { ++m_dFitness; } public double Fitness() { return m_dFitness; } public void PutWeights(List<double> w) { m_ItsBrain.PutWeights(w); } public int GetNumberOfWeights() { return m_ItsBrain.GetNumberOfWeights(); } }; }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.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 OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// PipelineStepImpl /// </summary> [DataContract] public partial class PipelineStepImpl : IEquatable<PipelineStepImpl>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="PipelineStepImpl" /> class. /// </summary> /// <param name="_class">_class.</param> /// <param name="links">links.</param> /// <param name="displayName">displayName.</param> /// <param name="durationInMillis">durationInMillis.</param> /// <param name="id">id.</param> /// <param name="input">input.</param> /// <param name="result">result.</param> /// <param name="startTime">startTime.</param> /// <param name="state">state.</param> public PipelineStepImpl(string _class = default(string), PipelineStepImpllinks links = default(PipelineStepImpllinks), string displayName = default(string), int durationInMillis = default(int), string id = default(string), InputStepImpl input = default(InputStepImpl), string result = default(string), string startTime = default(string), string state = default(string)) { this.Class = _class; this.Links = links; this.DisplayName = displayName; this.DurationInMillis = durationInMillis; this.Id = id; this.Input = input; this.Result = result; this.StartTime = startTime; this.State = state; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name="_class", EmitDefaultValue=false)] public string Class { get; set; } /// <summary> /// Gets or Sets Links /// </summary> [DataMember(Name="_links", EmitDefaultValue=false)] public PipelineStepImpllinks Links { get; set; } /// <summary> /// Gets or Sets DisplayName /// </summary> [DataMember(Name="displayName", EmitDefaultValue=false)] public string DisplayName { get; set; } /// <summary> /// Gets or Sets DurationInMillis /// </summary> [DataMember(Name="durationInMillis", EmitDefaultValue=false)] public int DurationInMillis { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Gets or Sets Input /// </summary> [DataMember(Name="input", EmitDefaultValue=false)] public InputStepImpl Input { get; set; } /// <summary> /// Gets or Sets Result /// </summary> [DataMember(Name="result", EmitDefaultValue=false)] public string Result { get; set; } /// <summary> /// Gets or Sets StartTime /// </summary> [DataMember(Name="startTime", EmitDefaultValue=false)] public string StartTime { get; set; } /// <summary> /// Gets or Sets State /// </summary> [DataMember(Name="state", EmitDefaultValue=false)] public string State { 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 PipelineStepImpl {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" Links: ").Append(Links).Append("\n"); sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); sb.Append(" DurationInMillis: ").Append(DurationInMillis).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Input: ").Append(Input).Append("\n"); sb.Append(" Result: ").Append(Result).Append("\n"); sb.Append(" StartTime: ").Append(StartTime).Append("\n"); sb.Append(" State: ").Append(State).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as PipelineStepImpl); } /// <summary> /// Returns true if PipelineStepImpl instances are equal /// </summary> /// <param name="input">Instance of PipelineStepImpl to be compared</param> /// <returns>Boolean</returns> public bool Equals(PipelineStepImpl input) { if (input == null) return false; return ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ) && ( this.Links == input.Links || (this.Links != null && this.Links.Equals(input.Links)) ) && ( this.DisplayName == input.DisplayName || (this.DisplayName != null && this.DisplayName.Equals(input.DisplayName)) ) && ( this.DurationInMillis == input.DurationInMillis || (this.DurationInMillis != null && this.DurationInMillis.Equals(input.DurationInMillis)) ) && ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.Input == input.Input || (this.Input != null && this.Input.Equals(input.Input)) ) && ( this.Result == input.Result || (this.Result != null && this.Result.Equals(input.Result)) ) && ( this.StartTime == input.StartTime || (this.StartTime != null && this.StartTime.Equals(input.StartTime)) ) && ( this.State == input.State || (this.State != null && this.State.Equals(input.State)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Class != null) hashCode = hashCode * 59 + this.Class.GetHashCode(); if (this.Links != null) hashCode = hashCode * 59 + this.Links.GetHashCode(); if (this.DisplayName != null) hashCode = hashCode * 59 + this.DisplayName.GetHashCode(); if (this.DurationInMillis != null) hashCode = hashCode * 59 + this.DurationInMillis.GetHashCode(); if (this.Id != null) hashCode = hashCode * 59 + this.Id.GetHashCode(); if (this.Input != null) hashCode = hashCode * 59 + this.Input.GetHashCode(); if (this.Result != null) hashCode = hashCode * 59 + this.Result.GetHashCode(); if (this.StartTime != null) hashCode = hashCode * 59 + this.StartTime.GetHashCode(); if (this.State != null) hashCode = hashCode * 59 + this.State.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
// 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. // -------------------------------------------------------------------------------------- // // A class that provides a simple, lightweight implementation of lazy initialization, // obviating the need for a developer to implement a custom, thread-safe lazy initialization // solution. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #pragma warning disable 0420 using System.Diagnostics; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Threading; namespace System { internal enum LazyState { NoneViaConstructor = 0, NoneViaFactory = 1, NoneException = 2, PublicationOnlyViaConstructor = 3, PublicationOnlyViaFactory = 4, PublicationOnlyWait = 5, PublicationOnlyException = 6, ExecutionAndPublicationViaConstructor = 7, ExecutionAndPublicationViaFactory = 8, ExecutionAndPublicationException = 9, } /// <summary> /// LazyHelper serves multiples purposes /// - minimizing code size of Lazy&lt;T&gt; by implementing as much of the code that is not generic /// this reduces generic code bloat, making faster class initialization /// - contains singleton objects that are used to handle threading primitives for PublicationOnly mode /// - allows for instantiation for ExecutionAndPublication so as to create an object for locking on /// - holds exception information. /// </summary> internal class LazyHelper { internal readonly static LazyHelper NoneViaConstructor = new LazyHelper(LazyState.NoneViaConstructor); internal readonly static LazyHelper NoneViaFactory = new LazyHelper(LazyState.NoneViaFactory); internal readonly static LazyHelper PublicationOnlyViaConstructor = new LazyHelper(LazyState.PublicationOnlyViaConstructor); internal readonly static LazyHelper PublicationOnlyViaFactory = new LazyHelper(LazyState.PublicationOnlyViaFactory); internal readonly static LazyHelper PublicationOnlyWaitForOtherThreadToPublish = new LazyHelper(LazyState.PublicationOnlyWait); internal LazyState State { get; } private readonly ExceptionDispatchInfo _exceptionDispatch; /// <summary> /// Constructor that defines the state /// </summary> internal LazyHelper(LazyState state) { State = state; } /// <summary> /// Constructor used for exceptions /// </summary> internal LazyHelper(LazyThreadSafetyMode mode, Exception exception) { switch(mode) { case LazyThreadSafetyMode.ExecutionAndPublication: State = LazyState.ExecutionAndPublicationException; break; case LazyThreadSafetyMode.None: State = LazyState.NoneException; break; case LazyThreadSafetyMode.PublicationOnly: State = LazyState.PublicationOnlyException; break; default: Debug.Assert(false, "internal constructor, this should never occur"); break; } _exceptionDispatch = ExceptionDispatchInfo.Capture(exception); } internal void ThrowException() { Debug.Assert(_exceptionDispatch != null, "execution path is invalid"); _exceptionDispatch.Throw(); } private LazyThreadSafetyMode GetMode() { switch (State) { case LazyState.NoneViaConstructor: case LazyState.NoneViaFactory: case LazyState.NoneException: return LazyThreadSafetyMode.None; case LazyState.PublicationOnlyViaConstructor: case LazyState.PublicationOnlyViaFactory: case LazyState.PublicationOnlyWait: case LazyState.PublicationOnlyException: return LazyThreadSafetyMode.PublicationOnly; case LazyState.ExecutionAndPublicationViaConstructor: case LazyState.ExecutionAndPublicationViaFactory: case LazyState.ExecutionAndPublicationException: return LazyThreadSafetyMode.ExecutionAndPublication; default: Debug.Assert(false, "Invalid logic; State should always have a valid value"); return default(LazyThreadSafetyMode); } } internal static LazyThreadSafetyMode? GetMode(LazyHelper state) { if (state == null) return null; // we don't know the mode anymore return state.GetMode(); } internal static bool GetIsValueFaulted(LazyHelper state) => state?._exceptionDispatch != null; internal static LazyHelper Create(LazyThreadSafetyMode mode, bool useDefaultConstructor) { switch (mode) { case LazyThreadSafetyMode.None: return useDefaultConstructor ? NoneViaConstructor : NoneViaFactory; case LazyThreadSafetyMode.PublicationOnly: return useDefaultConstructor ? PublicationOnlyViaConstructor : PublicationOnlyViaFactory; case LazyThreadSafetyMode.ExecutionAndPublication: // we need to create an object for ExecutionAndPublication because we use Monitor-based locking var state = useDefaultConstructor ? LazyState.ExecutionAndPublicationViaConstructor : LazyState.ExecutionAndPublicationViaFactory; return new LazyHelper(state); default: throw new ArgumentOutOfRangeException(nameof(mode), SR.Lazy_ctor_ModeInvalid); } } internal static object CreateViaDefaultConstructor(Type type) { try { return Activator.CreateInstance(type); } catch (MissingMethodException) { throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT); } } internal static LazyThreadSafetyMode GetModeFromIsThreadSafe(bool isThreadSafe) { return isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None; } } /// <summary> /// Provides support for lazy initialization. /// </summary> /// <typeparam name="T">Specifies the type of element being lazily initialized.</typeparam> /// <remarks> /// <para> /// By default, all public and protected members of <see cref="Lazy{T}"/> are thread-safe and may be used /// concurrently from multiple threads. These thread-safety guarantees may be removed optionally and per instance /// using parameters to the type's constructors. /// </para> /// </remarks> [DebuggerTypeProxy(typeof(System_LazyDebugView<>))] [DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")] public class Lazy<T> { private static T CreateViaDefaultConstructor() { return (T)LazyHelper.CreateViaDefaultConstructor(typeof(T)); } // _state, a volatile reference, is set to null after m_value has been set [NonSerialized] private volatile LazyHelper _state; // we ensure that _factory when finished is set to null to allow garbage collector to clean up // any referenced items [NonSerialized] private Func<T> _factory; // _value eventually stores the lazily created value. It is valid when _state = null. private T m_value; // Do not rename (binary serialization) /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that /// uses <typeparamref name="T"/>'s default constructor for lazy initialization. /// </summary> /// <remarks> /// An instance created with this constructor may be used concurrently from multiple threads. /// </remarks> public Lazy() : this(null, LazyThreadSafetyMode.ExecutionAndPublication, useDefaultConstructor:true) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that /// uses a pre-initialized specified value. /// </summary> /// <remarks> /// An instance created with this constructor should be usable by multiple threads // concurrently. /// </remarks> public Lazy(T value) { m_value = value; } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that uses a /// specified initialization function. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is /// needed. /// </param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <remarks> /// An instance created with this constructor may be used concurrently from multiple threads. /// </remarks> public Lazy(Func<T> valueFactory) : this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication, useDefaultConstructor:false) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> /// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode. /// </summary> /// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time. /// </param> public Lazy(bool isThreadSafe) : this(null, LazyHelper.GetModeFromIsThreadSafe(isThreadSafe), useDefaultConstructor:true) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> /// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode. /// </summary> /// <param name="mode">The lazy thread-safety mode mode</param> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid valuee</exception> public Lazy(LazyThreadSafetyMode mode) : this(null, mode, useDefaultConstructor:true) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class /// that uses a specified initialization function and a specified thread-safety mode. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed. /// </param> /// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time. /// </param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is /// a null reference (Nothing in Visual Basic).</exception> public Lazy(Func<T> valueFactory, bool isThreadSafe) : this(valueFactory, LazyHelper.GetModeFromIsThreadSafe(isThreadSafe), useDefaultConstructor:false) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class /// that uses a specified initialization function and a specified thread-safety mode. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed. /// </param> /// <param name="mode">The lazy thread-safety mode.</param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is /// a null reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid value.</exception> public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode) : this(valueFactory, mode, useDefaultConstructor:false) { } private Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode, bool useDefaultConstructor) { if (valueFactory == null && !useDefaultConstructor) throw new ArgumentNullException(nameof(valueFactory)); _factory = valueFactory; _state = LazyHelper.Create(mode, useDefaultConstructor); } private void ViaConstructor() { m_value = CreateViaDefaultConstructor(); _state = null; // volatile write, must occur after setting _value } private void ViaFactory(LazyThreadSafetyMode mode) { try { Func<T> factory = _factory; if (factory == null) throw new InvalidOperationException(SR.Lazy_Value_RecursiveCallsToValue); _factory = null; m_value = factory(); _state = null; // volatile write, must occur after setting _value } catch (Exception exception) { _state = new LazyHelper(mode, exception); throw; } } private void ExecutionAndPublication(LazyHelper executionAndPublication, bool useDefaultConstructor) { lock (executionAndPublication) { // it's possible for multiple calls to have piled up behind the lock, so we need to check // to see if the ExecutionAndPublication object is still the current implementation. if (ReferenceEquals(_state, executionAndPublication)) { if (useDefaultConstructor) { ViaConstructor(); } else { ViaFactory(LazyThreadSafetyMode.ExecutionAndPublication); } } } } private void PublicationOnly(LazyHelper publicationOnly, T possibleValue) { LazyHelper previous = Interlocked.CompareExchange(ref _state, LazyHelper.PublicationOnlyWaitForOtherThreadToPublish, publicationOnly); if (previous == publicationOnly) { _factory = null; m_value = possibleValue; _state = null; // volatile write, must occur after setting _value } } private void PublicationOnlyViaConstructor(LazyHelper initializer) { PublicationOnly(initializer, CreateViaDefaultConstructor()); } private void PublicationOnlyViaFactory(LazyHelper initializer) { Func<T> factory = _factory; if (factory == null) { PublicationOnlyWaitForOtherThreadToPublish(); } else { PublicationOnly(initializer, factory()); } } private void PublicationOnlyWaitForOtherThreadToPublish() { var spinWait = new SpinWait(); while (!ReferenceEquals(_state, null)) { // We get here when PublicationOnly temporarily sets _state to LazyHelper.PublicationOnlyWaitForOtherThreadToPublish. // This temporary state should be quickly followed by _state being set to null. spinWait.SpinOnce(); } } private T CreateValue() { // we have to create a copy of state here, and use the copy exclusively from here on in // so as to ensure thread safety. var state = _state; if (state != null) { switch (state.State) { case LazyState.NoneViaConstructor: ViaConstructor(); break; case LazyState.NoneViaFactory: ViaFactory(LazyThreadSafetyMode.None); break; case LazyState.PublicationOnlyViaConstructor: PublicationOnlyViaConstructor(state); break; case LazyState.PublicationOnlyViaFactory: PublicationOnlyViaFactory(state); break; case LazyState.PublicationOnlyWait: PublicationOnlyWaitForOtherThreadToPublish(); break; case LazyState.ExecutionAndPublicationViaConstructor: ExecutionAndPublication(state, useDefaultConstructor:true); break; case LazyState.ExecutionAndPublicationViaFactory: ExecutionAndPublication(state, useDefaultConstructor:false); break; default: state.ThrowException(); break; } } return Value; } /// <summary>Forces initialization during serialization.</summary> /// <param name="context">The StreamingContext for the serialization operation.</param> [OnSerializing] private void OnSerializing(StreamingContext context) { // Force initialization T dummy = Value; } /// <summary>Creates and returns a string representation of this instance.</summary> /// <returns>The result of calling <see cref="System.Object.ToString"/> on the <see /// cref="Value"/>.</returns> /// <exception cref="T:System.NullReferenceException"> /// The <see cref="Value"/> is null. /// </exception> public override string ToString() { return IsValueCreated ? Value.ToString() : SR.Lazy_ToString_ValueNotCreated; } /// <summary>Gets the value of the Lazy&lt;T&gt; for debugging display purposes.</summary> internal T ValueForDebugDisplay { get { if (!IsValueCreated) { return default(T); } return m_value; } } /// <summary> /// Gets a value indicating whether this instance may be used concurrently from multiple threads. /// </summary> internal LazyThreadSafetyMode? Mode => LazyHelper.GetMode(_state); /// <summary> /// Gets whether the value creation is faulted or not /// </summary> internal bool IsValueFaulted => LazyHelper.GetIsValueFaulted(_state); /// <summary>Gets a value indicating whether the <see cref="T:System.Lazy{T}"/> has been initialized. /// </summary> /// <value>true if the <see cref="T:System.Lazy{T}"/> instance has been initialized; /// otherwise, false.</value> /// <remarks> /// The initialization of a <see cref="T:System.Lazy{T}"/> instance may result in either /// a value being produced or an exception being thrown. If an exception goes unhandled during initialization, /// <see cref="IsValueCreated"/> will return false. /// </remarks> public bool IsValueCreated => _state == null; /// <summary>Gets the lazily initialized value of the current <see /// cref="T:System.Threading.Lazy{T}"/>.</summary> /// <value>The lazily initialized value of the current <see /// cref="T:System.Threading.Lazy{T}"/>.</value> /// <exception cref="T:System.MissingMemberException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor /// of the type being lazily initialized, and that type does not have a public, parameterless constructor. /// </exception> /// <exception cref="T:System.MemberAccessException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor /// of the type being lazily initialized, and permissions to access the constructor were missing. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was constructed with the <see cref="T:System.Threading.LazyThreadSafetyMode.ExecutionAndPublication"/> or /// <see cref="T:System.Threading.LazyThreadSafetyMode.None"/> and the initialization function attempted to access <see cref="Value"/> on this instance. /// </exception> /// <remarks> /// If <see cref="IsValueCreated"/> is false, accessing <see cref="Value"/> will force initialization. /// Please <see cref="System.Threading.LazyThreadSafetyMode"> for more information on how <see cref="T:System.Threading.Lazy{T}"/> will behave if an exception is thrown /// from initialization delegate. /// </remarks> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Value => _state == null ? m_value : CreateValue(); } /// <summary>A debugger view of the Lazy&lt;T&gt; to surface additional debugging properties and /// to ensure that the Lazy&lt;T&gt; does not become initialized if it was not already.</summary> internal sealed class System_LazyDebugView<T> { //The Lazy object being viewed. private readonly Lazy<T> _lazy; /// <summary>Constructs a new debugger view object for the provided Lazy object.</summary> /// <param name="lazy">A Lazy object to browse in the debugger.</param> public System_LazyDebugView(Lazy<T> lazy) { _lazy = lazy; } /// <summary>Returns whether the Lazy object is initialized or not.</summary> public bool IsValueCreated { get { return _lazy.IsValueCreated; } } /// <summary>Returns the value of the Lazy object.</summary> public T Value { get { return _lazy.ValueForDebugDisplay; } } /// <summary>Returns the execution mode of the Lazy object</summary> public LazyThreadSafetyMode? Mode { get { return _lazy.Mode; } } /// <summary>Returns the execution mode of the Lazy object</summary> public bool IsValueFaulted { get { return _lazy.IsValueFaulted; } } } }
using System.Diagnostics; using Exceptionless.Core.Billing; using Exceptionless.Core.Extensions; using Exceptionless.Core.Messaging.Models; using Exceptionless.Core.Models; using Exceptionless.Core.Repositories; using Exceptionless.DateTimeExtensions; using Exceptionless.Extensions; using Foundatio.Caching; using Foundatio.Messaging; using Foundatio.Repositories; using Foundatio.Utility; using Microsoft.Extensions.Logging; namespace Exceptionless.Core.Services; public sealed class UsageService { private readonly IOrganizationRepository _organizationRepository; private readonly IProjectRepository _projectRepository; private readonly ICacheClient _cache; private readonly IMessagePublisher _messagePublisher; private readonly BillingPlans _plans; private readonly ILogger<UsageService> _logger; public UsageService(IOrganizationRepository organizationRepository, IProjectRepository projectRepository, ICacheClient cache, IMessagePublisher messagePublisher, BillingPlans plans, ILoggerFactory loggerFactory = null) { _organizationRepository = organizationRepository; _projectRepository = projectRepository; _cache = cache; _messagePublisher = messagePublisher; _plans = plans; _logger = loggerFactory.CreateLogger<UsageService>(); } public Task<bool> IncrementTooBigAsync(Organization organization, Project project, bool applyHourlyLimit = true) { return IncrementUsageAsync(organization, project, true, 1, applyHourlyLimit); } public async Task<bool> IsOverLimitAsync(Organization organization) { if (organization == null || organization.MaxEventsPerMonth < 0) return false; // PERF: could save two cache calls by not returning all usage stats. var orgUsage = await GetUsageAsync(organization).AnyContext(); double totalBlocked = GetTotalBlocked(organization, 0, orgUsage, true); return totalBlocked > 0; } public Task<bool> IncrementUsageAsync(Organization organization, Project project, int count = 1, bool applyHourlyLimit = true) { return IncrementUsageAsync(organization, project, false, count, applyHourlyLimit); } private async Task<bool> IncrementUsageAsync(Organization organization, Project project, bool tooBig, int count = 1, bool applyHourlyLimit = true) { if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), "Count cannot be negative"); if (organization == null || organization.MaxEventsPerMonth < 0 || project == null) return false; var orgUsage = await IncrementUsageAsync(organization, tooBig, count).AnyContext(); double totalBlocked = GetTotalBlocked(organization, count, orgUsage, applyHourlyLimit); bool overLimit = totalBlocked > 0; if (overLimit) { orgUsage.HourlyBlocked = await _cache.IncrementAsync(GetHourlyBlockedCacheKey(organization.Id), (int)totalBlocked, TimeSpan.FromMinutes(61), (long)orgUsage.HourlyBlocked).AnyContext(); orgUsage.MonthlyBlocked = await _cache.IncrementAsync(GetMonthlyBlockedCacheKey(organization.Id), (int)totalBlocked, TimeSpan.FromDays(32), (long)orgUsage.MonthlyBlocked).AnyContext(); } bool justWentOverHourly = orgUsage.HourlyTotal > organization.GetHourlyEventLimit(_plans) && orgUsage.HourlyTotal <= organization.GetHourlyEventLimit(_plans) + count; bool justWentOverMonthly = orgUsage.MonthlyTotal > organization.GetMaxEventsPerMonthWithBonus() && orgUsage.MonthlyTotal <= organization.GetMaxEventsPerMonthWithBonus() + count; var projectUsage = await IncrementUsageAsync(organization, project, tooBig, count, overLimit, (int)totalBlocked).AnyContext(); var tasks = new List<Task>(3) { SaveUsageAsync(organization, justWentOverHourly, justWentOverMonthly, orgUsage), SaveUsageAsync(organization, project, justWentOverHourly, justWentOverMonthly, projectUsage) }; if (justWentOverMonthly) tasks.Add(_messagePublisher.PublishAsync(new PlanOverage { OrganizationId = organization.Id })); else if (justWentOverHourly) tasks.Add(_messagePublisher.PublishAsync(new PlanOverage { OrganizationId = organization.Id, IsHourly = true })); await Task.WhenAll(tasks).AnyContext(); return overLimit; } private async Task<Usage> IncrementUsageAsync(Organization org, bool tooBig, int count) { int tooBigCount = !tooBig || count != 0 ? count : 1; var hourlyTotal = _cache.IncrementIfAsync(GetHourlyTotalCacheKey(org.Id), count, TimeSpan.FromMinutes(61), count != 0, org.GetCurrentHourlyTotal()); var monthlyTotal = _cache.IncrementIfAsync(GetMonthlyTotalCacheKey(org.Id), count, TimeSpan.FromDays(32), count != 0, org.GetCurrentMonthlyTotal()); var hourlyTooBig = _cache.IncrementIfAsync(GetHourlyTooBigCacheKey(org.Id), tooBigCount, TimeSpan.FromMinutes(61), tooBig, org.GetCurrentHourlyTooBig()); var monthlyTooBig = _cache.IncrementIfAsync(GetMonthlyTooBigCacheKey(org.Id), tooBigCount, TimeSpan.FromDays(32), tooBig, org.GetCurrentMonthlyTooBig()); var hourlyBlocked = _cache.GetAsync<long>(GetHourlyBlockedCacheKey(org.Id), org.GetCurrentHourlyBlocked()); var monthlyBlocked = _cache.GetAsync<long>(GetMonthlyBlockedCacheKey(org.Id), org.GetCurrentMonthlyBlocked()); await Task.WhenAll(hourlyTotal, monthlyTotal, hourlyTooBig, monthlyTooBig, hourlyBlocked, monthlyBlocked).AnyContext(); return new Usage { HourlyTotal = hourlyTotal.Result, MonthlyTotal = monthlyTotal.Result, HourlyTooBig = hourlyTooBig.Result, MonthlyTooBig = monthlyTooBig.Result, HourlyBlocked = hourlyBlocked.Result, MonthlyBlocked = monthlyBlocked.Result, }; } private async Task<Usage> IncrementUsageAsync(Organization org, Project project, bool tooBig, int count, bool overLimit, int totalBlocked) { int tooBigCount = !tooBig || count != 0 ? count : 1; var hourlyTotal = _cache.IncrementIfAsync(GetHourlyTotalCacheKey(org.Id, project.Id), count, TimeSpan.FromMinutes(61), count != 0, project.GetCurrentHourlyTotal()); var monthlyTotal = _cache.IncrementIfAsync(GetMonthlyTotalCacheKey(org.Id, project.Id), count, TimeSpan.FromDays(32), count != 0, project.GetCurrentMonthlyTotal()); var hourlyTooBig = _cache.IncrementIfAsync(GetHourlyTooBigCacheKey(org.Id, project.Id), tooBigCount, TimeSpan.FromMinutes(61), tooBig, project.GetCurrentHourlyTooBig()); var monthlyTooBig = _cache.IncrementIfAsync(GetMonthlyTooBigCacheKey(org.Id, project.Id), tooBigCount, TimeSpan.FromDays(32), tooBig, project.GetCurrentMonthlyTooBig()); var hourlyBlocked = _cache.IncrementIfAsync(GetHourlyBlockedCacheKey(org.Id, project.Id), totalBlocked, TimeSpan.FromMinutes(61), overLimit, project.GetCurrentHourlyBlocked()); var monthlyBlocked = _cache.IncrementIfAsync(GetMonthlyBlockedCacheKey(org.Id, project.Id), totalBlocked, TimeSpan.FromDays(32), overLimit, project.GetCurrentMonthlyBlocked()); await Task.WhenAll(hourlyTotal, monthlyTotal, hourlyTooBig, monthlyTooBig, hourlyBlocked, monthlyBlocked).AnyContext(); return new Usage { HourlyTotal = hourlyTotal.Result, MonthlyTotal = monthlyTotal.Result, HourlyTooBig = hourlyTooBig.Result, MonthlyTooBig = monthlyTooBig.Result, HourlyBlocked = hourlyBlocked.Result, MonthlyBlocked = monthlyBlocked.Result, }; } public async Task<Usage> GetUsageAsync(Organization org) { var hourlyTotal = _cache.GetAsync<long>(GetHourlyTotalCacheKey(org.Id), org.GetCurrentHourlyTotal()); var monthlyTotal = _cache.GetAsync<long>(GetMonthlyTotalCacheKey(org.Id), org.GetCurrentMonthlyTotal()); var hourlyTooBig = _cache.GetAsync<long>(GetHourlyTooBigCacheKey(org.Id), org.GetCurrentHourlyTooBig()); var monthlyTooBig = _cache.GetAsync<long>(GetMonthlyTooBigCacheKey(org.Id), org.GetCurrentMonthlyTooBig()); var hourlyBlocked = _cache.GetAsync<long>(GetHourlyBlockedCacheKey(org.Id), org.GetCurrentHourlyBlocked()); var monthlyBlocked = _cache.GetAsync<long>(GetMonthlyBlockedCacheKey(org.Id), org.GetCurrentMonthlyBlocked()); await Task.WhenAll(hourlyTotal, monthlyTotal, hourlyTooBig, monthlyTooBig, hourlyBlocked, monthlyBlocked).AnyContext(); return new Usage { HourlyTotal = hourlyTotal.Result, MonthlyTotal = monthlyTotal.Result, HourlyTooBig = hourlyTooBig.Result, MonthlyTooBig = monthlyTooBig.Result, HourlyBlocked = hourlyBlocked.Result, MonthlyBlocked = monthlyBlocked.Result, }; } public async Task<Usage> GetUsageAsync(Organization org, Project project) { var hourlyTotal = _cache.GetAsync<long>(GetHourlyTotalCacheKey(org.Id, project.Id), project.GetCurrentHourlyTotal()); var monthlyTotal = _cache.GetAsync<long>(GetMonthlyTotalCacheKey(org.Id, project.Id), project.GetCurrentMonthlyTotal()); var hourlyTooBig = _cache.GetAsync<long>(GetHourlyTooBigCacheKey(org.Id, project.Id), project.GetCurrentHourlyTooBig()); var monthlyTooBig = _cache.GetAsync<long>(GetMonthlyTooBigCacheKey(org.Id, project.Id), project.GetCurrentMonthlyTooBig()); var hourlyBlocked = _cache.GetAsync<long>(GetHourlyBlockedCacheKey(org.Id, project.Id), project.GetCurrentHourlyBlocked()); var monthlyBlocked = _cache.GetAsync<long>(GetMonthlyBlockedCacheKey(org.Id, project.Id), project.GetCurrentMonthlyBlocked()); await Task.WhenAll(hourlyTotal, monthlyTotal, hourlyTooBig, monthlyTooBig, hourlyBlocked, monthlyBlocked).AnyContext(); return new Usage { HourlyTotal = hourlyTotal.Result, MonthlyTotal = monthlyTotal.Result, HourlyTooBig = hourlyTooBig.Result, MonthlyTooBig = monthlyTooBig.Result, HourlyBlocked = hourlyBlocked.Result, MonthlyBlocked = monthlyBlocked.Result, }; } private async Task SaveUsageAsync(Organization org, bool justWentOverHourly, bool justWentOverMonthly, Usage usage) { bool shouldSaveUsage = await ShouldSaveUsageAsync(org, null, justWentOverHourly, justWentOverMonthly).AnyContext(); if (!shouldSaveUsage) return; string orgId = org.Id; try { org = await _organizationRepository.GetByIdAsync(orgId).AnyContext(); if (org == null) return; org.LastEventDateUtc = SystemClock.UtcNow; org.SetMonthlyUsage(usage.MonthlyTotal, usage.MonthlyBlocked, usage.MonthlyTooBig); if (usage.HourlyBlocked > 0 || usage.HourlyTooBig > 0) org.SetHourlyOverage(usage.HourlyTotal, usage.HourlyBlocked, usage.HourlyTooBig, _plans); await _organizationRepository.SaveAsync(org, o => o.Cache()).AnyContext(); await _cache.SetAsync(GetUsageSavedCacheKey(orgId), SystemClock.UtcNow, TimeSpan.FromDays(32)).AnyContext(); } catch (Exception ex) { _logger.LogError(ex, "Error while saving organization {OrganizationId} usage data.", orgId); // Set the next document save for 5 seconds in the future. await _cache.SetAsync(GetUsageSavedCacheKey(orgId), SystemClock.UtcNow.SubtractMinutes(4).SubtractSeconds(55), TimeSpan.FromDays(32)).AnyContext(); } } private async Task SaveUsageAsync(Organization org, Project project, bool justWentOverHourly, bool justWentOverMonthly, Usage usage) { bool shouldSaveUsage = await ShouldSaveUsageAsync(org, project, justWentOverHourly, justWentOverMonthly).AnyContext(); if (!shouldSaveUsage) return; string projectId = project.Id; try { project = await _projectRepository.GetByIdAsync(projectId).AnyContext(); if (project == null) return; project.LastEventDateUtc = SystemClock.UtcNow; project.SetMonthlyUsage(usage.MonthlyTotal, usage.MonthlyBlocked, usage.MonthlyTooBig, org.GetMaxEventsPerMonthWithBonus()); if (usage.HourlyBlocked > 0 || usage.HourlyTooBig > 0) project.SetHourlyOverage(usage.HourlyTotal, usage.HourlyBlocked, usage.HourlyTooBig, org.GetHourlyEventLimit(_plans)); await _projectRepository.SaveAsync(project, o => o.Cache()).AnyContext(); await _cache.SetAsync(GetUsageSavedCacheKey(org.Id, projectId), SystemClock.UtcNow, TimeSpan.FromDays(32)).AnyContext(); } catch (Exception ex) { _logger.LogError(ex, "Error while saving project {ProjectId} usage data.", projectId); // Set the next document save for 5 seconds in the future. await _cache.SetAsync(GetUsageSavedCacheKey(org.Id, projectId), SystemClock.UtcNow.SubtractMinutes(4).SubtractSeconds(55), TimeSpan.FromDays(32)).AnyContext(); } } private async Task<bool> ShouldSaveUsageAsync(Organization organization, Project project, bool justWentOverHourly, bool justWentOverMonthly) { // save usages if we just went over one of the limits bool shouldSaveUsage = justWentOverHourly || justWentOverMonthly; if (shouldSaveUsage) return true; var lastCounterSavedDate = await _cache.GetAsync<DateTime>(GetUsageSavedCacheKey(organization.Id, project?.Id)).AnyContext(); // don't save on the 1st increment, but set the last saved date so we will save in 5 minutes if (!lastCounterSavedDate.HasValue) await _cache.SetAsync(GetUsageSavedCacheKey(organization.Id, project?.Id), SystemClock.UtcNow, TimeSpan.FromDays(32)).AnyContext(); // TODO: If the save period is in the next hour we will lose all data in the past five minutes. // save usages if the last time we saved them is more than 5 minutes ago if (lastCounterSavedDate.HasValue && SystemClock.UtcNow.Subtract(lastCounterSavedDate.Value).TotalMinutes >= 5) shouldSaveUsage = true; return shouldSaveUsage; } public async Task<int> GetRemainingEventLimitAsync(Organization organization) { if (organization == null || organization.MaxEventsPerMonth < 0) return Int32.MaxValue; string monthlyCacheKey = GetMonthlyTotalCacheKey(organization.Id); long monthlyEventCount = await _cache.GetAsync<long>(monthlyCacheKey, 0).AnyContext(); return Math.Max(0, organization.GetMaxEventsPerMonthWithBonus() - (int)monthlyEventCount); } private double GetTotalBlocked(Organization organization, int count, Usage usage, bool applyHourlyLimit) { if (organization.IsSuspended) return count; int hourlyEventLimit = organization.GetHourlyEventLimit(_plans); int monthlyEventLimit = organization.GetMaxEventsPerMonthWithBonus(); double originalAllowedMonthlyEventTotal = usage.MonthlyTotal - usage.MonthlyBlocked - count; // If the original count is less than the max events per month and original count + hourly limit is greater than the max events per month then use the monthly limit. if (originalAllowedMonthlyEventTotal < monthlyEventLimit && (originalAllowedMonthlyEventTotal + hourlyEventLimit) >= monthlyEventLimit) return originalAllowedMonthlyEventTotal < monthlyEventLimit ? Math.Max(usage.MonthlyTotal - usage.MonthlyBlocked - monthlyEventLimit, 0) : count; double originalAllowedHourlyEventTotal = usage.HourlyTotal - usage.HourlyBlocked - count; if (applyHourlyLimit && (usage.HourlyTotal - usage.HourlyBlocked) > hourlyEventLimit) return originalAllowedHourlyEventTotal < hourlyEventLimit ? Math.Max(usage.HourlyTotal - usage.HourlyBlocked - hourlyEventLimit, 0) : count; if ((usage.MonthlyTotal - usage.MonthlyBlocked) > monthlyEventLimit) return originalAllowedMonthlyEventTotal < monthlyEventLimit ? Math.Max(usage.MonthlyTotal - usage.MonthlyBlocked - monthlyEventLimit, 0) : count; return 0; } private string GetHourlyBlockedCacheKey(string organizationId, string projectId = null) { string key = String.Concat("usage:blocked", ":", SystemClock.UtcNow.ToString("MMddHH"), ":", organizationId); return projectId == null ? key : String.Concat(key, ":", projectId); } private string GetHourlyTotalCacheKey(string organizationId, string projectId = null) { string key = String.Concat("usage:total", ":", SystemClock.UtcNow.ToString("MMddHH"), ":", organizationId); return projectId == null ? key : String.Concat(key, ":", projectId); } private string GetHourlyTooBigCacheKey(string organizationId, string projectId = null) { string key = String.Concat("usage:toobig", ":", SystemClock.UtcNow.ToString("MMddHH"), ":", organizationId); return projectId == null ? key : String.Concat(key, ":", projectId); } private string GetMonthlyBlockedCacheKey(string organizationId, string projectId = null) { string key = String.Concat("usage:blocked", ":", SystemClock.UtcNow.Date.ToString("MM"), ":", organizationId); return projectId == null ? key : String.Concat(key, ":", projectId); } private string GetMonthlyTotalCacheKey(string organizationId, string projectId = null) { string key = String.Concat("usage:total", ":", SystemClock.UtcNow.Date.ToString("MM"), ":", organizationId); return projectId == null ? key : String.Concat(key, ":", projectId); } private string GetMonthlyTooBigCacheKey(string organizationId, string projectId = null) { string key = String.Concat("usage:toobig", ":", SystemClock.UtcNow.Date.ToString("MM"), ":", organizationId); return projectId == null ? key : String.Concat(key, ":", projectId); } private string GetUsageSavedCacheKey(string organizationId, string projectId = null) { string key = String.Concat("usage:saved", ":", organizationId); return projectId == null ? key : String.Concat(key, ":", projectId); } [DebuggerDisplay("MonthlyTotal: {MonthlyTotal}, HourlyTotal: {HourlyTotal}, MonthlyBlocked: {MonthlyBlocked}, HourlyBlocked: {HourlyBlocked}, MonthlyTooBig: {MonthlyTooBig}, HourlyTooBig: {HourlyTooBig}")] public struct Usage { public double MonthlyTotal { get; set; } public double HourlyTotal { get; set; } public double MonthlyBlocked { get; set; } public double HourlyBlocked { get; set; } public double MonthlyTooBig { get; set; } public double HourlyTooBig { get; set; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the RisTipoDocumento class. /// </summary> [Serializable] public partial class RisTipoDocumentoCollection : ActiveList<RisTipoDocumento, RisTipoDocumentoCollection> { public RisTipoDocumentoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>RisTipoDocumentoCollection</returns> public RisTipoDocumentoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { RisTipoDocumento o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the RIS_TipoDocumento table. /// </summary> [Serializable] public partial class RisTipoDocumento : ActiveRecord<RisTipoDocumento>, IActiveRecord { #region .ctors and Default Settings public RisTipoDocumento() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public RisTipoDocumento(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public RisTipoDocumento(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public RisTipoDocumento(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("RIS_TipoDocumento", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdTipoDocumento = new TableSchema.TableColumn(schema); colvarIdTipoDocumento.ColumnName = "idTipoDocumento"; colvarIdTipoDocumento.DataType = DbType.Int32; colvarIdTipoDocumento.MaxLength = 0; colvarIdTipoDocumento.AutoIncrement = true; colvarIdTipoDocumento.IsNullable = false; colvarIdTipoDocumento.IsPrimaryKey = true; colvarIdTipoDocumento.IsForeignKey = false; colvarIdTipoDocumento.IsReadOnly = false; colvarIdTipoDocumento.DefaultSetting = @""; colvarIdTipoDocumento.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdTipoDocumento); TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema); colvarDescripcion.ColumnName = "descripcion"; colvarDescripcion.DataType = DbType.AnsiString; colvarDescripcion.MaxLength = 100; colvarDescripcion.AutoIncrement = false; colvarDescripcion.IsNullable = false; colvarDescripcion.IsPrimaryKey = false; colvarDescripcion.IsForeignKey = false; colvarDescripcion.IsReadOnly = false; colvarDescripcion.DefaultSetting = @""; colvarDescripcion.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripcion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("RIS_TipoDocumento",schema); } } #endregion #region Props [XmlAttribute("IdTipoDocumento")] [Bindable(true)] public int IdTipoDocumento { get { return GetColumnValue<int>(Columns.IdTipoDocumento); } set { SetColumnValue(Columns.IdTipoDocumento, value); } } [XmlAttribute("Descripcion")] [Bindable(true)] public string Descripcion { get { return GetColumnValue<string>(Columns.Descripcion); } set { SetColumnValue(Columns.Descripcion, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varDescripcion) { RisTipoDocumento item = new RisTipoDocumento(); item.Descripcion = varDescripcion; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdTipoDocumento,string varDescripcion) { RisTipoDocumento item = new RisTipoDocumento(); item.IdTipoDocumento = varIdTipoDocumento; item.Descripcion = varDescripcion; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdTipoDocumentoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn DescripcionColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdTipoDocumento = @"idTipoDocumento"; public static string Descripcion = @"descripcion"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// // Copyright 2012, Xamarin 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.Net; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using System.Linq; using System.Text; using System.Threading; using Xamarin.Auth; using Xamarin.Utilities; namespace Xamarin.Auth { /// <summary> /// An HTTP web request that provides a convenient way to make authenticated /// requests using account objects obtained from an authenticator. /// </summary> #if XAMARIN_AUTH_INTERNAL internal class Request #else public class Request #endif { HttpWebRequest request; /// <summary> /// The HTTP method. /// </summary> public string Method { get; protected set; } /// <summary> /// The URL of the resource to request. /// </summary> public Uri Url { get; protected set; } /// <summary> /// The parameters of the request. These will be added to the query string of the /// URL for GET requests, encoded as form a parameters for POSTs, and added as /// multipart values if the request uses <see cref="Multiparts"/>. /// </summary> public IDictionary<string, string> Parameters { get; protected set; } /// <summary> /// The account that will be used to authenticate this request. /// </summary> public virtual Account Account { get; set; } /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.Request"/> class. /// </summary> /// <param name='method'> /// The HTTP method. /// </param> /// <param name='url'> /// The URL. /// </param> /// <param name='parameters'> /// Parameters that will pre-populate the <see cref="Parameters"/> property or null. /// </param> /// <param name='account'> /// The account used to authenticate this request. /// </param> public Request (string method, Uri url, IDictionary<string, string> parameters = null, Account account = null) { Method = method; Url = url; Parameters = parameters == null ? new Dictionary<string, string> () : new Dictionary<string, string> (parameters); Account = account; } /// <summary> /// A single part of a multipart request. /// </summary> protected class Part { /// <summary> /// The data. /// </summary> public Stream Data; /// <summary> /// The optional textual representation of the <see cref="Data"/>. /// </summary> public string TextData; /// <summary> /// The name. /// </summary> public string Name; /// <summary> /// The MIME type. /// </summary> public string MimeType; /// <summary> /// The filename of this part if it represents a file. /// </summary> public string Filename; } /// <summary> /// The parts of a multipart request. /// </summary> protected readonly List<Part> Multiparts = new List<Part> (); /// <summary> /// Adds a part to the request. Doing so will make this request be sent as multipart/form-data. /// </summary> /// <param name='name'> /// Name of the part. /// </param> /// <param name='data'> /// Text value of the part. /// </param> public void AddMultipartData (string name, string data) { Multiparts.Add (new Part { TextData = data, Data = new MemoryStream (Encoding.UTF8.GetBytes (data)), Name = name, MimeType = "", Filename = "", }); } /// <summary> /// Adds a part to the request. Doing so will make this request be sent as multipart/form-data. /// </summary> /// <param name='name'> /// Name of the part. /// </param> /// <param name='data'> /// Data used when transmitting this part. /// </param> /// <param name='mimeType'> /// The MIME type of this part. /// </param> /// <param name='filename'> /// The filename of this part if it represents a file. /// </param> public virtual void AddMultipartData (string name, Stream data, string mimeType = "", string filename = "") { Multiparts.Add (new Part { Data = data, Name = name, MimeType = mimeType, Filename = filename, }); } /// <summary> /// Gets the response. /// </summary> /// <returns> /// The response. /// </returns> public virtual Task<Response> GetResponseAsync () { return GetResponseAsync (CancellationToken.None); } /// <summary> /// Gets the response. /// </summary> /// <remarks> /// Service implementors should override this method to modify the PreparedWebRequest /// to authenticate it. /// </remarks> /// <returns> /// The response. /// </returns> public virtual Task<Response> GetResponseAsync (CancellationToken cancellationToken) { var request = GetPreparedWebRequest (); // // Disable 100-Continue: http://blogs.msdn.com/b/shitals/archive/2008/12/27/9254245.aspx // if (Method == "POST") { ServicePointManager.Expect100Continue = false; } if (Multiparts.Count > 0) { var boundary = "---------------------------" + new Random ().Next (); request.ContentType = "multipart/form-data; boundary=" + boundary; return Task.Factory .FromAsync<Stream> (request.BeginGetRequestStream, request.EndGetRequestStream, null) .ContinueWith (reqStreamtask => { using (reqStreamtask.Result) { WriteMultipartFormData (boundary, reqStreamtask.Result); } return Task.Factory .FromAsync<WebResponse> (request.BeginGetResponse, request.EndGetResponse, null) .ContinueWith (resTask => { return new Response ((HttpWebResponse)resTask.Result); }, cancellationToken); }, cancellationToken).Unwrap(); } else if (Method == "POST" && Parameters.Count > 0) { var body = Parameters.FormEncode (); var bodyData = System.Text.Encoding.UTF8.GetBytes (body); request.ContentLength = bodyData.Length; request.ContentType = "application/x-www-form-urlencoded"; return Task.Factory .FromAsync<Stream> (request.BeginGetRequestStream, request.EndGetRequestStream, null) .ContinueWith (reqStreamTask => { using (reqStreamTask.Result) { reqStreamTask.Result.Write (bodyData, 0, bodyData.Length); } return Task.Factory .FromAsync<WebResponse> (request.BeginGetResponse, request.EndGetResponse, null) .ContinueWith (resTask => { return new Response ((HttpWebResponse)resTask.Result); }, cancellationToken); }, cancellationToken).Unwrap(); } else { return Task.Factory .FromAsync<WebResponse> (request.BeginGetResponse, request.EndGetResponse, null) .ContinueWith (resTask => { return new Response ((HttpWebResponse)resTask.Result); }, cancellationToken); } } void WriteMultipartFormData (string boundary, Stream s) { var boundaryBytes = Encoding.ASCII.GetBytes ("--" + boundary); foreach (var p in Multiparts) { s.Write (boundaryBytes, 0, boundaryBytes.Length); s.Write (CrLf, 0, CrLf.Length); // // Content-Disposition // var header = "Content-Disposition: form-data; name=\"" + p.Name + "\""; if (!string.IsNullOrEmpty (p.Filename)) { header += "; filename=\"" + p.Filename + "\""; } var headerBytes = Encoding.ASCII.GetBytes (header); s.Write (headerBytes, 0, headerBytes.Length); s.Write (CrLf, 0, CrLf.Length); // // Content-Type // if (!string.IsNullOrEmpty (p.MimeType)) { header = "Content-Type: " + p.MimeType; headerBytes = Encoding.ASCII.GetBytes (header); s.Write (headerBytes, 0, headerBytes.Length); s.Write (CrLf, 0, CrLf.Length); } // // End Header // s.Write (CrLf, 0, CrLf.Length); // // Data // p.Data.CopyTo (s); s.Write (CrLf, 0, CrLf.Length); } // // End // s.Write (boundaryBytes, 0, boundaryBytes.Length); s.Write (DashDash, 0, DashDash.Length); s.Write (CrLf, 0, CrLf.Length); } static readonly byte[] CrLf = new byte[] { (byte)'\r', (byte)'\n' }; static readonly byte[] DashDash = new byte[] { (byte)'-', (byte)'-' }; /// <summary> /// Gets the prepared URL. /// </summary> /// <remarks> /// Service implementors should override this function and add any needed parameters /// from the Account to the URL before it is used to get the response. /// </remarks> /// <returns> /// The prepared URL. /// </returns> protected virtual Uri GetPreparedUrl () { var url = Url.AbsoluteUri; if (Parameters.Count > 0 && Method != "POST") { var head = Url.AbsoluteUri.Contains ('?') ? "&" : "?"; foreach (var p in Parameters) { url += head; url += Uri.EscapeDataString (p.Key); url += "="; url += Uri.EscapeDataString (p.Value); head = "&"; } } return new Uri (url); } /// <summary> /// Returns the <see cref="T:System.Net.HttpWebRequest"/> that will be used for this <see cref="T:Xamarin.Auth.Request"/>. All properties /// should be set to their correct values before accessing this object. /// </summary> /// <remarks> /// Service implementors should modify the returned request to add whatever /// authentication data is needed before getting the response. /// </remarks> /// <returns> /// The prepared HTTP web request. /// </returns> protected virtual HttpWebRequest GetPreparedWebRequest () { if (request == null) { request = (HttpWebRequest)WebRequest.Create (GetPreparedUrl ()); request.Method = Method; } if (request.CookieContainer == null && Account != null) { request.CookieContainer = Account.Cookies; } return request; } } }
//--------------------------------------------------------------------- // <copyright file="CqlBlock.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Linq; using System.Data.Common.CommandTrees; using System.Data.Common.CommandTrees.ExpressionBuilder; using System.Data.Common.Utils; using System.Collections.Generic; using System.Data.Mapping.ViewGeneration.Structures; using System.Collections.ObjectModel; using System.Text; using System.Diagnostics; namespace System.Data.Mapping.ViewGeneration.CqlGeneration { /// <summary> /// A class that holds an expression of the form "(SELECT .. FROM .. WHERE) AS alias". /// Essentially, it allows generating Cql query in a localized manner, i.e., all global decisions about nulls, constants, /// case statements, etc have already been made. /// </summary> internal abstract class CqlBlock : InternalBase { /// <summary> /// Initializes a <see cref="CqlBlock"/> with the SELECT (<paramref name="slotInfos"/>), FROM (<paramref name="children"/>), /// WHERE (<paramref name="whereClause"/>), AS (<paramref name="blockAliasNum"/>). /// </summary> protected CqlBlock(SlotInfo[] slotInfos, List<CqlBlock> children, BoolExpression whereClause, CqlIdentifiers identifiers, int blockAliasNum) { m_slots = new ReadOnlyCollection<SlotInfo>(slotInfos); m_children = new ReadOnlyCollection<CqlBlock>(children); m_whereClause = whereClause; m_blockAlias = identifiers.GetBlockAlias(blockAliasNum); } #region Fields /// <summary> /// Essentially, SELECT. May be replaced with another collection after block construction. /// </summary> private ReadOnlyCollection<SlotInfo> m_slots; /// <summary> /// FROM inputs. /// </summary> private readonly ReadOnlyCollection<CqlBlock> m_children; /// <summary> /// WHERER. /// </summary> private readonly BoolExpression m_whereClause; /// <summary> /// Alias of the whole block for cql generation. /// </summary> private readonly string m_blockAlias; /// <summary> /// See <see cref="JoinTreeContext"/> for more info. /// </summary> private JoinTreeContext m_joinTreeContext; #endregion #region Properties /// <summary> /// Returns all the slots for this block (SELECT). /// </summary> internal ReadOnlyCollection<SlotInfo> Slots { get { return m_slots; } set { m_slots = value; } } /// <summary> /// Returns all the child (input) blocks of this block (FROM). /// </summary> protected ReadOnlyCollection<CqlBlock> Children { get { return m_children; } } /// <summary> /// Returns the where clause of this block (WHERE). /// </summary> protected BoolExpression WhereClause { get { return m_whereClause; } } /// <summary> /// Returns an alias for this block that can be used for "AS". /// </summary> internal string CqlAlias { get { return m_blockAlias; } } #endregion #region Abstract Methods /// <summary> /// Returns a string corresponding to the eSQL representation of this block (and its children below). /// </summary> internal abstract StringBuilder AsEsql(StringBuilder builder, bool isTopLevel, int indentLevel); /// <summary> /// Returns a string corresponding to the CQT representation of this block (and its children below). /// </summary> internal abstract DbExpression AsCqt(bool isTopLevel); #endregion #region Methods /// <summary> /// For the given <paramref name="slotNum"/> creates a <see cref="QualifiedSlot"/> qualified with <see cref="CqlAlias"/> of the current block: /// "<see cref="CqlAlias"/>.slot_alias" /// </summary> internal QualifiedSlot QualifySlotWithBlockAlias(int slotNum) { Debug.Assert(this.IsProjected(slotNum), StringUtil.FormatInvariant("Slot {0} that is to be qualified with the block alias is not projected in this block", slotNum)); var slotInfo = m_slots[slotNum]; return new QualifiedSlot(this, slotInfo.SlotValue); } internal ProjectedSlot SlotValue(int slotNum) { Debug.Assert(slotNum < m_slots.Count, "Slotnum too high"); return m_slots[slotNum].SlotValue; } internal MemberPath MemberPath(int slotNum) { Debug.Assert(slotNum < m_slots.Count, "Slotnum too high"); return m_slots[slotNum].OutputMember; } /// <summary> /// Returns true iff <paramref name="slotNum"/> is being projected by this block. /// </summary> internal bool IsProjected(int slotNum) { Debug.Assert(slotNum < m_slots.Count, "Slotnum too high"); return m_slots[slotNum].IsProjected; } /// <summary> /// Generates "A, B, C, ..." for all the slots in the block. /// </summary> protected void GenerateProjectionEsql(StringBuilder builder, string blockAlias, bool addNewLineAfterEachSlot, int indentLevel, bool isTopLevel) { bool isFirst = true; foreach (SlotInfo slotInfo in Slots) { if (false == slotInfo.IsRequiredByParent) { // Ignore slots that are not needed continue; } if (isFirst == false) { builder.Append(", "); } if (addNewLineAfterEachSlot) { StringUtil.IndentNewLine(builder, indentLevel + 1); } slotInfo.AsEsql(builder, blockAlias, indentLevel); // Print the field alias for complex expressions that don't produce default alias. // Don't print alias for qualified fields as they reproduce their alias. // Don't print alias if it's a top level query using SELECT VALUE. if (!isTopLevel && (!(slotInfo.SlotValue is QualifiedSlot) || slotInfo.IsEnforcedNotNull)) { builder.Append(" AS ") .Append(slotInfo.CqlFieldAlias); } isFirst = false; } if (addNewLineAfterEachSlot) { StringUtil.IndentNewLine(builder, indentLevel); } } /// <summary> /// Generates "NewRow(A, B, C, ...)" for all the slots in the block. /// If <paramref name="isTopLevel"/>=true then generates "A" for the only slot that is marked as <see cref="SlotInfo.IsRequiredByParent"/>. /// </summary> protected DbExpression GenerateProjectionCqt(DbExpression row, bool isTopLevel) { if (isTopLevel) { Debug.Assert(this.Slots.Where(slot => slot.IsRequiredByParent).Count() == 1, "Top level projection must project only one slot."); return this.Slots.Where(slot => slot.IsRequiredByParent).Single().AsCqt(row); } else { return DbExpressionBuilder.NewRow( this.Slots.Where(slot => slot.IsRequiredByParent).Select(slot => new KeyValuePair<string, DbExpression>(slot.CqlFieldAlias, slot.AsCqt(row)))); } } /// <summary> /// Initializes context positioning in the join tree that owns the <see cref="CqlBlock"/>. /// For more info see <see cref="JoinTreeContext"/>. /// </summary> internal void SetJoinTreeContext(IList<string> parentQualifiers, string leafQualifier) { Debug.Assert(m_joinTreeContext == null, "Join tree context is already set."); m_joinTreeContext = new JoinTreeContext(parentQualifiers, leafQualifier); } /// <summary> /// Searches the input <paramref name="row"/> for the property that represents the current <see cref="CqlBlock"/>. /// In all cases except JOIN, the <paramref name="row"/> is returned as is. /// In case of JOIN, <paramref name="row"/>.JoinVarX.JoinVarY...blockVar is returned. /// See <see cref="SetJoinTreeContext"/> for more info. /// </summary> internal DbExpression GetInput(DbExpression row) { return m_joinTreeContext != null ? m_joinTreeContext.FindInput(row) : row; } internal override void ToCompactString(StringBuilder builder) { for (int i = 0; i < m_slots.Count; i++) { StringUtil.FormatStringBuilder(builder, "{0}: ", i); m_slots[i].ToCompactString(builder); builder.Append(' '); } m_whereClause.ToCompactString(builder); } #endregion #region JoinTreeContext /// <summary> /// The class represents a position of a <see cref="CqlBlock"/> in a join tree. /// It is expected that the join tree is left-recursive (not balanced) and looks like this: /// /// ___J___ /// / \ /// L3/ \R3 /// / \ /// __J__ \ /// / \ \ /// L2/ \R2 \ /// / \ \ /// _J_ \ \ /// / \ \ \ /// L1/ \R1 \ \ /// / \ \ \ /// CqlBlock1 CqlBlock2 CqlBlock3 CqlBlock4 /// /// Example of <see cref="JoinTreeContext"/>s for the <see cref="CqlBlock"/>s: /// block# m_parentQualifiers m_indexInParentQualifiers m_leafQualifier FindInput(row) = ... /// 1 (L2, L3) 0 L1 row.(L3.L2).L1 /// 2 (L2, L3) 0 R1 row.(L3.L2).R1 /// 3 (L2, L3) 1 R2 row.(L3).R2 /// 4 (L2, L3) 2 R3 row.().R3 /// /// </summary> private sealed class JoinTreeContext { internal JoinTreeContext(IList<string> parentQualifiers, string leafQualifier) { Debug.Assert(parentQualifiers != null, "parentQualifiers != null"); Debug.Assert(leafQualifier != null, "leafQualifier != null"); m_parentQualifiers = parentQualifiers; m_indexInParentQualifiers = parentQualifiers.Count; m_leafQualifier = leafQualifier; } private readonly IList<string> m_parentQualifiers; private readonly int m_indexInParentQualifiers; private readonly string m_leafQualifier; internal DbExpression FindInput(DbExpression row) { DbExpression cqt = row; for (int i = m_parentQualifiers.Count - 1; i >= m_indexInParentQualifiers; --i) { cqt = cqt.Property(m_parentQualifiers[i]); } return cqt.Property(m_leafQualifier); } } #endregion } }
/* * Copyright (C) 2009 The Android Open Source 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. */ using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Provider; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using System; namespace Xamarians.CropImage.Droid { /// <summary> /// The activity can crop specific region of interest from an image. /// </summary> [Activity] public class CropImageActivity : MonitoredActivity { #region Private members // These are various options can be specified in the intent. private Bitmap.CompressFormat outputFormat = Bitmap.CompressFormat.Jpeg; private Android.Net.Uri saveUri = null; private int aspectX, aspectY; private Handler mHandler = new Handler(); // These options specifiy the output image size and whether we should // scale the output to fit it (or just crop it). private int outputX, outputY; private bool scale; private bool scaleUp = true; private CropImageView imageView; private Bitmap bitmap; private string imagePath; private const int NO_STORAGE_ERROR = -1; private const int CANNOT_STAT_ERROR = -2; #endregion #region Properties public HighlightView Crop { set; get; } /// <summary> /// Whether the "save" button is already clicked. /// </summary> public bool Saving { get; set; } #endregion #region Overrides protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); RequestWindowFeature(Android.Views.WindowFeatures.NoTitle); SetContentView(Resource.Layout.cropimage); imageView = FindViewById<CropImageView>(Resource.Id.image); showStorageToast(this); Bundle extras = Intent.Extras; if (extras != null) { imagePath = extras.GetString("image-path"); saveUri = getImageUri(imagePath); if (extras.GetString(MediaStore.ExtraOutput) != null) { saveUri = getImageUri(extras.GetString(MediaStore.ExtraOutput)); } bitmap = getBitmap(imagePath); aspectX = extras.GetInt("aspectX"); aspectY = extras.GetInt("aspectY"); outputX = extras.GetInt("outputX"); outputY = extras.GetInt("outputY"); scale = extras.GetBoolean("scale", true); scaleUp = extras.GetBoolean("scaleUpIfNeeded", true); if (extras.GetString("outputFormat") != null) { outputFormat = Bitmap.CompressFormat.ValueOf(extras.GetString("outputFormat")); } } if (bitmap == null) { Finish(); return; } Window.AddFlags(WindowManagerFlags.Fullscreen); FindViewById<Button>(Resource.Id.cancel).Click += (sender, e) => { CropImageServiceAndroid.SetResult(new CropResult(false) { Message = "Cancelled" }); Finish(); return; }; FindViewById<Button>(Resource.Id.done).Click += (sender, e) => { OnSaveClicked(); }; FindViewById<Button>(Resource.Id.rotateLeft).Click += (o, e) => { bitmap = Util.rotateImage(bitmap, -90); RotateBitmap rotateBitmap = new RotateBitmap(bitmap); imageView.SetImageRotateBitmapResetBase(rotateBitmap, true); addHighlightView(); }; //FindViewById<Button>(Resource.Id.rotateRight).Click += (o, e) => //{ // bitmap = Util.rotateImage(bitmap, 90); // RotateBitmap rotateBitmap = new RotateBitmap(bitmap); // imageView.SetImageRotateBitmapResetBase(rotateBitmap, true); // addHighlightView(); //}; imageView.SetImageBitmapResetBase(bitmap, true); addHighlightView(); } protected override void OnDestroy() { base.OnDestroy(); if (bitmap != null && bitmap.IsRecycled) { bitmap.Recycle(); } } //protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data) //{ // base.OnActivityResult(requestCode, resultCode, data); // if (resultCode != Result.Ok) // { // CropImageServiceAndroid.SetResult(new CropResult(false) { Message = resultCode.ToString() }); // Finish(); // return; // } // switch (requestCode) // { // case RequestCodeCamera: // if (_maxWidth > 0 && _maxHeight > 0) // ImageResizer.ResizeImage(this, _filePath, _filePath, _maxWidth, _maxHeight); // MediaServiceAndroid.SetResult(new MediaResult(true) { FilePath = _filePath }); // break; // case RequestCodeGallery: // MediaServiceAndroid.SetResult(new MediaResult(true) { FilePath = RealPathHelper.GetPath(this, data.Data) }); // break; // } // Finish(); //} #endregion #region Private helpers private void addHighlightView() { Crop = new HighlightView(imageView); int width = bitmap.Width; int height = bitmap.Height; Rect imageRect = new Rect(0, 0, width, height); // make the default size about 4/5 of the width or height int cropWidth = Math.Min(width, height) * 4 / 5; int cropHeight = cropWidth; if (aspectX != 0 && aspectY != 0) { if (aspectX > aspectY) { cropHeight = cropWidth * aspectY / aspectX; } else { cropWidth = cropHeight * aspectX / aspectY; } } int x = (width - cropWidth) / 2; int y = (height - cropHeight) / 2; RectF cropRect = new RectF(x, y, x + cropWidth, y + cropHeight); Crop.Setup(imageView.ImageMatrix, imageRect, cropRect, aspectX != 0 && aspectY != 0); imageView.ClearHighlightViews(); Crop.Focused = true; imageView.AddHighlightView(Crop); } private Android.Net.Uri getImageUri(String path) { return Android.Net.Uri.FromFile(new Java.IO.File(path)); } private Bitmap getBitmap(String path) { var uri = getImageUri(path); System.IO.Stream ins = null; try { int IMAGE_MAX_SIZE = 1024; ins = ContentResolver.OpenInputStream(uri); // Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.InJustDecodeBounds = true; BitmapFactory.DecodeStream(ins, null, o); ins.Close(); int scale = 1; if (o.OutHeight > IMAGE_MAX_SIZE || o.OutWidth > IMAGE_MAX_SIZE) { scale = (int)Math.Pow(2, (int)Math.Round(Math.Log(IMAGE_MAX_SIZE / (double)Math.Max(o.OutHeight, o.OutWidth)) / Math.Log(0.5))); } BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.InSampleSize = scale; ins = ContentResolver.OpenInputStream(uri); Bitmap b = BitmapFactory.DecodeStream(ins, null, o2); ins.Close(); return b; } catch (Exception e) { Log.Error(GetType().Name, e.Message); } return null; } private void OnSaveClicked() { // TODO this code needs to change to use the decode/crop/encode single // step api so that we don't require that the whole (possibly large) // bitmap doesn't have to be read into memory if (Saving) { return; } Saving = true; var r = Crop.CropRect; int width = r.Width(); int height = r.Height(); Bitmap croppedImage = Bitmap.CreateBitmap(width, height, Bitmap.Config.Rgb565); { Canvas canvas = new Canvas(croppedImage); Rect dstRect = new Rect(0, 0, width, height); canvas.DrawBitmap(bitmap, r, dstRect, null); } // If the output is required to a specific size then scale or fill if (outputX != 0 && outputY != 0) { if (scale) { // Scale the image to the required dimensions Bitmap old = croppedImage; croppedImage = Util.transform(new Matrix(), croppedImage, outputX, outputY, scaleUp); if (old != croppedImage) { old.Recycle(); } } else { // Don't scale the image crop it to the size requested. // Create an new image with the cropped image in the center and // the extra space filled. Bitmap b = Bitmap.CreateBitmap(outputX, outputY, Bitmap.Config.Rgb565); Canvas canvas = new Canvas(b); Rect srcRect = Crop.CropRect; Rect dstRect = new Rect(0, 0, outputX, outputY); int dx = (srcRect.Width() - dstRect.Width()) / 2; int dy = (srcRect.Height() - dstRect.Height()) / 2; // If the srcRect is too big, use the center part of it. srcRect.Inset(Math.Max(0, dx), Math.Max(0, dy)); // If the dstRect is too big, use the center part of it. dstRect.Inset(Math.Max(0, -dx), Math.Max(0, -dy)); // Draw the cropped bitmap in the center canvas.DrawBitmap(bitmap, srcRect, dstRect, null); // Set the cropped bitmap as the new bitmap croppedImage.Recycle(); croppedImage = b; } } // Return the cropped image directly or save it to the specified URI. Bundle myExtras = Intent.Extras; if (myExtras != null && (myExtras.GetParcelable("data") != null || myExtras.GetBoolean("return-data"))) { Bundle extras = new Bundle(); extras.PutParcelable("data", croppedImage); SetResult(Result.Ok, (new Intent()).SetAction("inline-data").PutExtras(extras)); CropImageServiceAndroid.SetResult(new CropResult(true) { FilePath = saveUri.Path, Message = "Image cropped successfully" }); Finish(); } else { Bitmap b = croppedImage; BackgroundJob.StartBackgroundJob(this, null, "Saving image", () => SaveOutput(b), mHandler); } } private void SaveOutput(Bitmap croppedImage) { if (saveUri != null) { try { using (var outputStream = ContentResolver.OpenOutputStream(saveUri)) { if (outputStream != null) { croppedImage.Compress(outputFormat, 75, outputStream); } } } catch (Exception ex) { Log.Error(this.GetType().Name, ex.Message); } Bundle extras = new Bundle(); SetResult(Result.Ok, new Intent(saveUri.ToString()) .PutExtras(extras)); CropImageServiceAndroid.SetResult(new CropResult(true) { FilePath = saveUri.Path, Message = "Image cropped successfully" }); } else { Log.Error(this.GetType().Name, "not defined image url"); } croppedImage.Recycle(); Finish(); } private static void showStorageToast(Activity activity) { showStorageToast(activity, calculatePicturesRemaining()); } private static void showStorageToast(Activity activity, int remaining) { string noStorageText = null; if (remaining == NO_STORAGE_ERROR) { String state = Android.OS.Environment.ExternalStorageState; if (state == Android.OS.Environment.MediaChecking) { noStorageText = "Preparing card"; } else { noStorageText = "No storage card"; } } else if (remaining < 1) { noStorageText = "Not enough space"; } if (noStorageText != null) { Toast.MakeText(activity, noStorageText, ToastLength.Long).Show(); } } private static int calculatePicturesRemaining() { try { string storageDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryPictures).ToString(); StatFs stat = new StatFs(storageDirectory); float remaining = ((float)stat.AvailableBlocks * (float)stat.BlockSize) / 400000F; return (int)remaining; } catch (Exception) { // if we can't stat the filesystem then we don't know how many // pictures are remaining. it might be zero but just leave it // blank since we really don't know. return CANNOT_STAT_ERROR; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading.Tasks; using System.Xml; using Microsoft.Build.BackEnd; using Microsoft.Build.BackEnd.SdkResolution; using Microsoft.Build.Collections; using Microsoft.Build.Engine.UnitTests.BackEnd; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using ElementLocation = Microsoft.Build.Construction.ElementLocation; using ILoggingService = Microsoft.Build.BackEnd.Logging.ILoggingService; using LegacyThreadingData = Microsoft.Build.Execution.LegacyThreadingData; using Shouldly; using Xunit; using Xunit.Abstractions; namespace Microsoft.Build.UnitTests.BackEnd { /// <summary> /// Unit tests for the TaskBuilder component /// </summary> public class TaskBuilder_Tests : ITargetBuilderCallback { /// <summary> /// The mock component host and logger /// </summary> private MockHost _host; private readonly ITestOutputHelper _testOutput; /// <summary> /// The temporary project we use to run the test /// </summary> private ProjectInstance _testProject; /// <summary> /// Prepares the environment for the test. /// </summary> public TaskBuilder_Tests(ITestOutputHelper output) { _host = new MockHost(); _testOutput = output; _testProject = CreateTestProject(); } /********************************************************************************* * * OUTPUT PARAMS * *********************************************************************************/ /// <summary> /// Verifies that we do look up the task during execute when the condition is true. /// </summary> [Fact] public void TasksAreDiscoveredWhenTaskConditionTrue() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <NonExistantTask Condition=""'1'=='1'""/> <Message Text='Made it'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t", loggers); logger.AssertLogContains("MSB4036"); logger.AssertLogDoesntContain("Made it"); } /// <summary> /// Tests that when the task condition is false, Execute still returns true even though we never loaded /// the task. We verify that we never loaded the task because if we did try, the task load itself would /// have failed, resulting in an error. /// </summary> [Fact] public void TasksNotDiscoveredWhenTaskConditionFalse() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <NonExistantTask Condition=""'1'=='2'""/> <Message Text='Made it'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t", loggers); logger.AssertLogContains("Made it"); } /// <summary> /// Verify when task outputs are overridden the override messages are correctly displayed /// </summary> [Fact] public void OverridePropertiesInCreateProperty() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <EmbeddedResource Include='a.resx'> <LogicalName>foo</LogicalName> </EmbeddedResource> <EmbeddedResource Include='b.resx'> <LogicalName>bar</LogicalName> </EmbeddedResource> <EmbeddedResource Include='c.resx'> <LogicalName>barz</LogicalName> </EmbeddedResource> </ItemGroup> <Target Name='t'> <CreateProperty Value=""@(EmbeddedResource->'/assemblyresource:%(Identity),%(LogicalName)', ' ')"" Condition=""'%(LogicalName)' != '' ""> <Output TaskParameter=""Value"" PropertyName=""LinkSwitches""/> </CreateProperty> <Message Text='final:[$(LinkSwitches)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t", loggers); logger.AssertLogContains(new string[] { "final:[/assemblyresource:c.resx,barz]" }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TaskStarted", "CreateProperty") }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:a.resx,foo", "/assemblyresource:b.resx,bar") }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:b.resx,bar", "/assemblyresource:c.resx,barz") }); } /// <summary> /// Verify that when a task outputs are inferred the override messages are displayed /// </summary> [Fact] public void OverridePropertiesInInferredCreateProperty() { string[] files = null; try { files = ObjectModelHelpers.GetTempFiles(2, new DateTime(2005, 1, 1)); MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <i Include='" + files[0] + "'><output>" + files[1] + @"</output></i> </ItemGroup> <ItemGroup> <EmbeddedResource Include='a.resx'> <LogicalName>foo</LogicalName> </EmbeddedResource> <EmbeddedResource Include='b.resx'> <LogicalName>bar</LogicalName> </EmbeddedResource> <EmbeddedResource Include='c.resx'> <LogicalName>barz</LogicalName> </EmbeddedResource> </ItemGroup> <Target Name='t2' DependsOnTargets='t'> <Message Text='final:[$(LinkSwitches)]'/> </Target> <Target Name='t' Inputs='%(i.Identity)' Outputs='%(i.Output)'> <Message Text='start:[Hello]'/> <CreateProperty Value=""@(EmbeddedResource->'/assemblyresource:%(Identity),%(LogicalName)', ' ')"" Condition=""'%(LogicalName)' != '' ""> <Output TaskParameter=""Value"" PropertyName=""LinkSwitches""/> </CreateProperty> <Message Text='end:[hello]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t2", loggers); // We should only see messages from the second target, as the first is only inferred logger.AssertLogDoesntContain("start:"); logger.AssertLogDoesntContain("end:"); logger.AssertLogContains(new string[] { "final:[/assemblyresource:c.resx,barz]" }); logger.AssertLogDoesntContain(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TaskStarted", "CreateProperty")); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:a.resx,foo", "/assemblyresource:b.resx,bar") }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:b.resx,bar", "/assemblyresource:c.resx,barz") }); } finally { ObjectModelHelpers.DeleteTempFiles(files); } } /// <summary> /// Tests that tasks batch on outputs correctly. /// </summary> [Fact] public void TaskOutputBatching() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <TaskParameterItem Include=""foo""> <ParameterName>Value</ParameterName> <ParameterName2>Include</ParameterName2> <PropertyName>MetadataProperty</PropertyName> <ItemType>MetadataItem</ItemType> </TaskParameterItem> </ItemGroup> <Target Name='Build'> <CreateProperty Value=""@(TaskParameterItem)""> <Output TaskParameter=""Value"" PropertyName=""Property1""/> </CreateProperty> <Message Text='Property1=[$(Property1)]' /> <CreateProperty Value=""@(TaskParameterItem)""> <Output TaskParameter=""%(TaskParameterItem.ParameterName)"" PropertyName=""Property2""/> </CreateProperty> <Message Text='Property2=[$(Property2)]' /> <CreateProperty Value=""@(TaskParameterItem)""> <Output TaskParameter=""Value"" PropertyName=""%(TaskParameterItem.PropertyName)""/> </CreateProperty> <Message Text='MetadataProperty=[$(MetadataProperty)]' /> <CreateItem Include=""@(TaskParameterItem)""> <Output TaskParameter=""Include"" ItemName=""TestItem1""/> </CreateItem> <Message Text='TestItem1=[@(TestItem1)]' /> <CreateItem Include=""@(TaskParameterItem)""> <Output TaskParameter=""%(TaskParameterItem.ParameterName2)"" ItemName=""TestItem2""/> </CreateItem> <Message Text='TestItem2=[@(TestItem2)]' /> <CreateItem Include=""@(TaskParameterItem)""> <Output TaskParameter=""Include"" ItemName=""%(TaskParameterItem.ItemType)""/> </CreateItem> <Message Text='MetadataItem=[@(MetadataItem)]' /> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build(loggers); logger.AssertLogContains("Property1=[foo]"); logger.AssertLogContains("Property2=[foo]"); logger.AssertLogContains("MetadataProperty=[foo]"); logger.AssertLogContains("TestItem1=[foo]"); logger.AssertLogContains("TestItem2=[foo]"); logger.AssertLogContains("MetadataItem=[foo]"); } /// <summary> /// MSbuildLastTaskResult property contains true or false indicating /// the success or failure of the last task. /// </summary> [Fact] public void MSBuildLastTaskResult() { string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project DefaultTargets='t2' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <Message Text='[start:$(MSBuildLastTaskResult)]'/> <!-- Should be blank --> <Warning Text='warning'/> <Message Text='[0:$(MSBuildLastTaskResult)]'/> <!-- Should be true, only a warning--> <!-- task's Execute returns false --> <Copy SourceFiles='|' DestinationFolder='c:\' ContinueOnError='true' /> <PropertyGroup> <p>$(MSBuildLastTaskResult)</p> </PropertyGroup> <Message Text='[1:$(MSBuildLastTaskResult)]'/> <!-- Should be false: propertygroup did not reset it --> <Message Text='[p:$(p)]'/> <!-- Should be false as stored earlier --> <Message Text='[2:$(MSBuildLastTaskResult)]'/> <!-- Message succeeded, should now be true --> </Target> <Target Name='t2' DependsOnTargets='t'> <Message Text='[3:$(MSBuildLastTaskResult)]'/> <!-- Should still have true --> <!-- check Error task as well --> <Error Text='error' ContinueOnError='true' /> <Message Text='[4:$(MSBuildLastTaskResult)]'/> <!-- Should be false --> <!-- trigger OnError target, ContinueOnError is false --> <Error Text='error2'/> <OnError ExecuteTargets='t3'/> </Target> <Target Name='t3' > <Message Text='[5:$(MSBuildLastTaskResult)]'/> <!-- Should be false --> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); MockLogger logger = new MockLogger(); loggers.Add(logger); project.Build("t2", loggers); logger.AssertLogContains("[start:]"); logger.AssertLogContains("[0:true]"); logger.AssertLogContains("[1:false]"); logger.AssertLogContains("[p:false]"); logger.AssertLogContains("[2:true]"); logger.AssertLogContains("[3:true]"); logger.AssertLogContains("[4:false]"); logger.AssertLogContains("[4:false]"); } /// <summary> /// Verifies that we can add "recursivedir" built-in metadata as target outputs. /// This is to support wildcards in CreateItem. Allowing anything /// else could let the item get corrupt (inconsistent values for Filename and FullPath, for example) /// </summary> [Fact] public void TasksCanAddRecursiveDirBuiltInMetadata() { MockLogger logger = new MockLogger(this._testOutput); string projectFileContents = ObjectModelHelpers.CleanupFileContents($@" <Project> <Target Name='t'> <CreateItem Include='{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\**\*.dll'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> <Message Text='@(x)'/> <Message Text='[%(x.RecursiveDir)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); project.Build("t", new[] { logger }).ShouldBeTrue(); // Assuming the current directory of the test .dll has at least one subfolder // such as Roslyn, the log will contain [Roslyn\] (or [Roslyn/] on Unix) string slashAndBracket = Path.DirectorySeparatorChar.ToString() + "]"; logger.AssertLogContains(slashAndBracket); logger.AssertLogDoesntContain("MSB4118"); logger.AssertLogDoesntContain("MSB3031"); } /// <summary> /// Verify CreateItem prevents adding any built-in metadata explicitly, even recursivedir. /// </summary> [Fact] public void OtherBuiltInMetadataErrors() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <CreateItem Include='Foo' AdditionalMetadata='RecursiveDir=1'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.False(result); logger.AssertLogContains("MSB3031"); } /// <summary> /// Verify CreateItem prevents adding any built-in metadata explicitly, even recursivedir. /// </summary> [Fact] public void OtherBuiltInMetadataErrors2() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <CreateItem Include='Foo' AdditionalMetadata='Extension=1'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.False(result); logger.AssertLogContains("MSB3031"); } /// <summary> /// Verify that properties can be passed in to a task and out as items, despite the /// built-in metadata restrictions. /// </summary> [Fact] public void PropertiesInItemsOutOfTask() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <PropertyGroup> <p>c:\a.ext</p> </PropertyGroup> <CreateItem Include='$(p)'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> <Message Text='[%(x.Extension)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.True(result); logger.AssertLogContains("[.ext]"); } /// <summary> /// Verify that properties can be passed in to a task and out as items, despite /// having illegal characters for a file name /// </summary> [Fact] public void IllegalFileCharsInItemsOutOfTask() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <PropertyGroup> <p>||illegal||</p> </PropertyGroup> <CreateItem Include='$(p)'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> <Message Text='[@(x)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.True(result); logger.AssertLogContains("[||illegal||]"); } /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void NullMetadataOnOutputItems() { string customTaskPath = Assembly.GetExecutingAssembly().Location; string projectContents = @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <UsingTask TaskName=`NullMetadataTask` AssemblyFile=`" + customTaskPath + @"` /> <Target Name=`Build`> <NullMetadataTask> <Output TaskParameter=`OutputItems` ItemName=`Outputs`/> </NullMetadataTask> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput); logger.AssertLogContains("[foo: ]"); } /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void NullMetadataOnLegacyOutputItems() { string customTaskPath = Assembly.GetExecutingAssembly().Location; string projectContents = @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <UsingTask TaskName=`NullMetadataTask` AssemblyFile=`" + customTaskPath + @"` /> <Target Name=`Build`> <NullMetadataTask> <Output TaskParameter=`OutputItems` ItemName=`Outputs`/> </NullMetadataTask> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput); logger.AssertLogContains("[foo: ]"); } /// <summary> /// Regression test for https://github.com/microsoft/msbuild/issues/5080 /// </summary> [Fact] public void SameAssemblyFromDifferentRelativePathsSharesAssemblyLoadContext() { string realTaskPath = Assembly.GetExecutingAssembly().Location; string fileName = Path.GetFileName(realTaskPath); string directoryName = Path.GetDirectoryName(realTaskPath); using var env = TestEnvironment.Create(); string customTaskFolder = Path.Combine(directoryName, "buildCrossTargeting"); env.CreateFolder(customTaskFolder); string projectContents = @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <UsingTask TaskName=`RegisterObject` AssemblyFile=`" + Path.Combine(customTaskFolder, "..", fileName) + @"` /> <UsingTask TaskName=`RetrieveObject` AssemblyFile=`" + realTaskPath + @"` /> <Target Name=`Build`> <RegisterObject /> <RetrieveObject /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput); logger.AssertLogDoesntContain("MSB4018"); } #if FEATURE_CODETASKFACTORY /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] public void NullMetadataOnOutputItems_InlineTask() { string projectContents = @" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`NullMetadataTask_v12` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <OutputItems ParameterType=`Microsoft.Build.Framework.ITaskItem[]` Output=`true` /> </ParameterGroup> <Task> <Code> <![CDATA[ OutputItems = new ITaskItem[1]; IDictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add(`a`, null); OutputItems[0] = new TaskItem(`foo`, (IDictionary)metadata); return true; ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <NullMetadataTask_v12> <Output TaskParameter=`OutputItems` ItemName=`Outputs` /> </NullMetadataTask_v12> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput); logger.AssertLogContains("[foo: ]"); } /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact(Skip = "https://github.com/dotnet/msbuild/issues/6521")] [Trait("Category", "non-mono-tests")] public void NullMetadataOnLegacyOutputItems_InlineTask() { string projectContents = @" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`NullMetadataTask_v4` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildFrameworkToolsPath)\Microsoft.Build.Tasks.v4.0.dll`> <ParameterGroup> <OutputItems ParameterType=`Microsoft.Build.Framework.ITaskItem[]` Output=`true` /> </ParameterGroup> <Task> <Code> <![CDATA[ OutputItems = new ITaskItem[1]; IDictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add(`a`, null); OutputItems[0] = new TaskItem(`foo`, (IDictionary)metadata); return true; ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <NullMetadataTask_v4> <Output TaskParameter=`OutputItems` ItemName=`Outputs` /> </NullMetadataTask_v4> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput); logger.AssertLogContains("[foo: ]"); } #endif /// <summary> /// Validates that the defining project metadata is set (or not set) as expected in /// various task output-related operations, using a task built against the current /// version of MSBuild. /// </summary> [Fact] public void ValidateDefiningProjectMetadataOnTaskOutputs() { string customTaskPath = Assembly.GetExecutingAssembly().Location; ValidateDefiningProjectMetadataOnTaskOutputsHelper(customTaskPath); } /// <summary> /// Validates that the defining project metadata is set (or not set) as expected in /// various task output-related operations, using a task built against V4 MSBuild, /// which didn't support the defining project metadata. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void ValidateDefiningProjectMetadataOnTaskOutputs_LegacyItems() { string customTaskPath = Assembly.GetExecutingAssembly().Location; ValidateDefiningProjectMetadataOnTaskOutputsHelper(customTaskPath); } #if FEATURE_APARTMENT_STATE /// <summary> /// Tests that putting the RunInSTA attribute on a task causes it to run in the STA thread. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadRequired() { TestSTATask(true, false, false); } /// <summary> /// Tests an STA task with an exception /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadRequiredWithException() { TestSTATask(true, false, true); } /// <summary> /// Tests an STA task with failure. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadRequiredWithFailure() { TestSTATask(true, true, false); } /// <summary> /// Tests an MTA task. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadNotRequired() { TestSTATask(false, false, false); } /// <summary> /// Tests an MTA task with an exception. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadNotRequiredWithException() { TestSTATask(false, false, true); } /// <summary> /// Tests an MTA task with failure. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadNotRequiredWithFailure() { TestSTATask(false, true, false); } #endif #region ITargetBuilderCallback Members /// <summary> /// Empty impl /// </summary> Task<ITargetResult[]> ITargetBuilderCallback.LegacyCallTarget(string[] targets, bool continueOnError, ElementLocation referenceLocation) { throw new NotImplementedException(); } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.Yield() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.Reacquire() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.EnterMSBuildCallbackState() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.ExitMSBuildCallbackState() { } /// <summary> /// Empty impl /// </summary> int IRequestBuilderCallback.RequestCores(object monitorLockObject, int requestedCores, bool waitForCores) { return 0; } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.ReleaseCores(int coresToRelease) { } #endregion #region IRequestBuilderCallback Members /// <summary> /// Empty impl /// </summary> Task<BuildResult[]> IRequestBuilderCallback.BuildProjects(string[] projectFiles, PropertyDictionary<ProjectPropertyInstance>[] properties, string[] toolsVersions, string[] targets, bool waitForResults, bool skipNonexistentTargets) { throw new NotImplementedException(); } /// <summary> /// Not implemented. /// </summary> Task IRequestBuilderCallback.BlockOnTargetInProgress(int blockingRequestId, string blockingTarget, BuildResult partialBuildResult) { throw new NotImplementedException(); } #endregion /********************************************************************************* * * Helpers * *********************************************************************************/ /// <summary> /// Helper method for validating the setting of defining project metadata on items /// coming from task outputs /// </summary> private void ValidateDefiningProjectMetadataOnTaskOutputsHelper(string customTaskPath) { string projectAPath = Path.Combine(ObjectModelHelpers.TempProjectDir, "a.proj"); string projectBPath = Path.Combine(ObjectModelHelpers.TempProjectDir, "b.proj"); string projectAContents = @" <Project xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`> <UsingTask TaskName=`ItemCreationTask` AssemblyFile=`" + customTaskPath + @"` /> <Import Project=`b.proj` /> <Target Name=`Run`> <ItemCreationTask InputItemsToPassThrough=`@(PassThrough)` InputItemsToCopy=`@(Copy)`> <Output TaskParameter=`OutputString` ItemName=`A` /> <Output TaskParameter=`PassedThroughOutputItems` ItemName=`B` /> <Output TaskParameter=`CreatedOutputItems` ItemName=`C` /> <Output TaskParameter=`CopiedOutputItems` ItemName=`D` /> </ItemCreationTask> <Warning Text=`A is wrong: EXPECTED: [a] ACTUAL: [%(A.DefiningProjectName)]` Condition=`'%(A.DefiningProjectName)' != 'a'` /> <Warning Text=`B is wrong: EXPECTED: [a] ACTUAL: [%(B.DefiningProjectName)]` Condition=`'%(B.DefiningProjectName)' != 'a'` /> <Warning Text=`C is wrong: EXPECTED: [a] ACTUAL: [%(C.DefiningProjectName)]` Condition=`'%(C.DefiningProjectName)' != 'a'` /> <Warning Text=`D is wrong: EXPECTED: [a] ACTUAL: [%(D.DefiningProjectName)]` Condition=`'%(D.DefiningProjectName)' != 'a'` /> </Target> </Project> "; string projectBContents = @" <Project xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`> <ItemGroup> <PassThrough Include=`aaa.cs` /> <Copy Include=`bbb.cs` /> </ItemGroup> </Project> "; try { File.WriteAllText(projectAPath, ObjectModelHelpers.CleanupFileContents(projectAContents)); File.WriteAllText(projectBPath, ObjectModelHelpers.CleanupFileContents(projectBContents)); MockLogger logger = new MockLogger(_testOutput); ObjectModelHelpers.BuildTempProjectFileExpectSuccess("a.proj", logger); logger.AssertNoWarnings(); } finally { if (File.Exists(projectAPath)) { File.Delete(projectAPath); } if (File.Exists(projectBPath)) { File.Delete(projectBPath); } } } #if FEATURE_APARTMENT_STATE /// <summary> /// Executes an STA task test. /// </summary> private void TestSTATask(bool requireSTA, bool failTask, bool throwException) { MockLogger logger = new MockLogger(); logger.AllowTaskCrashes = throwException; string taskAssemblyName; Project project = CreateSTATestProject(requireSTA, failTask, throwException, out taskAssemblyName); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); BuildParameters parameters = new BuildParameters(); parameters.Loggers = new ILogger[] { logger }; BuildResult result = BuildManager.DefaultBuildManager.Build(parameters, new BuildRequestData(project.CreateProjectInstance(), new string[] { "Foo" })); if (requireSTA) { logger.AssertLogContains("STA"); } else { logger.AssertLogContains("MTA"); } if (throwException) { logger.AssertLogContains("EXCEPTION"); Assert.Equal(BuildResultCode.Failure, result.OverallResult); return; } else { logger.AssertLogDoesntContain("EXCEPTION"); } if (failTask) { logger.AssertLogContains("FAIL"); Assert.Equal(BuildResultCode.Failure, result.OverallResult); } else { logger.AssertLogDoesntContain("FAIL"); } if (!throwException && !failTask) { Assert.Equal(BuildResultCode.Success, result.OverallResult); } } /// <summary> /// Helper to create a project which invokes the STA helper task. /// </summary> private Project CreateSTATestProject(bool requireSTA, bool failTask, bool throwException, out string assemblyToDelete) { assemblyToDelete = GenerateSTATask(requireSTA); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <UsingTask TaskName='ThreadTask' AssemblyFile='" + assemblyToDelete + @"'/> <Target Name='Foo'> <ThreadTask Fail='" + failTask + @"' ThrowException='" + throwException + @"'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); return project; } #endif /// <summary> /// Helper to create the STA test task. /// </summary> private string GenerateSTATask(bool requireSTA) { string taskContents = @" using System; using Microsoft.Build.Framework; namespace ClassLibrary2 {" + (requireSTA ? "[RunInSTA]" : String.Empty) + @" public class ThreadTask : ITask { #region ITask Members public IBuildEngine BuildEngine { get; set; } public bool ThrowException { get; set; } public bool Fail { get; set; } public bool Execute() { string message; if (System.Threading.Thread.CurrentThread.GetApartmentState() == System.Threading.ApartmentState.STA) { message = ""STA""; } else { message = ""MTA""; } BuildEngine.LogMessageEvent(new BuildMessageEventArgs(message, """", ""ThreadTask"", MessageImportance.High)); if (ThrowException) { throw new InvalidOperationException(""EXCEPTION""); } if (Fail) { BuildEngine.LogMessageEvent(new BuildMessageEventArgs(""FAIL"", """", ""ThreadTask"", MessageImportance.High)); } return !Fail; } public ITaskHost HostObject { get; set; } #endregion } }"; return CustomTaskHelper.GetAssemblyForTask(taskContents); } /// <summary> /// Creates a test project. /// </summary> /// <returns>The project.</returns> private ProjectInstance CreateTestProject() { string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <Compile Include='b.cs' /> <Compile Include='c.cs' /> </ItemGroup> <ItemGroup> <Reference Include='System' /> </ItemGroup> <Target Name='Empty' /> <Target Name='Skip' Inputs='testProject.proj' Outputs='testProject.proj' /> <Target Name='Error' > <ErrorTask1 ContinueOnError='True'/> <ErrorTask2 ContinueOnError='False'/> <ErrorTask3 /> <OnError ExecuteTargets='Foo'/> <OnError ExecuteTargets='Bar'/> </Target> <Target Name='Foo' Inputs='foo.cpp' Outputs='foo.o'> <FooTask1/> </Target> <Target Name='Bar'> <BarTask1/> </Target> <Target Name='Baz' DependsOnTargets='Bar'> <BazTask1/> <BazTask2/> </Target> <Target Name='Baz2' DependsOnTargets='Bar;Foo'> <Baz2Task1/> <Baz2Task2/> <Baz2Task3/> </Target> <Target Name='DepSkip' DependsOnTargets='Skip'> <DepSkipTask1/> <DepSkipTask2/> <DepSkipTask3/> </Target> <Target Name='DepError' DependsOnTargets='Foo;Skip;Error'> <DepSkipTask1/> <DepSkipTask2/> <DepSkipTask3/> </Target> </Project> "); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestConfiguration config = new BuildRequestConfiguration(1, new BuildRequestData("testfile", new Dictionary<string, string>(), "3.5", new string[0], null), "2.0"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); config.Project = project.CreateProjectInstance(); cache.AddConfiguration(config); return config.Project; } /// <summary> /// The mock component host object. /// </summary> private class MockHost : MockLoggingService, IBuildComponentHost, IBuildComponent { #region IBuildComponentHost Members /// <summary> /// The config cache /// </summary> private IConfigCache _configCache; /// <summary> /// The logging service /// </summary> private ILoggingService _loggingService; /// <summary> /// The results cache /// </summary> private IResultsCache _resultsCache; /// <summary> /// The request builder /// </summary> private IRequestBuilder _requestBuilder; /// <summary> /// The target builder /// </summary> private ITargetBuilder _targetBuilder; /// <summary> /// The build parameters. /// </summary> private BuildParameters _buildParameters; /// <summary> /// Retrieves the LegacyThreadingData associated with a particular component host /// </summary> private LegacyThreadingData _legacyThreadingData; private ISdkResolverService _sdkResolverService; /// <summary> /// Constructor /// /// UNDONE: Refactor this, and the other MockHosts, to use a common base implementation. The duplication of the /// logging implementation alone is unfortunate. /// </summary> public MockHost() { _buildParameters = new BuildParameters(); _legacyThreadingData = new LegacyThreadingData(); _configCache = new ConfigCache(); ((IBuildComponent)_configCache).InitializeComponent(this); _loggingService = this; _resultsCache = new ResultsCache(); ((IBuildComponent)_resultsCache).InitializeComponent(this); _requestBuilder = new RequestBuilder(); ((IBuildComponent)_requestBuilder).InitializeComponent(this); _targetBuilder = new TargetBuilder(); ((IBuildComponent)_targetBuilder).InitializeComponent(this); _sdkResolverService = new MockSdkResolverService(); ((IBuildComponent)_sdkResolverService).InitializeComponent(this); } /// <summary> /// Returns the node logging service. We don't distinguish here. /// </summary> public ILoggingService LoggingService { get { return _loggingService; } } /// <summary> /// Retrieves the name of the host. /// </summary> public string Name { get { return "TaskBuilder_Tests.MockHost"; } } /// <summary> /// Returns the build parameters. /// </summary> public BuildParameters BuildParameters { get { return _buildParameters; } } /// <summary> /// Retrieves the LegacyThreadingData associated with a particular component host /// </summary> LegacyThreadingData IBuildComponentHost.LegacyThreadingData { get { return _legacyThreadingData; } } /// <summary> /// Constructs and returns a component of the specified type. /// </summary> /// <param name="type">The type of component to return</param> /// <returns>The component</returns> public IBuildComponent GetComponent(BuildComponentType type) { return type switch { BuildComponentType.ConfigCache => (IBuildComponent)_configCache, BuildComponentType.LoggingService => (IBuildComponent)_loggingService, BuildComponentType.ResultsCache => (IBuildComponent)_resultsCache, BuildComponentType.RequestBuilder => (IBuildComponent)_requestBuilder, BuildComponentType.TargetBuilder => (IBuildComponent)_targetBuilder, BuildComponentType.SdkResolverService => (IBuildComponent)_sdkResolverService, _ => throw new ArgumentException("Unexpected type " + type), }; } /// <summary> /// Register a component factory. /// </summary> public void RegisterFactory(BuildComponentType type, BuildComponentFactoryDelegate factory) { } #endregion #region IBuildComponent Members /// <summary> /// Sets the component host /// </summary> /// <param name="host">The component host</param> public void InitializeComponent(IBuildComponentHost host) { throw new NotImplementedException(); } /// <summary> /// Shuts down the component /// </summary> public void ShutdownComponent() { throw new NotImplementedException(); } #endregion } } }
using System.IO; using GitTools.Testing; using GitVersion; using GitVersion.Logging; using GitVersion.Model; using GitVersionCore.Tests.Helpers; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using Shouldly; using Environment = System.Environment; namespace GitVersionExe.Tests { [TestFixture] public class ArgumentParserTests : TestBase { private IEnvironment environment; private IArgumentParser argumentParser; [SetUp] public void SetUp() { var sp = ConfigureServices(services => { services.AddSingleton<IArgumentParser, ArgumentParser>(); services.AddSingleton<IGlobbingResolver, GlobbingResolver>(); }); environment = sp.GetService<IEnvironment>(); argumentParser = sp.GetService<IArgumentParser>(); } [Test] public void EmptyMeansUseCurrentDirectory() { var arguments = argumentParser.ParseArguments(""); arguments.TargetPath.ShouldBe(Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); } [Test] public void SingleMeansUseAsTargetDirectory() { var arguments = argumentParser.ParseArguments("path"); arguments.TargetPath.ShouldBe("path"); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); } [Test] public void NoPathAndLogfileShouldUseCurrentDirectoryTargetDirectory() { var arguments = argumentParser.ParseArguments("-l logFilePath"); arguments.TargetPath.ShouldBe(Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); } [Test] public void HelpSwitchTest() { var arguments = argumentParser.ParseArguments("-h"); Assert.IsNull(arguments.TargetPath); Assert.IsNull(arguments.LogFilePath); arguments.IsHelp.ShouldBe(true); } [Test] public void VersionSwitchTest() { var arguments = argumentParser.ParseArguments("-version"); Assert.IsNull(arguments.TargetPath); Assert.IsNull(arguments.LogFilePath); arguments.IsVersion.ShouldBe(true); } [Test] public void TargetDirectoryAndLogFilePathCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -l logFilePath"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); } [Test] public void UsernameAndPasswordCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -u [username] -p [password]"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.Authentication.Username.ShouldBe("[username]"); arguments.Authentication.Password.ShouldBe("[password]"); arguments.IsHelp.ShouldBe(false); } [Test] public void UnknownOutputShouldThrow() { var exception = Assert.Throws<WarningException>(() => argumentParser.ParseArguments("targetDirectoryPath -output invalid_value")); exception.Message.ShouldBe("Value 'invalid_value' cannot be parsed as output type, please use 'json', 'file' or 'buildserver'"); } [Test] public void OutputDefaultsToJson() { var arguments = argumentParser.ParseArguments("targetDirectoryPath"); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.File); } [Test] public void OutputJsonCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output json"); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.File); } [Test] public void MultipleOutputJsonCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output json -output json"); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.File); } [Test] public void OutputBuildserverCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver"); arguments.Output.ShouldContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.File); } [Test] public void MultipleOutputBuildserverCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver -output buildserver"); arguments.Output.ShouldContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.File); } [Test] public void OutputFileCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output file"); arguments.Output.ShouldContain(OutputType.File); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.Json); } [Test] public void MultipleOutputFileCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output file -output file"); arguments.Output.ShouldContain(OutputType.File); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.Json); } [Test] public void OutputBuildserverAndJsonCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver -output json"); arguments.Output.ShouldContain(OutputType.BuildServer); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.File); } [Test] public void OutputBuildserverAndJsonAndFileCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver -output json -output file"); arguments.Output.ShouldContain(OutputType.BuildServer); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldContain(OutputType.File); } [Test] public void MultipleArgsAndFlag() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver -updateAssemblyInfo"); arguments.Output.ShouldContain(OutputType.BuildServer); } [TestCase("-output file", "GitVersion.json")] [TestCase("-output file -outputfile version.json", "version.json")] public void OutputFileArgumentCanBeParsed(string args, string outputFile) { var arguments = argumentParser.ParseArguments(args); arguments.Output.ShouldContain(OutputType.File); arguments.OutputFile.ShouldBe(outputFile); } [Test] public void UrlAndBranchNameCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -url http://github.com/Particular/GitVersion.git -b somebranch"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.TargetUrl.ShouldBe("http://github.com/Particular/GitVersion.git"); arguments.TargetBranch.ShouldBe("somebranch"); arguments.IsHelp.ShouldBe(false); } [Test] public void WrongNumberOfArgumentsShouldThrow() { var exception = Assert.Throws<WarningException>(() => argumentParser.ParseArguments("targetDirectoryPath -l logFilePath extraArg")); exception.Message.ShouldBe("Could not parse command line parameter 'extraArg'."); } [TestCase("targetDirectoryPath -x logFilePath")] [TestCase("/invalid-argument")] public void UnknownArgumentsShouldThrow(string arguments) { var exception = Assert.Throws<WarningException>(() => argumentParser.ParseArguments(arguments)); exception.Message.ShouldStartWith("Could not parse command line parameter"); } [TestCase("-updateAssemblyInfo true")] [TestCase("-updateAssemblyInfo 1")] [TestCase("-updateAssemblyInfo")] [TestCase("-updateAssemblyInfo assemblyInfo.cs")] [TestCase("-updateAssemblyInfo assemblyInfo.cs -ensureassemblyinfo")] [TestCase("-updateAssemblyInfo assemblyInfo.cs otherAssemblyInfo.cs")] [TestCase("-updateAssemblyInfo Assembly.cs Assembly.cs -ensureassemblyinfo")] public void UpdateAssemblyInfoTrue(string command) { var arguments = argumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(true); } [TestCase("-updateProjectFiles assemblyInfo.csproj")] [TestCase("-updateProjectFiles assemblyInfo.csproj")] [TestCase("-updateProjectFiles assemblyInfo.csproj otherAssemblyInfo.fsproj")] [TestCase("-updateProjectFiles")] public void UpdateProjectTrue(string command) { var arguments = argumentParser.ParseArguments(command); arguments.UpdateProjectFiles.ShouldBe(true); } [TestCase("-updateAssemblyInfo false")] [TestCase("-updateAssemblyInfo 0")] public void UpdateAssemblyInfoFalse(string command) { var arguments = argumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(false); } [TestCase("-updateAssemblyInfo Assembly.cs Assembly1.cs -ensureassemblyinfo")] public void CreateMulitpleAssemblyInfoProtected(string command) { var exception = Assert.Throws<WarningException>(() => argumentParser.ParseArguments(command)); exception.Message.ShouldBe("Can't specify multiple assembly info files when using /ensureassemblyinfo switch, either use a single assembly info file or do not specify /ensureassemblyinfo and create assembly info files manually"); } [TestCase("-updateProjectFiles Assembly.csproj -ensureassemblyinfo")] public void UpdateProjectInfoWithEnsureAssemblyInfoProtected(string command) { var exception = Assert.Throws<WarningException>(() => argumentParser.ParseArguments(command)); exception.Message.ShouldBe("Cannot specify -ensureassemblyinfo with updateprojectfiles: please ensure your project file exists before attempting to update it"); } [Test] public void UpdateAssemblyInfoWithFilename() { using var repo = new EmptyRepositoryFixture(); var assemblyFile = Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); using var file = File.Create(assemblyFile); var arguments = argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(1); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); } [Test] public void UpdateAssemblyInfoWithMultipleFilenames() { using var repo = new EmptyRepositoryFixture(); var assemblyFile1 = Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); using var file = File.Create(assemblyFile1); var assemblyFile2 = Path.Combine(repo.RepositoryPath, "VersionAssemblyInfo.cs"); using var file2 = File.Create(assemblyFile2); var arguments = argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo CommonAssemblyInfo.cs VersionAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(2); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("VersionAssemblyInfo.cs")); } [Test] public void UpdateProjectFilesWithMultipleFilenames() { using var repo = new EmptyRepositoryFixture(); var assemblyFile1 = Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.csproj"); using var file = File.Create(assemblyFile1); var assemblyFile2 = Path.Combine(repo.RepositoryPath, "VersionAssemblyInfo.csproj"); using var file2 = File.Create(assemblyFile2); var arguments = argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateProjectFiles CommonAssemblyInfo.csproj VersionAssemblyInfo.csproj"); arguments.UpdateProjectFiles.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(2); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.csproj")); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("VersionAssemblyInfo.csproj")); } [Test] public void UpdateAssemblyInfoWithMultipleFilenamesMatchingGlobbing() { using var repo = new EmptyRepositoryFixture(); var assemblyFile1 = Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); using var file = File.Create(assemblyFile1); var assemblyFile2 = Path.Combine(repo.RepositoryPath, "VersionAssemblyInfo.cs"); using var file2 = File.Create(assemblyFile2); var subdir = Path.Combine(repo.RepositoryPath, "subdir"); Directory.CreateDirectory(subdir); var assemblyFile3 = Path.Combine(subdir, "LocalAssemblyInfo.cs"); using var file3 = File.Create(assemblyFile3); var arguments = argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo **/*AssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(3); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("VersionAssemblyInfo.cs")); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("LocalAssemblyInfo.cs")); } [Test] public void UpdateAssemblyInfoWithRelativeFilename() { using var repo = new EmptyRepositoryFixture(); var assemblyFile = Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); using var file = File.Create(assemblyFile); var targetPath = Path.Combine(repo.RepositoryPath, "subdir1", "subdir2"); Directory.CreateDirectory(targetPath); var arguments = argumentParser.ParseArguments($"-targetpath {targetPath} -updateAssemblyInfo ..\\..\\CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(1); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); } [Test] public void OverrideconfigWithNoOptions() { var arguments = argumentParser.ParseArguments("/overrideconfig"); arguments.OverrideConfig.ShouldBeNull(); } [Test] public void OverrideconfigWithSingleTagprefixOption() { var arguments = argumentParser.ParseArguments("/overrideconfig tag-prefix=sample"); arguments.OverrideConfig.TagPrefix.ShouldBe("sample"); } [TestCase("tag-prefix=sample;tag-prefix=other")] [TestCase("tag-prefix=sample;param2=other")] public void OverrideconfigWithSeveralOptions(string options) { var exception = Assert.Throws<WarningException>(() => argumentParser.ParseArguments($"/overrideconfig {options}")); exception.Message.ShouldContain("Can't specify multiple /overrideconfig options"); } [TestCase("tag-prefix=sample=asdf")] public void OverrideconfigWithInvalidOption(string options) { var exception = Assert.Throws<WarningException>(() => argumentParser.ParseArguments($"/overrideconfig {options}")); exception.Message.ShouldContain("Could not parse /overrideconfig option"); } [Test] public void EnsureAssemblyInfoTrueWhenFound() { var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo"); arguments.EnsureAssemblyInfo.ShouldBe(true); } [Test] public void EnsureAssemblyInfoTrue() { var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo true"); arguments.EnsureAssemblyInfo.ShouldBe(true); } [Test] public void EnsureAssemblyInfoFalse() { var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo false"); arguments.EnsureAssemblyInfo.ShouldBe(false); } [Test] public void DynamicRepoLocation() { var arguments = argumentParser.ParseArguments("-dynamicRepoLocation c:\\foo\\"); arguments.DynamicRepositoryClonePath.ShouldBe("c:\\foo\\"); } [Test] public void CanLogToConsole() { var arguments = argumentParser.ParseArguments("-l console"); arguments.LogFilePath.ShouldBe("console"); } [Test] public void NofetchTrueWhenDefined() { var arguments = argumentParser.ParseArguments("-nofetch"); arguments.NoFetch.ShouldBe(true); } [Test] public void NonormilizeTrueWhenDefined() { var arguments = argumentParser.ParseArguments("-nonormalize"); arguments.NoNormalize.ShouldBe(true); } [Test] public void OtherArgumentsCanBeParsedBeforeNofetch() { var arguments = argumentParser.ParseArguments("targetpath -nofetch "); arguments.TargetPath.ShouldBe("targetpath"); arguments.NoFetch.ShouldBe(true); } [Test] public void OtherArgumentsCanBeParsedBeforeNonormalize() { var arguments = argumentParser.ParseArguments("targetpath -nonormalize"); arguments.TargetPath.ShouldBe("targetpath"); arguments.NoNormalize.ShouldBe(true); } [Test] public void OtherArgumentsCanBeParsedBeforeNocache() { var arguments = argumentParser.ParseArguments("targetpath -nocache"); arguments.TargetPath.ShouldBe("targetpath"); arguments.NoCache.ShouldBe(true); } [TestCase("-nofetch -nonormalize -nocache")] [TestCase("-nofetch -nocache -nonormalize")] [TestCase("-nocache -nofetch -nonormalize")] [TestCase("-nocache -nonormalize -nofetch")] [TestCase("-nonormalize -nocache -nofetch")] [TestCase("-nonormalize -nofetch -nocache")] public void SeveralSwitchesCanBeParsed(string commandLineArgs) { var arguments = argumentParser.ParseArguments(commandLineArgs); arguments.NoCache.ShouldBe(true); arguments.NoNormalize.ShouldBe(true); arguments.NoFetch.ShouldBe(true); } [Test] public void LogPathCanContainForwardSlash() { var arguments = argumentParser.ParseArguments("-l /some/path"); arguments.LogFilePath.ShouldBe("/some/path"); } [Test] public void BooleanArgumentHandling() { var arguments = argumentParser.ParseArguments("/nofetch /updateassemblyinfo true"); arguments.NoFetch.ShouldBe(true); arguments.UpdateAssemblyInfo.ShouldBe(true); } [Test] public void NocacheTrueWhenDefined() { var arguments = argumentParser.ParseArguments("-nocache"); arguments.NoCache.ShouldBe(true); } [TestCase("-verbosity x", true, Verbosity.Normal)] [TestCase("-verbosity diagnostic", false, Verbosity.Diagnostic)] [TestCase("-verbosity Minimal", false, Verbosity.Minimal)] [TestCase("-verbosity NORMAL", false, Verbosity.Normal)] [TestCase("-verbosity quiet", false, Verbosity.Quiet)] [TestCase("-verbosity Verbose", false, Verbosity.Verbose)] public void CheckVerbosityParsing(string command, bool shouldThrow, Verbosity expectedVerbosity) { if (shouldThrow) { Assert.Throws<WarningException>(() => argumentParser.ParseArguments(command)); } else { var arguments = argumentParser.ParseArguments(command); arguments.Verbosity.ShouldBe(expectedVerbosity); } } [Test] public void EmptyArgumentsRemoteUsernameDefinedSetsUsername() { environment.SetEnvironmentVariable("GITVERSION_REMOTE_USERNAME", "value"); var arguments = argumentParser.ParseArguments(string.Empty); arguments.Authentication.Username.ShouldBe("value"); } [Test] public void EmptyArgumentsRemotePasswordDefinedSetsPassword() { environment.SetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD", "value"); var arguments = argumentParser.ParseArguments(string.Empty); arguments.Authentication.Password.ShouldBe("value"); } [Test] public void ArbitraryArgumentsRemoteUsernameDefinedSetsUsername() { environment.SetEnvironmentVariable("GITVERSION_REMOTE_USERNAME", "value"); var arguments = argumentParser.ParseArguments("-nocache"); arguments.Authentication.Username.ShouldBe("value"); } [Test] public void ArbitraryArgumentsRemotePasswordDefinedSetsPassword() { environment.SetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD", "value"); var arguments = argumentParser.ParseArguments("-nocache"); arguments.Authentication.Password.ShouldBe("value"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.Scripting.Runtime; namespace Microsoft.Scripting.Interpreter { internal interface IBoxableInstruction { Instruction BoxIfIndexMatches(int index); } internal abstract class LocalAccessInstruction : Instruction { internal readonly int _index; protected LocalAccessInstruction(int index) { _index = index; } public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects) { return cookie == null ? InstructionName + "(" + _index + ")" : InstructionName + "(" + cookie + ": " + _index + ")"; } } #region Load internal sealed class LoadLocalInstruction : LocalAccessInstruction, IBoxableInstruction { internal LoadLocalInstruction(int index) : base(index) { } public override int ProducedStack => 1; public override int Run(InterpretedFrame frame) { frame.Data[frame.StackIndex++] = frame.Data[_index]; //frame.Push(frame.Data[_index]); return +1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? InstructionList.LoadLocalBoxed(index) : null; } } internal sealed class LoadLocalBoxedInstruction : LocalAccessInstruction { internal LoadLocalBoxedInstruction(int index) : base(index) { } public override int ProducedStack => 1; public override int Run(InterpretedFrame frame) { var box = (StrongBox<object>)frame.Data[_index]; frame.Data[frame.StackIndex++] = box.Value; return +1; } } internal sealed class LoadLocalFromClosureInstruction : LocalAccessInstruction { internal LoadLocalFromClosureInstruction(int index) : base(index) { } public override int ProducedStack => 1; public override int Run(InterpretedFrame frame) { var box = frame.Closure[_index]; frame.Data[frame.StackIndex++] = box.Value; return +1; } } internal sealed class LoadLocalFromClosureBoxedInstruction : LocalAccessInstruction { internal LoadLocalFromClosureBoxedInstruction(int index) : base(index) { } public override int ProducedStack => 1; public override int Run(InterpretedFrame frame) { var box = frame.Closure[_index]; frame.Data[frame.StackIndex++] = box; return +1; } } #endregion #region Store, Assign internal sealed class AssignLocalInstruction : LocalAccessInstruction, IBoxableInstruction { internal AssignLocalInstruction(int index) : base(index) { } public override int ConsumedStack => 1; public override int ProducedStack => 1; public override int Run(InterpretedFrame frame) { frame.Data[_index] = frame.Peek(); return +1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? InstructionList.AssignLocalBoxed(index) : null; } } internal sealed class StoreLocalInstruction : LocalAccessInstruction, IBoxableInstruction { internal StoreLocalInstruction(int index) : base(index) { } public override int ConsumedStack => 1; public override int Run(InterpretedFrame frame) { frame.Data[_index] = frame.Data[--frame.StackIndex]; //frame.Data[_index] = frame.Pop(); return +1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? InstructionList.StoreLocalBoxed(index) : null; } } internal sealed class AssignLocalBoxedInstruction : LocalAccessInstruction { internal AssignLocalBoxedInstruction(int index) : base(index) { } public override int ConsumedStack => 1; public override int ProducedStack => 1; public override int Run(InterpretedFrame frame) { var box = (StrongBox<object>)frame.Data[_index]; box.Value = frame.Peek(); return +1; } } internal sealed class StoreLocalBoxedInstruction : LocalAccessInstruction { internal StoreLocalBoxedInstruction(int index) : base(index) { } public override int ConsumedStack => 1; public override int ProducedStack => 0; public override int Run(InterpretedFrame frame) { var box = (StrongBox<object>)frame.Data[_index]; box.Value = frame.Data[--frame.StackIndex]; return +1; } } internal sealed class AssignLocalToClosureInstruction : LocalAccessInstruction { internal AssignLocalToClosureInstruction(int index) : base(index) { } public override int ConsumedStack => 1; public override int ProducedStack => 1; public override int Run(InterpretedFrame frame) { var box = frame.Closure[_index]; box.Value = frame.Peek(); return +1; } } #endregion #region Initialize [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1012:AbstractTypesShouldNotHaveConstructors")] internal abstract class InitializeLocalInstruction : LocalAccessInstruction { internal InitializeLocalInstruction(int index) : base(index) { } internal sealed class Reference : InitializeLocalInstruction, IBoxableInstruction { internal Reference(int index) : base(index) { } public override int Run(InterpretedFrame frame) { frame.Data[_index] = null; return 1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? InstructionList.InitImmutableRefBox(index) : null; } public override string InstructionName => "InitRef"; } internal sealed class ImmutableValue : InitializeLocalInstruction, IBoxableInstruction { private readonly object _defaultValue; internal ImmutableValue(int index, object defaultValue) : base(index) { _defaultValue = defaultValue; } public override int Run(InterpretedFrame frame) { frame.Data[_index] = _defaultValue; return 1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? new ImmutableBox(index, _defaultValue) : null; } public override string InstructionName => "InitImmutableValue"; } internal sealed class ImmutableBox : InitializeLocalInstruction { // immutable value: private readonly object _defaultValue; internal ImmutableBox(int index, object defaultValue) : base(index) { _defaultValue = defaultValue; } public override int Run(InterpretedFrame frame) { frame.Data[_index] = new StrongBox<object>(_defaultValue); return 1; } public override string InstructionName => "InitImmutableBox"; } internal sealed class ParameterBox : InitializeLocalInstruction { public ParameterBox(int index) : base(index) { } public override int Run(InterpretedFrame frame) { frame.Data[_index] = new StrongBox<object>(frame.Data[_index]); return 1; } } internal sealed class Parameter : InitializeLocalInstruction, IBoxableInstruction { internal Parameter(int index) : base(index) { } public override int Run(InterpretedFrame frame) { // nop return 1; } public Instruction BoxIfIndexMatches(int index) { if (index == _index) { return InstructionList.ParameterBox(index); } return null; } public override string InstructionName => "InitParameter"; } internal sealed class MutableValue : InitializeLocalInstruction, IBoxableInstruction { private readonly Type _type; internal MutableValue(int index, Type type) : base(index) { _type = type; } public override int Run(InterpretedFrame frame) { try { frame.Data[_index] = Activator.CreateInstance(_type); } catch (TargetInvocationException e) { ExceptionHelpers.UpdateForRethrow(e.InnerException); throw e.InnerException; } return 1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? new MutableBox(index, _type) : null; } public override string InstructionName => "InitMutableValue"; } internal sealed class MutableBox : InitializeLocalInstruction { private readonly Type _type; internal MutableBox(int index, Type type) : base(index) { _type = type; } public override int Run(InterpretedFrame frame) { frame.Data[_index] = new StrongBox<object>(Activator.CreateInstance(_type)); return 1; } public override string InstructionName => "InitMutableBox"; } } #endregion #region RuntimeVariables internal sealed class RuntimeVariablesInstruction : Instruction { private readonly int _count; public RuntimeVariablesInstruction(int count) { _count = count; } public override int ProducedStack => 1; public override int ConsumedStack => _count; public override int Run(InterpretedFrame frame) { var ret = new IStrongBox[_count]; for (int i = ret.Length - 1; i >= 0; i--) { ret[i] = (IStrongBox)frame.Pop(); } frame.Push(RuntimeVariables.Create(ret)); return +1; } public override string ToString() { return "GetRuntimeVariables()"; } } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CppSharp.AST; namespace CppSharp.Generators { public enum NewLineKind { Never, Always, BeforeNextBlock, IfNotEmpty } public class BlockKind { public const int Unknown = 0; public const int BlockComment = 1; public const int InlineComment = 2; public const int Header = 3; public const int Footer = 4; public const int LAST = 5; } public class Block : ITextGenerator { public TextGenerator Text { get; set; } public int Kind { get; set; } public NewLineKind NewLineKind { get; set; } public Block Parent { get; set; } public List<Block> Blocks { get; set; } public Declaration Declaration { get; set; } private bool hasIndentChanged; private bool isSubBlock; public Func<bool> CheckGenerate; public Block() : this(BlockKind.Unknown) { } public Block(int kind) { Kind = kind; Blocks = new List<Block>(); Text = new TextGenerator(); hasIndentChanged = false; isSubBlock = false; } public void AddBlock(Block block) { if (Text.StringBuilder.Length != 0 || hasIndentChanged) { hasIndentChanged = false; var newBlock = new Block { Text = Text.Clone(), isSubBlock = true }; Text.StringBuilder.Clear(); AddBlock(newBlock); } block.Parent = this; Blocks.Add(block); } public IEnumerable<Block> FindBlocks(int kind) { foreach (var block in Blocks) { if (block.Kind == kind) yield return block; foreach (var childBlock in block.FindBlocks(kind)) yield return childBlock; } } public virtual string Generate(DriverOptions options) { if (CheckGenerate != null && !CheckGenerate()) return ""; if (Blocks.Count == 0) return Text.ToString(); var builder = new StringBuilder(); uint totalIndent = 0; Block previousBlock = null; var blockIndex = 0; foreach (var childBlock in Blocks) { var childText = childBlock.Generate(options); var nextBlock = (++blockIndex < Blocks.Count) ? Blocks[blockIndex] : null; var skipBlock = false; if (nextBlock != null) { var nextText = nextBlock.Generate(options); if (string.IsNullOrEmpty(nextText) && childBlock.NewLineKind == NewLineKind.IfNotEmpty) skipBlock = true; } if (skipBlock) continue; if (string.IsNullOrEmpty(childText)) continue; var lines = childText.SplitAndKeep(Environment.NewLine).ToList(); if (previousBlock != null && previousBlock.NewLineKind == NewLineKind.BeforeNextBlock) builder.AppendLine(); if (childBlock.isSubBlock) totalIndent = 0; if (childBlock.Kind == BlockKind.BlockComment) { // Wrap the comment to the max line width. var maxSize = options.MaxIndent - totalIndent; maxSize -= options.CommentPrefix.Length + 2; lines = StringHelpers.WordWrapLines(childText, (int)maxSize); for (var i = 0; i < lines.Count; ++i) { var line = lines[i]; if (!line.StartsWith(options.CommentPrefix)) lines[i] = options.CommentPrefix + " " + line; } } foreach (var line in lines) { if (string.IsNullOrEmpty(line)) continue; if (!string.IsNullOrWhiteSpace(line)) builder.Append(new string(' ', (int)totalIndent)); builder.Append(line); if (!line.EndsWith(Environment.NewLine)) builder.AppendLine(); } if (childBlock.NewLineKind == NewLineKind.Always) builder.AppendLine(); totalIndent += childBlock.Text.Indent; previousBlock = childBlock; } if (Text.StringBuilder.Length != 0) builder.Append(Text.StringBuilder); return builder.ToString(); } public bool IsEmpty { get { if (Blocks.Any(block => !block.IsEmpty)) return false; return string.IsNullOrEmpty(Text.ToString()); } } #region ITextGenerator implementation public uint Indent { get { return Text.Indent; } } public void Write(string msg, params object[] args) { Text.Write(msg, args); } public void WriteLine(string msg, params object[] args) { Text.WriteLine(msg, args); } public void WriteLineIndent(string msg, params object[] args) { Text.WriteLineIndent(msg, args); } public void NewLine() { Text.NewLine(); } public void NewLineIfNeeded() { Text.NewLineIfNeeded(); } public void NeedNewLine() { Text.NeedNewLine(); } public void ResetNewLine() { Text.ResetNewLine(); } public void PushIndent(uint indent = 4u) { hasIndentChanged = true; Text.PushIndent(indent); } public void PopIndent() { hasIndentChanged = true; Text.PopIndent(); } public void WriteStartBraceIndent() { Text.WriteStartBraceIndent(); } public void WriteCloseBraceIndent() { Text.WriteCloseBraceIndent(); } #endregion } public abstract class Template : ITextGenerator { public Driver Driver { get; private set; } public DriverOptions Options { get; private set; } public List<TranslationUnit> TranslationUnits { get; private set; } public TranslationUnit TranslationUnit { get { return TranslationUnits[0]; } } public IDiagnosticConsumer Log { get { return Driver.Diagnostics; } } public Block RootBlock { get; private set; } public Block ActiveBlock { get; private set; } public abstract string FileExtension { get; } protected Template(Driver driver, IEnumerable<TranslationUnit> units) { Driver = driver; Options = driver.Options; TranslationUnits = new List<TranslationUnit>(units); RootBlock = new Block(); ActiveBlock = RootBlock; } public abstract void Process(); public string Generate() { return RootBlock.Generate(Options); } #region Block helpers public void AddBlock(Block block) { ActiveBlock.AddBlock(block); } public void PushBlock(int kind, Declaration decl = null) { var block = new Block { Kind = kind, Declaration = decl }; PushBlock(block); } public void PushBlock(Block block) { block.Parent = ActiveBlock; ActiveBlock.AddBlock(block); ActiveBlock = block; } public Block PopBlock(NewLineKind newLineKind = NewLineKind.Never) { var block = ActiveBlock; ActiveBlock.NewLineKind = newLineKind; ActiveBlock = ActiveBlock.Parent; return block; } public IEnumerable<Block> FindBlocks(int kind) { return RootBlock.FindBlocks(kind); } public Block FindBlock(int kind) { return FindBlocks(kind).SingleOrDefault(); } #endregion #region ITextGenerator implementation public uint Indent { get { return ActiveBlock.Indent; } } public void Write(string msg, params object[] args) { ActiveBlock.Write(msg, args); } public void WriteLine(string msg, params object[] args) { ActiveBlock.WriteLine(msg, args); } public void WriteLineIndent(string msg, params object[] args) { ActiveBlock.WriteLineIndent(msg, args); } public void NewLine() { ActiveBlock.NewLine(); } public void NewLineIfNeeded() { ActiveBlock.NewLineIfNeeded(); } public void NeedNewLine() { ActiveBlock.NeedNewLine(); } public void ResetNewLine() { ActiveBlock.ResetNewLine(); } public void PushIndent(uint indent = 4u) { ActiveBlock.PushIndent(indent); } public void PopIndent() { ActiveBlock.PopIndent(); } public void WriteStartBraceIndent() { ActiveBlock.WriteStartBraceIndent(); } public void WriteCloseBraceIndent() { ActiveBlock.WriteCloseBraceIndent(); } #endregion } }
// ========================================================== // Updated to use UGUI, March 2015 // Dennis Trevillyan - WatreGames // using UnityEngine; using UnityEngine.UI; using System.Collections; using UMA; namespace UMA.Examples { public class UMACustomization : MonoBehaviour { public UMAData umaData; public UMADynamicAvatar umaDynamicAvatar; public CameraTrack cameraTrack; public MouseOrbitImproved orbitor; private UMADnaHumanoid umaDna; private UMADnaTutorial umaTutorialDna; private GameObject DnaPanel; // This is the parent panel private GameObject DnaScrollPanel; // This is the scrollable panel that holds the sliders // Slider objects private Slider HeightSlider; private Slider UpperMuscleSlider; private Slider UpperWeightSlider; private Slider LowerMuscleSlider; private Slider LowerWeightSlider; private Slider ArmLengthSlider; private Slider ForearmLengthSlider; private Slider LegSeparationSlider; private Slider HandSizeSlider; private Slider FeetSizeSlider; private Slider LegSizeSlider; private Slider ArmWidthSlider; private Slider ForearmWidthSlider; private Slider BreastSlider; private Slider BellySlider; private Slider WaistSizeSlider; private Slider GlueteusSizeSlider; private Slider HeadSizeSlider; private Slider NeckThickSlider; private Slider EarSizeSlider; private Slider EarPositionSlider; private Slider EarRotationSlider; private Slider NoseSizeSlider; private Slider NoseCurveSlider; private Slider NoseWidthSlider; private Slider NoseInclinationSlider; private Slider NosePositionSlider; private Slider NosePronuncedSlider; private Slider NoseFlattenSlider; private Slider ChinSizeSlider; private Slider ChinPronouncedSlider; private Slider ChinPositionSlider; private Slider MandibleSizeSlider; private Slider JawSizeSlider; private Slider JawPositionSlider; private Slider CheekSizeSlider; private Slider CheekPositionSlider; private Slider lowCheekPronSlider; private Slider ForeHeadSizeSlider; private Slider ForeHeadPositionSlider; private Slider LipSizeSlider; private Slider MouthSlider; private Slider EyeSizeSlider; private Slider EyeRotationSlider; private Slider EyeSpacingSlider; private Slider LowCheekPosSlider; private Slider HeadWidthSlider; private Slider[] sliders; private Rect ViewPortReduced; private Transform baseTarget; private Button DnaHide; // get the sliders and store for later use void Awake() { HeightSlider = GameObject.Find("HeightSlider").GetComponent<Slider>(); UpperMuscleSlider = GameObject.Find("UpperMuscleSlider").GetComponent<Slider>(); UpperWeightSlider = GameObject.Find("UpperWeightSlider").GetComponent<Slider>(); LowerMuscleSlider = GameObject.Find("LowerMuscleSlider").GetComponent<Slider>(); LowerWeightSlider = GameObject.Find("LowerWeightSlider").GetComponent<Slider>(); ArmLengthSlider = GameObject.Find("ArmLengthSlider").GetComponent<Slider>(); ForearmLengthSlider = GameObject.Find("ForearmLengthSlider").GetComponent<Slider>(); LegSeparationSlider = GameObject.Find("LegSepSlider").GetComponent<Slider>(); HandSizeSlider = GameObject.Find("HandSizeSlider").GetComponent<Slider>(); FeetSizeSlider = GameObject.Find("FeetSizeSlider").GetComponent<Slider>(); LegSizeSlider = GameObject.Find("LegSizeSlider").GetComponent<Slider>(); ArmWidthSlider = GameObject.Find("ArmWidthSlider").GetComponent<Slider>(); ForearmWidthSlider = GameObject.Find("ForearmWidthSlider").GetComponent<Slider>(); BreastSlider = GameObject.Find("BreastSizeSlider").GetComponent<Slider>(); BellySlider = GameObject.Find("BellySlider").GetComponent<Slider>(); WaistSizeSlider = GameObject.Find("WaistSizeSlider").GetComponent<Slider>(); GlueteusSizeSlider = GameObject.Find("GluteusSlider").GetComponent<Slider>(); HeadSizeSlider = GameObject.Find("HeadSizeSlider").GetComponent<Slider>(); HeadWidthSlider = GameObject.Find("HeadWidthSlider").GetComponent<Slider>(); NeckThickSlider = GameObject.Find("NeckSlider").GetComponent<Slider>(); EarSizeSlider = GameObject.Find("EarSizeSlider").GetComponent<Slider>(); EarPositionSlider = GameObject.Find("EarPosSlider").GetComponent<Slider>(); EarRotationSlider = GameObject.Find("EarRotSlider").GetComponent<Slider>(); NoseSizeSlider = GameObject.Find("NoseSizeSlider").GetComponent<Slider>(); NoseCurveSlider = GameObject.Find("NoseCurveSlider").GetComponent<Slider>(); NoseWidthSlider = GameObject.Find("NoseWidthSlider").GetComponent<Slider>(); NoseInclinationSlider = GameObject.Find("NoseInclineSlider").GetComponent<Slider>(); NosePositionSlider = GameObject.Find("NosePosSlider").GetComponent<Slider>(); NosePronuncedSlider = GameObject.Find("NosePronSlider").GetComponent<Slider>(); NoseFlattenSlider = GameObject.Find("NoseFlatSlider").GetComponent<Slider>(); ChinSizeSlider = GameObject.Find("ChinSizeSlider").GetComponent<Slider>(); ChinPronouncedSlider = GameObject.Find("ChinPronSlider").GetComponent<Slider>(); ChinPositionSlider = GameObject.Find("ChinPosSlider").GetComponent<Slider>(); MandibleSizeSlider = GameObject.Find("MandibleSizeSlider").GetComponent<Slider>(); JawSizeSlider = GameObject.Find("JawSizeSlider").GetComponent<Slider>(); JawPositionSlider = GameObject.Find("JawPosSlider").GetComponent<Slider>(); CheekSizeSlider = GameObject.Find("CheekSizeSlider").GetComponent<Slider>(); CheekPositionSlider = GameObject.Find("CheekPosSlider").GetComponent<Slider>(); lowCheekPronSlider = GameObject.Find("LowCheekPronSlider").GetComponent<Slider>(); ForeHeadSizeSlider = GameObject.Find("ForeheadSizeSlider").GetComponent<Slider>(); ForeHeadPositionSlider = GameObject.Find("ForeheadPosSlider").GetComponent<Slider>(); LipSizeSlider = GameObject.Find("LipSizeSlider").GetComponent<Slider>(); MouthSlider = GameObject.Find("MouthSizeSlider").GetComponent<Slider>(); EyeSizeSlider = GameObject.Find("EyeSizeSlider").GetComponent<Slider>(); EyeRotationSlider = GameObject.Find("EyeRotSlider").GetComponent<Slider>(); EyeSpacingSlider = GameObject.Find("EyeSpaceSlider").GetComponent<Slider>(); LowCheekPosSlider = GameObject.Find("LowCheekPosSlider").GetComponent<Slider>(); // Find the panels and hide for now DnaPanel = GameObject.Find("DnaEditorPanel"); // DnaScrollPanel = GameObject.Find("ScrollPanel"); DnaPanel.SetActive(false); #if UNITY_5 && !UNITY_5_1 && !UNITY_5_0 var oldUIMask = DnaPanel.GetComponent<Mask>(); if (oldUIMask != null) { DestroyImmediate(oldUIMask); DnaPanel.AddComponent<RectMask2D>(); } #endif // Find the DNA hide button and hide it for now DnaHide = GameObject.Find("MessagePanel").GetComponentInChildren<Button>(); DnaHide.gameObject.SetActive(false); } protected virtual void Start() { //float vpWidth; // sliders = DnaScrollPanel.GetComponentsInChildren<Slider>(); // Create an array of the sliders to use for initialization //vpWidth = ((float)Screen.width - 175) / (float)Screen.width; // Get the width of the screen so that we can adjust the viewport //ViewPortReduced = new Rect(0, 0, vpWidth, 1); //Camera.main.rect = ViewPortFull; baseTarget = GameObject.Find("UMACrowd").transform; // Get the transform of the UMA Crown GO to use when retargeting the camera } void Update() { if (umaTutorialDna != null) EyeSpacingSlider.interactable = true; else EyeSpacingSlider.interactable = false; // Don't raycast if the editor is open if (umaData != null) return; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1)) { if (Physics.Raycast(ray, out hit, 100)) { Transform tempTransform = hit.collider.transform; umaData = tempTransform.GetComponent<UMAData>(); if (umaData) { AvatarSetup(); } } } } // An avatar has been selected, setup the camera, sliders, retarget the camera, and adjust the viewport // to account for the DNA slider scroll panel public void AvatarSetup() { umaDynamicAvatar = umaData.gameObject.GetComponent<UMADynamicAvatar>(); if (cameraTrack) { cameraTrack.target = umaData.umaRoot.transform; } if (orbitor) { orbitor.target = umaData.umaRoot.transform; } umaDna = umaData.GetDna<UMADnaHumanoid>(); umaTutorialDna = umaData.GetDna<UMADnaTutorial>(); SetSliders(); SetCamera(true); } // Set the camera target and viewport private void SetCamera(bool show) { if (show) { DnaPanel.SetActive(true); DnaHide.gameObject.SetActive(true); #if UNITY_5 && !UNITY_5_1 && !UNITY_5_0 // really Unity? Yes we change the value and set it back to trigger a ui recalculation... // because setting the damn game object active doesn't do that! var rt = DnaPanel.GetComponent<RectTransform>(); var pos = rt.offsetMin; rt.offsetMin = new Vector2(pos.x + 1, pos.y); rt.offsetMin = pos; #endif } else { if (cameraTrack != null) cameraTrack.target = baseTarget; if (orbitor != null) orbitor.target = baseTarget; DnaPanel.SetActive(false); DnaHide.gameObject.SetActive(false); umaData = null; umaDna = null; umaTutorialDna = null; } } // Button callback to hide slider scroll panel public void HideDnaSlider() { SetCamera(false); } public void UpdateUMAAtlas() { if (umaData != null) { umaData.isTextureDirty = true; umaData.Dirty(); } } public void UpdateUMAShape() { if (umaData != null) { umaData.isShapeDirty = true; umaData.Dirty(); } } // Set all of the sliders to the values contained in the UMA Character public void SetSliders() { HeightSlider.value = umaDna.height; UpperMuscleSlider.value = umaDna.upperMuscle; UpperWeightSlider.value = umaDna.upperWeight; LowerMuscleSlider.value = umaDna.lowerMuscle; LowerWeightSlider.value = umaDna.lowerWeight; ArmLengthSlider.value = umaDna.armLength; ForearmLengthSlider.value = umaDna.forearmLength; LegSeparationSlider.value = umaDna.legSeparation; HandSizeSlider.value = umaDna.handsSize; FeetSizeSlider.value = umaDna.feetSize; LegSizeSlider.value = umaDna.legsSize; ArmWidthSlider.value = umaDna.armWidth; ForearmWidthSlider.value = umaDna.forearmWidth; BreastSlider.value = umaDna.breastSize; BellySlider.value = umaDna.belly; WaistSizeSlider.value = umaDna.waist; GlueteusSizeSlider.value = umaDna.gluteusSize; HeadSizeSlider.value = umaDna.headSize; HeadWidthSlider.value = umaDna.headWidth; NeckThickSlider.value = umaDna.neckThickness; EarSizeSlider.value = umaDna.earsSize; EarPositionSlider.value = umaDna.earsPosition; EarRotationSlider.value = umaDna.earsRotation; NoseSizeSlider.value = umaDna.noseSize; NoseCurveSlider.value = umaDna.noseCurve; NoseWidthSlider.value = umaDna.noseWidth; NoseInclinationSlider.value = umaDna.noseInclination; NosePositionSlider.value = umaDna.nosePosition; NosePronuncedSlider.value = umaDna.nosePronounced; NoseFlattenSlider.value = umaDna.noseFlatten; ChinSizeSlider.value = umaDna.chinSize; ChinPronouncedSlider.value = umaDna.chinPronounced; ChinPositionSlider.value = umaDna.chinPosition; MandibleSizeSlider.value = umaDna.mandibleSize; JawSizeSlider.value = umaDna.jawsSize; JawPositionSlider.value = umaDna.jawsPosition; CheekSizeSlider.value = umaDna.cheekSize; CheekPositionSlider.value = umaDna.cheekPosition; lowCheekPronSlider.value = umaDna.lowCheekPronounced; ForeHeadSizeSlider.value = umaDna.foreheadSize; ForeHeadPositionSlider.value = umaDna.foreheadPosition; LipSizeSlider.value = umaDna.lipsSize; MouthSlider.value = umaDna.mouthSize; EyeSizeSlider.value = umaDna.eyeSize; EyeRotationSlider.value = umaDna.eyeRotation; LowCheekPosSlider.value = umaDna.lowCheekPosition; if (umaTutorialDna != null) EyeSpacingSlider.value = umaTutorialDna.eyeSpacing; } // Slider callbacks public void OnHeightChange() { if (umaDna != null) umaDna.height = HeightSlider.value; UpdateUMAShape(); } public void OnUpperMuscleChange() { if (umaDna != null) umaDna.upperMuscle = UpperMuscleSlider.value; UpdateUMAShape(); } public void OnUpperWeightChange() { if (umaDna != null) umaDna.upperWeight = UpperWeightSlider.value; UpdateUMAShape(); } public void OnLowerMuscleChange() { if (umaDna != null) umaDna.lowerMuscle = LowerMuscleSlider.value; UpdateUMAShape(); } public void OnLowerWeightChange() { if (umaDna != null) umaDna.lowerWeight = LowerWeightSlider.value; UpdateUMAShape(); } public void OnArmLengthChange() { if (umaDna != null) umaDna.armLength = ArmLengthSlider.value; UpdateUMAShape(); } public void OnForearmLengthChange() { if (umaDna != null) umaDna.forearmLength = ForearmLengthSlider.value; UpdateUMAShape(); } public void OnLegSeparationChange() { if (umaDna != null) umaDna.legSeparation = LegSeparationSlider.value; UpdateUMAShape(); } public void OnHandSizeChange() { if (umaDna != null) umaDna.handsSize = HandSizeSlider.value; UpdateUMAShape(); } public void OnFootSizeChange() { if (umaDna != null) umaDna.feetSize = FeetSizeSlider.value; UpdateUMAShape(); } public void OnLegSizeChange() { if (umaDna != null) umaDna.legsSize = LegSizeSlider.value; UpdateUMAShape(); } public void OnArmWidthChange() { if (umaDna != null) umaDna.armWidth = ArmWidthSlider.value; UpdateUMAShape(); } public void OnForearmWidthChange() { if (umaDna != null) umaDna.forearmWidth = ForearmWidthSlider.value; UpdateUMAShape(); } public void OnBreastSizeChange() { if (umaDna != null) umaDna.breastSize = BreastSlider.value; UpdateUMAShape(); } public void OnBellySizeChange() { if (umaDna != null) umaDna.belly = BellySlider.value; UpdateUMAShape(); } public void OnWaistSizeChange() { if (umaDna != null) umaDna.waist = WaistSizeSlider.value; UpdateUMAShape(); } public void OnGluteusSizeChange() { if (umaDna != null) umaDna.gluteusSize = GlueteusSizeSlider.value; UpdateUMAShape(); } public void OnHeadSizeChange() { if (umaDna != null) umaDna.headSize = HeadSizeSlider.value; UpdateUMAShape(); } public void OnHeadWidthChange() { if (umaDna != null) umaDna.headWidth = HeadWidthSlider.value; UpdateUMAShape(); } public void OnNeckThicknessChange() { if (umaDna != null) umaDna.neckThickness = NeckThickSlider.value; UpdateUMAShape(); } public void OnEarSizeChange() { if (umaDna != null) umaDna.earsSize = EarSizeSlider.value; UpdateUMAShape(); } public void OnEarPositionChange() { if (umaDna != null) umaDna.earsPosition = EarPositionSlider.value; UpdateUMAShape(); } public void OnEarRotationChange() { if (umaDna != null) umaDna.earsRotation = EarRotationSlider.value; UpdateUMAShape(); } public void OnNoseSizeChange() { if (umaDna != null) umaDna.noseSize = NoseSizeSlider.value; UpdateUMAShape(); } public void OnNoseCurveChange() { if (umaDna != null) umaDna.noseCurve = NoseCurveSlider.value; UpdateUMAShape(); } public void OnNoseWidthChange() { if (umaDna != null) umaDna.noseWidth = NoseWidthSlider.value; UpdateUMAShape(); } public void OnNoseInclinationChange() { if (umaDna != null) umaDna.noseInclination = NoseInclinationSlider.value; UpdateUMAShape(); } public void OnNosePositionChange() { if (umaDna != null) umaDna.nosePosition = NosePositionSlider.value; UpdateUMAShape(); } public void OnNosePronouncedChange() { if (umaDna != null) umaDna.nosePronounced = NosePronuncedSlider.value; UpdateUMAShape(); } public void OnNoseFlattenChange() { if (umaDna != null) umaDna.noseFlatten = NoseFlattenSlider.value; UpdateUMAShape(); } public void OnChinSizeChange() { if (umaDna != null) umaDna.chinSize = ChinSizeSlider.value; UpdateUMAShape(); } public void OnChinPronouncedChange() { if (umaDna != null) umaDna.chinPronounced = ChinPronouncedSlider.value; UpdateUMAShape(); } public void OnChinPositionChange() { if (umaDna != null) umaDna.chinPosition = ChinPositionSlider.value; UpdateUMAShape(); } public void OnMandibleSizeChange() { if (umaDna != null) umaDna.mandibleSize = MandibleSizeSlider.value; UpdateUMAShape(); } public void OnJawSizeChange() { if (umaDna != null) umaDna.jawsSize = JawSizeSlider.value; UpdateUMAShape(); } public void OnJawPositionChange() { if (umaDna != null) umaDna.jawsPosition = JawPositionSlider.value; UpdateUMAShape(); } public void OnCheekSizeChange() { if (umaDna != null) umaDna.cheekSize = CheekSizeSlider.value; UpdateUMAShape(); } public void OnCheekPositionChange() { if (umaDna != null) umaDna.cheekPosition = CheekPositionSlider.value; UpdateUMAShape(); } public void OnCheekLowPronouncedChange() { if (umaDna != null) umaDna.lowCheekPronounced = lowCheekPronSlider.value; UpdateUMAShape(); } public void OnForeheadSizeChange() { if (umaDna != null) umaDna.foreheadSize = ForeHeadSizeSlider.value; UpdateUMAShape(); } public void OnForeheadPositionChange() { if (umaDna != null) umaDna.foreheadPosition = ForeHeadPositionSlider.value; UpdateUMAShape(); } public void OnLipSizeChange() { if (umaDna != null) umaDna.lipsSize = LipSizeSlider.value; UpdateUMAShape(); } public void OnMouthSizeChange() { if (umaDna != null) umaDna.mouthSize = MouthSlider.value; UpdateUMAShape(); } public void OnEyeSizechange() { if (umaDna != null) umaDna.eyeSize = EyeSizeSlider.value; UpdateUMAShape(); } public void OnEyeRotationChange() { if (umaDna != null) umaDna.eyeRotation = EyeRotationSlider.value; UpdateUMAShape(); } public void OnLowCheekPositionChange() { if (umaDna != null) umaDna.lowCheekPosition = LowCheekPosSlider.value; UpdateUMAShape(); } public void OnEyeSpacingChange() { if (umaTutorialDna != null) umaTutorialDna.eyeSpacing = EyeSpacingSlider.value; UpdateUMAShape(); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// .Net client wrapper for the REST API for Azure ApiManagement Service /// </summary> public partial class ApiManagementClient : ServiceClient<ApiManagementClient>, IApiManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IApiOperationPolicyOperations _apiOperationPolicy; /// <summary> /// Operations for managing API Operation Policy. /// </summary> public virtual IApiOperationPolicyOperations ApiOperationPolicy { get { return this._apiOperationPolicy; } } private IApiOperationsOperations _apiOperations; /// <summary> /// Operations for managing API Operations. /// </summary> public virtual IApiOperationsOperations ApiOperations { get { return this._apiOperations; } } private IApiPolicyOperations _apiPolicy; /// <summary> /// Operations for managing API Policy. /// </summary> public virtual IApiPolicyOperations ApiPolicy { get { return this._apiPolicy; } } private IApiProductsOperations _apiProducts; /// <summary> /// Operations for listing API associated Products. /// </summary> public virtual IApiProductsOperations ApiProducts { get { return this._apiProducts; } } private IApisOperations _apis; /// <summary> /// Operations for managing APIs. /// </summary> public virtual IApisOperations Apis { get { return this._apis; } } private IAuthorizationServersOperations _authorizationServers; /// <summary> /// Operations for managing Authorization Servers. /// </summary> public virtual IAuthorizationServersOperations AuthorizationServers { get { return this._authorizationServers; } } private ICertificatesOperations _certificates; /// <summary> /// Operations for managing Certificates. /// </summary> public virtual ICertificatesOperations Certificates { get { return this._certificates; } } private IGroupsOperations _groups; /// <summary> /// Operations for managing Groups. /// </summary> public virtual IGroupsOperations Groups { get { return this._groups; } } private IGroupUsersOperations _groupUsers; /// <summary> /// Operations for managing Group Users (list, add, remove users within /// a group). /// </summary> public virtual IGroupUsersOperations GroupUsers { get { return this._groupUsers; } } private IPolicySnippetsOperations _policySnippents; /// <summary> /// Operations for managing Policy Snippets. /// </summary> public virtual IPolicySnippetsOperations PolicySnippents { get { return this._policySnippents; } } private IProductApisOperations _productApis; /// <summary> /// Operations for managing Product APIs. /// </summary> public virtual IProductApisOperations ProductApis { get { return this._productApis; } } private IProductGroupsOperations _productGroups; /// <summary> /// Operations for managing Product Groups. /// </summary> public virtual IProductGroupsOperations ProductGroups { get { return this._productGroups; } } private IProductPolicyOperations _productPolicy; /// <summary> /// Operations for managing Product Policy. /// </summary> public virtual IProductPolicyOperations ProductPolicy { get { return this._productPolicy; } } private IProductsOperations _products; /// <summary> /// Operations for managing Products. /// </summary> public virtual IProductsOperations Products { get { return this._products; } } private IProductSubscriptionsOperations _productSubscriptions; /// <summary> /// Operations for managing Product Subscriptions. /// </summary> public virtual IProductSubscriptionsOperations ProductSubscriptions { get { return this._productSubscriptions; } } private IRegionsOperations _regions; /// <summary> /// Operations for managing Regions. /// </summary> public virtual IRegionsOperations Regions { get { return this._regions; } } private IReportsOperations _reports; /// <summary> /// Operations for managing Reports. /// </summary> public virtual IReportsOperations Reports { get { return this._reports; } } private IResourceProviderOperations _resourceProvider; /// <summary> /// Operations for managing Api Management service provisioning /// (create/remove, backup/restore, scale, etc.). /// </summary> public virtual IResourceProviderOperations ResourceProvider { get { return this._resourceProvider; } } private ISubscriptionsOperations _subscriptions; /// <summary> /// Operations for managing Subscriptions. /// </summary> public virtual ISubscriptionsOperations Subscriptions { get { return this._subscriptions; } } private ITenantPolicyOperations _tenantPolicy; /// <summary> /// Operations for managing Tenant Policy. /// </summary> public virtual ITenantPolicyOperations TenantPolicy { get { return this._tenantPolicy; } } private IUserApplicationsOperations _userApplications; /// <summary> /// Operations for managing User Applications. /// </summary> public virtual IUserApplicationsOperations UserApplications { get { return this._userApplications; } } private IUserGroupsOperations _userGroups; /// <summary> /// Operations for managing User Groups. /// </summary> public virtual IUserGroupsOperations UserGroups { get { return this._userGroups; } } private IUserIdentitiesOperations _userIdentities; /// <summary> /// Operations for managing User Identities. /// </summary> public virtual IUserIdentitiesOperations UserIdentities { get { return this._userIdentities; } } private IUsersOperations _users; /// <summary> /// Operations for managing Users. /// </summary> public virtual IUsersOperations Users { get { return this._users; } } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> public ApiManagementClient() : base() { this._apiOperationPolicy = new ApiOperationPolicyOperations(this); this._apiOperations = new ApiOperationsOperations(this); this._apiPolicy = new ApiPolicyOperations(this); this._apiProducts = new ApiProductsOperations(this); this._apis = new ApisOperations(this); this._authorizationServers = new AuthorizationServersOperations(this); this._certificates = new CertificatesOperations(this); this._groups = new GroupsOperations(this); this._groupUsers = new GroupUsersOperations(this); this._policySnippents = new PolicySnippetsOperations(this); this._productApis = new ProductApisOperations(this); this._productGroups = new ProductGroupsOperations(this); this._productPolicy = new ProductPolicyOperations(this); this._products = new ProductsOperations(this); this._productSubscriptions = new ProductSubscriptionsOperations(this); this._regions = new RegionsOperations(this); this._reports = new ReportsOperations(this); this._resourceProvider = new ResourceProviderOperations(this); this._subscriptions = new SubscriptionsOperations(this); this._tenantPolicy = new TenantPolicyOperations(this); this._userApplications = new UserApplicationsOperations(this); this._userGroups = new UserGroupsOperations(this); this._userIdentities = new UserIdentitiesOperations(this); this._users = new UsersOperations(this); this._apiVersion = "2014-02-14"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public ApiManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public ApiManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public ApiManagementClient(HttpClient httpClient) : base(httpClient) { this._apiOperationPolicy = new ApiOperationPolicyOperations(this); this._apiOperations = new ApiOperationsOperations(this); this._apiPolicy = new ApiPolicyOperations(this); this._apiProducts = new ApiProductsOperations(this); this._apis = new ApisOperations(this); this._authorizationServers = new AuthorizationServersOperations(this); this._certificates = new CertificatesOperations(this); this._groups = new GroupsOperations(this); this._groupUsers = new GroupUsersOperations(this); this._policySnippents = new PolicySnippetsOperations(this); this._productApis = new ProductApisOperations(this); this._productGroups = new ProductGroupsOperations(this); this._productPolicy = new ProductPolicyOperations(this); this._products = new ProductsOperations(this); this._productSubscriptions = new ProductSubscriptionsOperations(this); this._regions = new RegionsOperations(this); this._reports = new ReportsOperations(this); this._resourceProvider = new ResourceProviderOperations(this); this._subscriptions = new SubscriptionsOperations(this); this._tenantPolicy = new TenantPolicyOperations(this); this._userApplications = new UserApplicationsOperations(this); this._userGroups = new UserGroupsOperations(this); this._userIdentities = new UserIdentitiesOperations(this); this._users = new UsersOperations(this); this._apiVersion = "2014-02-14"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public ApiManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public ApiManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// ApiManagementClient instance /// </summary> /// <param name='client'> /// Instance of ApiManagementClient to clone to /// </param> protected override void Clone(ServiceClient<ApiManagementClient> client) { base.Clone(client); if (client is ApiManagementClient) { ApiManagementClient clonedClient = ((ApiManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// Parse enum values for type BearerTokenSendingMethodsContract. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static BearerTokenSendingMethodsContract ParseBearerTokenSendingMethodsContract(string value) { if ("authorizationHeader".Equals(value, StringComparison.OrdinalIgnoreCase)) { return BearerTokenSendingMethodsContract.AuthorizationHeader; } if ("query".Equals(value, StringComparison.OrdinalIgnoreCase)) { return BearerTokenSendingMethodsContract.Query; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type BearerTokenSendingMethodsContract to a /// string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string BearerTokenSendingMethodsContractToString(BearerTokenSendingMethodsContract value) { if (value == BearerTokenSendingMethodsContract.AuthorizationHeader) { return "authorizationHeader"; } if (value == BearerTokenSendingMethodsContract.Query) { return "query"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type GrantTypesContract. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static GrantTypesContract ParseGrantTypesContract(string value) { if ("authorizationCode".Equals(value, StringComparison.OrdinalIgnoreCase)) { return GrantTypesContract.AuthorizationCode; } if ("implicit".Equals(value, StringComparison.OrdinalIgnoreCase)) { return GrantTypesContract.Implicit; } if ("resourceOwnerPassword".Equals(value, StringComparison.OrdinalIgnoreCase)) { return GrantTypesContract.ResourceOwnerPassword; } if ("clientCredentials".Equals(value, StringComparison.OrdinalIgnoreCase)) { return GrantTypesContract.ClientCredentials; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type GrantTypesContract to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string GrantTypesContractToString(GrantTypesContract value) { if (value == GrantTypesContract.AuthorizationCode) { return "authorizationCode"; } if (value == GrantTypesContract.Implicit) { return "implicit"; } if (value == GrantTypesContract.ResourceOwnerPassword) { return "resourceOwnerPassword"; } if (value == GrantTypesContract.ClientCredentials) { return "clientCredentials"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type MethodContract. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static MethodContract ParseMethodContract(string value) { if ("HEAD".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Head; } if ("OPTIONS".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Options; } if ("TRACE".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Trace; } if ("GET".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Get; } if ("POST".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Post; } if ("PUT".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Put; } if ("PATCH".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Patch; } if ("DELETE".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Delete; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type MethodContract to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string MethodContractToString(MethodContract value) { if (value == MethodContract.Head) { return "HEAD"; } if (value == MethodContract.Options) { return "OPTIONS"; } if (value == MethodContract.Trace) { return "TRACE"; } if (value == MethodContract.Get) { return "GET"; } if (value == MethodContract.Post) { return "POST"; } if (value == MethodContract.Put) { return "PUT"; } if (value == MethodContract.Patch) { return "PATCH"; } if (value == MethodContract.Delete) { return "DELETE"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type ReportsAggregation. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static ReportsAggregation ParseReportsAggregation(string value) { if ("byApi".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByApi; } if ("byGeo".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByGeo; } if ("byOperation".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByOperation; } if ("byProduct".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByProduct; } if ("bySubscription".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.BySubscription; } if ("byTime".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByTime; } if ("byUser".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByUser; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type ReportsAggregation to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string ReportsAggregationToString(ReportsAggregation value) { if (value == ReportsAggregation.ByApi) { return "byApi"; } if (value == ReportsAggregation.ByGeo) { return "byGeo"; } if (value == ReportsAggregation.ByOperation) { return "byOperation"; } if (value == ReportsAggregation.ByProduct) { return "byProduct"; } if (value == ReportsAggregation.BySubscription) { return "bySubscription"; } if (value == ReportsAggregation.ByTime) { return "byTime"; } if (value == ReportsAggregation.ByUser) { return "byUser"; } throw new ArgumentOutOfRangeException("value"); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using OpenLiveWriter.Interop.Windows; using OpenLiveWriter.ApplicationFramework; namespace OpenLiveWriter { /// <summary> /// Summary description for PaintingTestForm. /// </summary> public class PaintingTestForm : Form { class TransparentLinkLabel : LinkLabel { public TransparentLinkLabel() { SetStyle(ControlStyles.SupportsTransparentBackColor, true); BackColor = Color.Transparent ; FlatStyle = FlatStyle.System ; Cursor = Cursors.Hand ; LinkBehavior = LinkBehavior.HoverUnderline ; } } class TransparentLabel : Label { public TransparentLabel() { SetStyle(ControlStyles.SupportsTransparentBackColor, true); BackColor = Color.Transparent ; } } private TransparentLinkLabel linkLabel1; private OpenLiveWriter.PaintingTestForm.TransparentLinkLabel transparentLinkLabel1; private OpenLiveWriter.PaintingTestForm.TransparentLinkLabel transparentLinkLabel2; private OpenLiveWriter.PaintingTestForm.TransparentLinkLabel transparentLinkLabel3; private OpenLiveWriter.PaintingTestForm.TransparentLinkLabel transparentLinkLabel4; private OpenLiveWriter.PaintingTestForm.TransparentLinkLabel transparentLinkLabel5; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public static void Main(string[] args) { Application.Run(new PaintingTestForm()); } public PaintingTestForm() { // // Required for Windows Form Designer support // InitializeComponent(); // Turn off CS_CLIPCHILDREN. //User32.SetWindowLong(Handle, GWL.STYLE, User32.GetWindowLong(Handle, GWL.STYLE) & ~WS.CLIPCHILDREN); // Turn on double buffered painting. SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.DoubleBuffer, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); } protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged (e); Invalidate(); } /* protected override void OnPaintBackground(PaintEventArgs pevent) { } */ protected override void OnPaint(PaintEventArgs e) { // paint background using ( Brush brush = new LinearGradientBrush(ClientRectangle, ApplicationManager.ApplicationStyle.PrimaryWorkspaceCommandBarTopColor, ApplicationManager.ApplicationStyle.PrimaryWorkspaceCommandBarBottomColor, LinearGradientMode.Vertical)) e.Graphics.FillRectangle(brush, ClientRectangle); // paint headers using ( Brush brush = new SolidBrush(ForeColor) ) { e.Graphics.DrawString("Header1", Font, brush, linkLabel1.Left, linkLabel1.Top - 20) ; e.Graphics.DrawString("Header2", Font, brush, transparentLinkLabel5.Left, transparentLinkLabel5.Top - 20) ; } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.linkLabel1 = new OpenLiveWriter.PaintingTestForm.TransparentLinkLabel(); this.transparentLinkLabel1 = new OpenLiveWriter.PaintingTestForm.TransparentLinkLabel(); this.transparentLinkLabel2 = new OpenLiveWriter.PaintingTestForm.TransparentLinkLabel(); this.transparentLinkLabel3 = new OpenLiveWriter.PaintingTestForm.TransparentLinkLabel(); this.transparentLinkLabel4 = new OpenLiveWriter.PaintingTestForm.TransparentLinkLabel(); this.transparentLinkLabel5 = new OpenLiveWriter.PaintingTestForm.TransparentLinkLabel(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // linkLabel1 // this.linkLabel1.BackColor = System.Drawing.Color.Transparent; this.linkLabel1.Cursor = System.Windows.Forms.Cursors.Hand; this.linkLabel1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.linkLabel1.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.linkLabel1.Location = new System.Drawing.Point(64, 56); this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.Size = new System.Drawing.Size(120, 24); this.linkLabel1.TabIndex = 0; this.linkLabel1.TabStop = true; this.linkLabel1.Text = "linkLabel1"; // // transparentLinkLabel1 // this.transparentLinkLabel1.BackColor = System.Drawing.Color.Transparent; this.transparentLinkLabel1.Cursor = System.Windows.Forms.Cursors.Hand; this.transparentLinkLabel1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.transparentLinkLabel1.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.transparentLinkLabel1.Location = new System.Drawing.Point(64, 80); this.transparentLinkLabel1.Name = "transparentLinkLabel1"; this.transparentLinkLabel1.Size = new System.Drawing.Size(120, 24); this.transparentLinkLabel1.TabIndex = 1; this.transparentLinkLabel1.TabStop = true; this.transparentLinkLabel1.Text = "transparentLinkLabel1"; // // transparentLinkLabel2 // this.transparentLinkLabel2.BackColor = System.Drawing.Color.Transparent; this.transparentLinkLabel2.Cursor = System.Windows.Forms.Cursors.Hand; this.transparentLinkLabel2.FlatStyle = System.Windows.Forms.FlatStyle.System; this.transparentLinkLabel2.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.transparentLinkLabel2.Location = new System.Drawing.Point(64, 104); this.transparentLinkLabel2.Name = "transparentLinkLabel2"; this.transparentLinkLabel2.TabIndex = 0; this.transparentLinkLabel2.TabStop = true; this.transparentLinkLabel2.Text = "last label"; // // transparentLinkLabel3 // this.transparentLinkLabel3.BackColor = System.Drawing.Color.Transparent; this.transparentLinkLabel3.Cursor = System.Windows.Forms.Cursors.Hand; this.transparentLinkLabel3.FlatStyle = System.Windows.Forms.FlatStyle.System; this.transparentLinkLabel3.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.transparentLinkLabel3.Location = new System.Drawing.Point(64, 208); this.transparentLinkLabel3.Name = "transparentLinkLabel3"; this.transparentLinkLabel3.TabIndex = 3; this.transparentLinkLabel3.TabStop = true; this.transparentLinkLabel3.Text = "last label"; // // transparentLinkLabel4 // this.transparentLinkLabel4.BackColor = System.Drawing.Color.Transparent; this.transparentLinkLabel4.Cursor = System.Windows.Forms.Cursors.Hand; this.transparentLinkLabel4.FlatStyle = System.Windows.Forms.FlatStyle.System; this.transparentLinkLabel4.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.transparentLinkLabel4.Location = new System.Drawing.Point(64, 184); this.transparentLinkLabel4.Name = "transparentLinkLabel4"; this.transparentLinkLabel4.Size = new System.Drawing.Size(120, 24); this.transparentLinkLabel4.TabIndex = 4; this.transparentLinkLabel4.TabStop = true; this.transparentLinkLabel4.Text = "transparentLinkLabel4"; // // transparentLinkLabel5 // this.transparentLinkLabel5.BackColor = System.Drawing.Color.Transparent; this.transparentLinkLabel5.Cursor = System.Windows.Forms.Cursors.Hand; this.transparentLinkLabel5.FlatStyle = System.Windows.Forms.FlatStyle.System; this.transparentLinkLabel5.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.transparentLinkLabel5.Location = new System.Drawing.Point(64, 160); this.transparentLinkLabel5.Name = "transparentLinkLabel5"; this.transparentLinkLabel5.TabIndex = 5; this.transparentLinkLabel5.TabStop = true; this.transparentLinkLabel5.Text = "label5"; // // button1 // this.button1.Location = new System.Drawing.Point(216, 96); this.button1.Name = "button1"; this.button1.TabIndex = 6; this.button1.Text = "Show"; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Location = new System.Drawing.Point(216, 128); this.button2.Name = "button2"; this.button2.TabIndex = 7; this.button2.Text = "Hide"; this.button2.Click += new System.EventHandler(this.button2_Click); // // PaintingTestForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(304, 266); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.transparentLinkLabel3); this.Controls.Add(this.transparentLinkLabel4); this.Controls.Add(this.transparentLinkLabel5); this.Controls.Add(this.transparentLinkLabel2); this.Controls.Add(this.transparentLinkLabel1); this.Controls.Add(this.linkLabel1); this.Name = "PaintingTestForm"; this.Text = "PaintingTestForm"; this.ResumeLayout(false); } #endregion private void button1_Click(object sender, System.EventArgs e) { transparentLinkLabel1.Visible = true ; transparentLinkLabel2.Top += transparentLinkLabel1.Height ; transparentLinkLabel3.Top += transparentLinkLabel1.Height ; transparentLinkLabel4.Top += transparentLinkLabel1.Height ; transparentLinkLabel5.Top += transparentLinkLabel1.Height ; Invalidate(false); } private void button2_Click(object sender, System.EventArgs e) { transparentLinkLabel1.Visible = false ; transparentLinkLabel2.Top -= transparentLinkLabel1.Height ; transparentLinkLabel3.Top -= transparentLinkLabel1.Height ; transparentLinkLabel4.Top -= transparentLinkLabel1.Height ; transparentLinkLabel5.Top -= transparentLinkLabel1.Height ; Invalidate(false); } } }
// Copyright (c) Microsoft Corporation. All Rights Reserved. // Licensed under the MIT License. using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; using System.ComponentModel; namespace InteractiveDataDisplay.WPF { /// <summary> /// Provides mouse navigation around viewport of parent <see cref="PlotBase"/>. /// </summary> /// <remarks> /// Place instance of <see cref="MouseNavigation"/> inside your <see cref="PlotBase"/> element to enable mouse navigation over it. /// </remarks> [Description("Navigates parent plot by mouse")] public class MouseNavigation : Panel { private Canvas navigationCanvas = new Canvas { // This background brush allows Canvas to intercept mouse events while remaining transparent Background = new SolidColorBrush(Color.FromArgb(0, 255, 255, 255)) }; private PlotBase masterPlot = null; /// <summary>First parent Control in visual tree. Used to receive focus on mouse click</summary> private Control parentControl = null; private bool isPanning = false; private bool isSelecting = false; private bool wasInside = false; private bool isLeftClicked = false; private bool selectingStarted = false; private Point panningStart; private Point panningEnd; private Point selectStart; private Point selectEnd; private DateTime lastClick; private bool selectingMode = true; private Rectangle selectArea; private Plot plot = new NavigationPlot(); private bool transformChangeRequested = false; /// <summary> /// Initializes a new instance of <see cref="MouseNavigation"/> class. /// </summary> public MouseNavigation() { Children.Add(navigationCanvas); Loaded += MouseNavigationLoaded; Unloaded += MouseNavigationUnloaded; MouseLeave += new MouseEventHandler(MouseNavigationLayer_MouseLeave); MouseMove += new MouseEventHandler(MouseNavigationLayer_MouseMove); MouseRightButtonUp += new MouseButtonEventHandler(MouseNavigationLayer_MouseRightButtonUp); MouseRightButtonDown += new MouseButtonEventHandler(MouseNavigationLayer_MouseRightButtonDown); MouseWheel += new MouseWheelEventHandler(MouseNavigationLayer_MouseWheel); LayoutUpdated += (s, a) => transformChangeRequested = false; } /// <summary>Gets or sets vertical navigation status. True means that user can navigate along Y axis</summary> /// <remarks>The default value is true</remarks> [Category("InteractiveDataDisplay")] public bool IsVerticalNavigationEnabled { get { return (bool)GetValue(IsVerticalNavigationEnabledProperty); } set { SetValue(IsVerticalNavigationEnabledProperty, value); } } /// <summary>Identifies <see cref="IsVerticalNavigationEnabled"/> property</summary> public static readonly DependencyProperty IsVerticalNavigationEnabledProperty = DependencyProperty.Register("IsVerticalNavigationEnabled", typeof(bool), typeof(MouseNavigation), new PropertyMetadata(true)); /// <summary>Gets or sets horizontal navigation status. True means that user can navigate along X axis</summary> /// <remarks>The default value is true</remarks> [Category("InteractiveDataDisplay")] public bool IsHorizontalNavigationEnabled { get { return (bool)GetValue(IsHorizontalNavigationEnabledProperty); } set { SetValue(IsHorizontalNavigationEnabledProperty, value); } } /// <summary>Identifies <see cref="IsHorizontalNavigationEnabled"/> property</summary> public static readonly DependencyProperty IsHorizontalNavigationEnabledProperty = DependencyProperty.Register("IsHorizontalNavigationEnabled", typeof(bool), typeof(MouseNavigation), new PropertyMetadata(true)); void MouseNavigationUnloaded(object sender, RoutedEventArgs e) { if (masterPlot != null) { masterPlot.MouseLeave -= MouseNavigationLayer_MouseLeave; masterPlot.MouseMove -= MouseNavigationLayer_MouseMove; masterPlot.MouseRightButtonUp -= MouseNavigationLayer_MouseRightButtonUp; masterPlot.MouseRightButtonDown -= MouseNavigationLayer_MouseRightButtonDown; masterPlot.MouseWheel -= MouseNavigationLayer_MouseWheel; } masterPlot = null; parentControl = null; } void MouseNavigationLoaded(object sender, RoutedEventArgs e) { masterPlot = PlotBase.FindMaster(this); if (masterPlot != null) { masterPlot.MouseLeave += MouseNavigationLayer_MouseLeave; masterPlot.MouseMove += MouseNavigationLayer_MouseMove; masterPlot.MouseRightButtonUp += MouseNavigationLayer_MouseRightButtonUp; masterPlot.MouseRightButtonDown += MouseNavigationLayer_MouseRightButtonDown; masterPlot.MouseWheel += MouseNavigationLayer_MouseWheel; } var parent = VisualTreeHelper.GetParent(this); var controlParent = parent as Control; while (parent != null && controlParent == null) { parent = VisualTreeHelper.GetParent(parent); controlParent = parent as Control; } parentControl = controlParent; } /// <summary> /// Measures the size in layout required for child elements and determines a size for the Figure. /// </summary> /// <param name="availableSize">The available size that this element can give to child elements. Infinity can be specified as a value to indicate that the element will size to whatever content is available.</param> /// <returns>The size that this element determines it needs during layout, based on its calculations of child element sizes.</returns> protected override Size MeasureOverride(Size availableSize) { navigationCanvas.Measure(availableSize); return navigationCanvas.DesiredSize; } /// <summary> /// Positions child elements and determines a size for a Figure /// </summary> /// <param name="finalSize">The final area within the parent that Figure should use to arrange itself and its children</param> /// <returns>The actual size used</returns> protected override Size ArrangeOverride(Size finalSize) { navigationCanvas.Arrange(new Rect(new Point(0, 0), finalSize)); transformChangeRequested = false; return finalSize; } private void DoZoom(double factor) { if (masterPlot != null) { var rect = masterPlot.PlotRect; if (IsHorizontalNavigationEnabled) rect.X = rect.X.Zoom(factor); if (IsVerticalNavigationEnabled) rect.Y = rect.Y.Zoom(factor); if (IsZoomEnable(rect)) { masterPlot.SetPlotRect(rect); masterPlot.IsAutoFitEnabled = false; } } } private bool IsZoomEnable(DataRect rect) { bool res = true; if (IsHorizontalNavigationEnabled) { double e_max = Math.Log(Math.Max(Math.Abs(rect.XMax), Math.Abs(rect.XMin)), 2); double log = Math.Log(rect.Width, 2); res = log > e_max - 40; } if (IsVerticalNavigationEnabled) { double e_max = Math.Log(Math.Max(Math.Abs(rect.YMax), Math.Abs(rect.YMin)), 2); double log = Math.Log(rect.Height, 2); res = res && log > e_max - 40; } return res; } private void MouseNavigationLayer_MouseWheel(object sender, MouseWheelEventArgs e) { Point cursorPosition = e.GetPosition(this); if (!CheckCursor(cursorPosition)) return; // TODO: Zoom relative to mouse position double factor = e.Delta < 0 ? 1.2 : 1 / 1.2; DoZoom(factor); e.Handled = true; } private void DoPan(Point screenStart, Point screenEnd) { if (masterPlot != null) { double dx = IsHorizontalNavigationEnabled ? masterPlot.XFromLeft(screenEnd.X) - masterPlot.XFromLeft(screenStart.X) : 0; double dy = IsVerticalNavigationEnabled ? masterPlot.YFromTop(screenEnd.Y) - masterPlot.YFromTop(screenStart.Y) : 0; var rect = masterPlot.PlotRect; double width = rect.Width; double height = rect.Height; masterPlot.SetPlotRect(new DataRect( rect.XMin - dx, rect.YMin - dy, rect.XMin - dx + width, rect.YMin - dy + height)); masterPlot.IsAutoFitEnabled = false; } } private void MouseNavigationLayer_MouseLeave(object sender, MouseEventArgs e) { if (isPanning && (e.OriginalSource == navigationCanvas || e.OriginalSource == masterPlot)) { //panningEnd = e.GetPosition(this); DoPan(panningStart, panningEnd); isPanning = false; } if (isSelecting && (e.OriginalSource == navigationCanvas || e.OriginalSource == masterPlot)) { if (selectArea != null) { if (navigationCanvas.Children.Contains(selectArea)) { navigationCanvas.Children.Remove(selectArea); } if (masterPlot != null && masterPlot.Children.Contains(plot)) { masterPlot.Children.Remove(plot); } } isSelecting = false; selectingStarted = false; } } private void MouseNavigationLayer_MouseMove(object sender, MouseEventArgs e) { Point cursorPosition = e.GetPosition(this); if (!CheckCursor(cursorPosition)) { wasInside = true; MouseNavigationLayer_MouseLeave(sender, e); return; } else { if (wasInside && isLeftClicked) { HandleMouseUp(); HandleMouseDown(e); } } if (isPanning) { if (!transformChangeRequested) { transformChangeRequested = true; panningEnd = e.GetPosition(this); DoPan(panningStart, panningEnd); panningStart = panningEnd; InvalidateArrange(); } } if (isSelecting) { selectEnd = e.GetPosition(this); if (!selectingStarted) { if ((Math.Abs(selectStart.X - selectEnd.X) > 4) || (Math.Abs(selectStart.Y - selectEnd.Y) > 4)) { selectingStarted = true; selectArea = new Rectangle(); selectArea.Fill = new SolidColorBrush(Colors.LightGray); selectArea.StrokeThickness = 2; selectArea.Stroke = new SolidColorBrush(Color.FromArgb(255, 40, 0, 120)); selectArea.Opacity = 0.6; if (masterPlot != null) { plot.IsAutoFitEnabled = false; plot.Children.Clear(); plot.Children.Add(selectArea); if (!masterPlot.Children.Contains(plot)) { masterPlot.Children.Add(plot); Canvas.SetZIndex(plot, 40000); } double width = Math.Abs(masterPlot.XFromLeft(selectStart.X) - masterPlot.XFromLeft(selectEnd.X)); double height = Math.Abs(masterPlot.YFromTop(selectStart.Y) - masterPlot.YFromTop(selectEnd.Y)); double xmin = masterPlot.XFromLeft(Math.Min(selectStart.X, selectEnd.X)); double ymin = masterPlot.YFromTop(Math.Max(selectStart.Y, selectEnd.Y)); Plot.SetX1(selectArea, xmin); Plot.SetY1(selectArea, ymin); Plot.SetX2(selectArea, xmin + width); Plot.SetY2(selectArea, ymin + height); } else { navigationCanvas.Children.Add(selectArea); Canvas.SetLeft(selectArea, selectStart.X); Canvas.SetTop(selectArea, selectStart.Y); } } } else { if (masterPlot == null) { double width = Math.Abs(selectStart.X - selectEnd.X); double height = Math.Abs(selectStart.Y - selectEnd.Y); selectArea.Width = width; selectArea.Height = height; if (selectEnd.X < selectStart.X) { Canvas.SetLeft(selectArea, selectStart.X - width); } if (selectEnd.Y < selectStart.Y) { Canvas.SetTop(selectArea, selectStart.Y - height); } } else { double width = Math.Abs(masterPlot.XFromLeft(selectStart.X) - masterPlot.XFromLeft(selectEnd.X)); double height = Math.Abs(masterPlot.YFromTop(selectStart.Y) - masterPlot.YFromTop(selectEnd.Y)); double xmin = masterPlot.XFromLeft(Math.Min(selectStart.X, selectEnd.X)); double ymin = masterPlot.YFromTop(Math.Max(selectStart.Y, selectEnd.Y)); Plot.SetX1(selectArea, xmin); Plot.SetY1(selectArea, ymin); Plot.SetX2(selectArea, xmin + width); Plot.SetY2(selectArea, ymin + height); } } } wasInside = false; } private void MouseNavigationLayer_MouseRightButtonDown(object sender, MouseButtonEventArgs e) { e.Handled = HandleMouseDown(e); } private void MouseNavigationLayer_MouseRightButtonUp(object sender, MouseButtonEventArgs e) { e.Handled = HandleMouseUp(); } private bool CheckCursor(Point cursorPosition) { return !(cursorPosition.X < 0 || cursorPosition.Y < 0 || cursorPosition.X > this.ActualWidth || cursorPosition.Y > this.ActualHeight); } private bool HandleMouseDown(MouseEventArgs e) { Point cursorPosition = e.GetPosition(this); if (!CheckCursor(cursorPosition)) return false; else { isLeftClicked = true; if (masterPlot != null) { if (Keyboard.Modifiers == ModifierKeys.Shift) { DoZoom(1.2); } else { if (Keyboard.Modifiers == ModifierKeys.Control) { if (selectingMode && IsVerticalNavigationEnabled && IsHorizontalNavigationEnabled) { isSelecting = true; selectStart = cursorPosition; this.CaptureMouse(); } lastClick = DateTime.Now; } else { DateTime d = DateTime.Now; if ((d - lastClick).TotalMilliseconds < 200) { masterPlot.IsAutoFitEnabled = true; return true; } else { isPanning = true; panningStart = cursorPosition; this.CaptureMouse(); lastClick = DateTime.Now; } } } } } if (parentControl != null) parentControl.Focus(); return true; } private bool HandleMouseUp() { isLeftClicked = false; isPanning = false; if ((!isSelecting || !selectingStarted) && (Keyboard.Modifiers == ModifierKeys.Control)) { DateTime d = DateTime.Now; if ((d - lastClick).TotalMilliseconds < 300) { isSelecting = false; DoZoom(1 / 1.2); } } if (isSelecting) { if (selectingStarted) { if (!transformChangeRequested) { transformChangeRequested = true; isSelecting = false; selectingStarted = false; navigationCanvas.Children.Remove(selectArea); if (masterPlot != null) { masterPlot.Children.Remove(plot); double width = Math.Abs(masterPlot.XFromLeft(selectStart.X) - masterPlot.XFromLeft(selectEnd.X)); double height = Math.Abs(masterPlot.YFromTop(selectStart.Y) - masterPlot.YFromTop(selectEnd.Y)); double xmin = masterPlot.XFromLeft(Math.Min(selectStart.X, selectEnd.X)); double ymin = masterPlot.YFromTop(Math.Max(selectStart.Y, selectEnd.Y)); masterPlot.SetPlotRect(new DataRect(xmin, ymin, xmin + width, ymin + height)); masterPlot.IsAutoFitEnabled = false; } } } } this.ReleaseMouseCapture(); return true; } } internal class NavigationPlot : Plot { protected override DataRect ComputeBounds() { return DataRect.Empty; } } }
using UnityEngine; using System; using CotcSdk; using IntegrationTests; using System.Collections; public class MatchTests : TestBase { [Test("Creates a match with the minimum number of arguments and checks that it is created properly (might highlight problems with the usage of the Bundle class).")] public IEnumerator ShouldCreateMatchWithMinimumArgs() { Login(cloud, gamer => { gamer.Matches.Create(maxPlayers: 2) .CompleteTestIfSuccessful(); }); return WaitForEndOfTest(); } [Test("Creates a match, and verifies that the match object seems to be configured appropriately.", "Because of a unit test on a hook, the global state of the matches aren't empty.")] public IEnumerator ShouldCreateMatch() { string matchDesc = "Test match"; Login(cloud, gamer => { gamer.Matches.Create( description: matchDesc, maxPlayers: 2, customProperties: Bundle.CreateObject("test", "value"), shoe: Bundle.CreateArray(1, 2, 3)) .ExpectSuccess(match => { Assert(match.Creator.GamerId == gamer.GamerId, "Match creator not set properly"); Assert(match.CustomProperties["test"] == "value", "Missing custom property"); Assert(match.Description == matchDesc, "Invalid match description"); Assert(match.Moves.Count == 0, "Should not have any move at first"); // Because of a unit test on a hook, the global state of the matches aren't empty //Assert(match.GlobalState.AsDictionary().Count == 0, "Global state should be empty initially"); Assert(match.LastEventId != null, "Last event should not be null"); Assert(match.MatchId != null, "Match ID shouldn't be null"); Assert(match.MaxPlayers == 2, "Should have two players"); Assert(match.Players.Count == 1, "Should contain only one player"); Assert(match.Players[0].GamerId == gamer.GamerId, "Should contain me as player"); Assert(match.Seed != 0, "A 31-bit seed should be provided"); Assert(match.Shoe.AsArray().Count == 0, "The shoe shouldn't be available until the match is finished"); Assert(match.Status == MatchStatus.Running, "The match status is invalid"); CompleteTest(); }); }); return WaitForEndOfTest(); } [Test("Creates a match, and fetches it then, verifying that the match can be continued properly.")] public IEnumerator ShouldContinueMatch() { Login(cloud, gamer => { gamer.Matches.Create(2) .ExpectSuccess(createdMatch => { string matchId = createdMatch.MatchId; gamer.Matches.Fetch(matchId) .ExpectSuccess(fetchedMatch => { Assert(fetchedMatch.MatchId == createdMatch.MatchId, "The fetched match doesn't correspond to the created one"); Assert(fetchedMatch.Players[0].GamerId == gamer.GamerId, "Should contain me as player"); CompleteTest(); }); }); }); return WaitForEndOfTest(); } [Test("Creates a match as one user, and joins with another. Also tries to join again with the same user and expects an error.")] public IEnumerator ShouldJoinMatch() { Login2Users(cloud, (Gamer creator, Gamer joiner) => { creator.Matches.Create(2) .ExpectSuccess(createdMatch => { // Creator should not be able to join again creator.Matches.Join(createdMatch.MatchId) .ExpectFailure(triedJoin => { // But the second player should joiner.Matches.Join(createdMatch.MatchId) .ExpectSuccess(joined => { // Check that the match looks usable Assert(joined.MatchId == createdMatch.MatchId, "The fetched match doesn't correspond to the created one"); Assert(joined.Players[0].GamerId == creator.GamerId, "Should contain creator as player 1"); Assert(joined.Players[1].GamerId == joiner.GamerId, "Should contain joiner as player 2"); CompleteTest(); }); }); }); }); return WaitForEndOfTest(); } [Test("Creates a match and attempts to delete it, and expects it to fail.")] public IEnumerator ShouldFailToDeleteMatch() { Login(cloud, gamer => { gamer.Matches.Create(2) .ExpectSuccess(createResult => { gamer.Matches.Delete(createResult.MatchId) .ExpectFailure(deleteResult => { Assert(deleteResult.ServerData["name"] == "MatchNotFinished", "Should not be able to delete match"); CompleteTest(); }); }); }); return WaitForEndOfTest(); } [Test("Big test that creates a match and simulates playing it with two players. Tries a bit of everything in the API.")] public IEnumerator ShouldPlayMatch() { Login2Users(cloud, (Gamer gamer1, Gamer gamer2) => { Match[] matches = new Match[2]; // Create a match gamer1.Matches.Create(maxPlayers: 2) .ExpectSuccess(matchP1 => { matches[0] = matchP1; // Join with P2 return gamer2.Matches.Join(matchP1.MatchId); }) .ExpectSuccess(matchP2 => { matches[1] = matchP2; // Post a move return matchP2.PostMove(Bundle.CreateObject("x", 1)); }) .ExpectSuccess(movePosted => { Assert(matches[1].Moves.Count == 1, "Should have a move event"); Assert(matches[1].LastEventId != null, "Last event ID shouldn't be null"); Assert(matches[1].Players.Count == 2, "Should contain two players"); // Post another move with global state return matches[1].PostMove(Bundle.CreateObject("x", 2), Bundle.CreateObject("key", "value")); }) .ExpectSuccess(matchPostedGlobalState => { Assert(matches[1].Moves.Count == 1, "Posting a global state should clear events"); Assert(matches[1].GlobalState["key"] == "value", "The global state should have been updated"); // Now make P2 leave return matches[1].Leave(); }) .ExpectSuccess(leftMatch => { // Then update P1's match, and check that it reflects changes made by P2. // Normally these changes should be fetched automatically via events, but we don't handle them in this test. return gamer1.Matches.Fetch(matches[0].MatchId); }) .ExpectSuccess(matchRefreshed => { matches[0] = matchRefreshed; Assert(matches[0].Moves.Count == 1, "Should have a move event (after refresh)"); Assert(matches[0].LastEventId == matches[1].LastEventId, "Last event ID should match"); Assert(matches[0].Players.Count == 1, "Should only contain one player after P2 has left"); // Then finish the match & delete for good return matches[0].Finish(true); }) .ExpectSuccess(matchFinished => { // The match should have been deleted gamer1.Matches.Fetch(matches[0].MatchId) .ExpectFailure(deletedMatch => { Assert(deletedMatch.ServerData["name"] == "BadMatchID", "Expected bad match ID"); CompleteTest(); }); }); }); return WaitForEndOfTest(); } [Test("Creates a match and plays it as two users. Checks that events are broadcasted appropriately.")] public IEnumerator ShouldReceiveEvents() { Login2NewUsers(cloud, (Gamer gamer1, Gamer gamer2) => { DomainEventLoop loopP1 = gamer1.StartEventLoop(); DomainEventLoop loopP2 = gamer2.StartEventLoop(); gamer1.Matches.Create(maxPlayers: 2) .ExpectSuccess(createdMatch => { // 1) P1 subscribe to OnPlayerJoined createdMatch.OnPlayerJoined += (Match sender, MatchJoinEvent e) => { // 4) P2 has joined; wait that he subscribes to the movePosted event. RunOnSignal("p2subscribed", () => { // 5) Now that P2 has joined and is ready, P1 can post a move createdMatch.PostMove(Bundle.CreateObject("x", 3)).ExpectSuccess(); }); }; // Join as P2 gamer2.Matches.Join(createdMatch.MatchId) .ExpectSuccess(joinedMatch => { // 2) P2 Subscribe to OnMovePosted joinedMatch.OnMovePosted += (Match sender, MatchMoveEvent e) => { // 6) P1 sent his move, P2 verify its validity. Test Complete. Assert(e.MoveData["x"] == 3, "Invalid move data"); Assert(e.PlayerId == gamer1.GamerId, "Expected P1 to make move"); loopP1.Stop(); loopP2.Stop(); CompleteTest(); }; // 3) Send a signal to let P1 know that P2 has done its job Signal("p2subscribed"); }); }); }); return WaitForEndOfTest(); } [Test("Tests the reception of an invitation between two players")] public IEnumerator ShouldReceiveInvitation() { Login2NewUsers(cloud, (Gamer gamer1, Gamer gamer2) => { // P2 will create a match and invite P1 gamer2.Matches.Create(maxPlayers: 2) .ExpectSuccess(createMatch => { // P1 will be invited DomainEventLoop loopP1 = gamer1.StartEventLoop(); gamer1.Matches.OnMatchInvitation += (MatchInviteEvent e) => { Assert(e.Inviter.GamerId == gamer2.GamerId, "Invitation should come from P2"); Assert(e.Match.MatchId == createMatch.MatchId, "Should indicate the match ID"); // Test discard functionality (not needed in reality since we are stopping the loop it is registered to) gamer1.Matches.DiscardEventHandlers(); loopP1.Stop(); CompleteTest(); }; // Invite P1 createMatch.InvitePlayer(gamer1.GamerId).ExpectSuccess(); }); }); return WaitForEndOfTest(); } [Test("Tests that the DiscardEventHandlers works properly")] public IEnumerator ShouldDiscardEventHandlers() { Login2NewUsers(cloud, (Gamer gamer1, Gamer gamer2) => { // P2 will create a match and invite P1 gamer2.Matches.Create(maxPlayers: 2) .ExpectSuccess(createMatch => { // P1 will be invited DomainEventLoop loopP1 = gamer1.StartEventLoop(); gamer1.Matches.OnMatchInvitation += (MatchInviteEvent e) => { FailTest("Should be discarded"); }; gamer1.Matches.DiscardEventHandlers(); gamer1.Matches.OnMatchInvitation += (MatchInviteEvent e) => { loopP1.Stop(); CompleteTest(); }; // Invite P1 createMatch.InvitePlayer(gamer1.GamerId).ExpectSuccess(); }); }); return WaitForEndOfTest(); } [Test("Creates a variety of matches and tests the various features of the match listing functionality.")] public IEnumerator ShouldListMatches() { Login2NewUsers(cloud, (gamer1, gamer2) => { int totalMatches = 0; Match[] matches = new Match[4]; // 1) Create a match to which only P1 is participating gamer1.Matches.Create(2) .ExpectSuccess(m1 => { matches[0] = m1; // 2) Create a finished match return gamer1.Matches.Create(2); }) .ExpectSuccess(m2 => { matches[1] = m2; return m2.Finish(); }) .ExpectSuccess(finishedM2 => { // 3) Create a match to which we invite P1 (he should see himself) return gamer2.Matches.Create(2); }) .ExpectSuccess(m3 => { matches[2] = m3; // Invite P1 to match 3 return m3.InvitePlayer(gamer1.GamerId); }) .ExpectSuccess(invitedP1 => { // 4) Create a full match return gamer1.Matches.Create(1); }) .ExpectSuccess(m4 => { matches[3] = m4; // List all matches; by default, not all matches should be returned (i.e. m1 and m3) return gamer1.Matches.List(); }) .ExpectSuccess(list => { Assert(list.Count >= 4, "Should have many results"); totalMatches = list.Total; // List matches to which P1 is participating (i.e. not m1 as m2 is full, m3 created by P2 and m4 full) return gamer1.Matches.List(participating: true); }) .ExpectSuccess(list => { Assert(list.Count == 1, "Should have 1 match"); Assert(list[0].MatchId == matches[0].MatchId, "M1 expected"); // List matches to which P1 is invited (i.e. m3) return gamer1.Matches.List(invited: true); }) .ExpectSuccess(list => { Assert(list.Count == 1, "Should have 1 match"); Assert(list[0].MatchId == matches[2].MatchId, "M3 expected"); // List all matches, including finished ones (i.e. m2) return gamer1.Matches.List(finished: true); }) .ExpectSuccess(list => { Assert(list.Total > totalMatches, "Should list more matches"); // List full matches (i.e. m4) return gamer1.Matches.List(full: true); }) .ExpectSuccess(list => { Assert(list.Total > totalMatches, "Should list more matches"); CompleteTest(); }); }); return WaitForEndOfTest(); } [Test("Tests race conditions between players.")] public IEnumerator ShouldHandleRaceConditions() { Login2NewUsers(cloud, (gamer1, gamer2) => { Match[] matches = new Match[2]; // Create a match, and make P2 join it but start no event loop gamer1.Matches.Create(maxPlayers: 2) .ExpectSuccess(m => { matches[0] = m; return gamer2.Matches.Join(m.MatchId); }) .ExpectSuccess(m => { matches[1] = m; // Then make P2 play into the match created by P1 return m.PostMove(Bundle.CreateObject("x", 2)); }) .ExpectSuccess(dummy => { // P1 will now be desynchronized, try to post a move, which should fail matches[0].PostMove(Bundle.CreateObject("x", 3)) .ExpectFailure(ex => { Assert(ex.ServerData["name"] == "InvalidLastEventId", "Move should be refused"); // Try again after refreshing the match gamer1.Matches.Fetch(matches[0].MatchId) .ExpectSuccess(m => m.PostMove(Bundle.CreateObject("x", 3))) .CompleteTestIfSuccessful(); }); }); }); return WaitForEndOfTest(); } [Test("Test the dismiss invitation functionnality")] public IEnumerator ShouldDismissInvitation() { Login2NewUsers(cloud, (gamer1, gamer2) => { gamer2.Matches.Create(maxPlayers: 2) .ExpectSuccess(createMatch => { // Invite P1 DomainEventLoop loopP1 = gamer1.StartEventLoop(); gamer1.Matches.OnMatchInvitation += (MatchInviteEvent e) => { Assert(e.Inviter.GamerId == gamer2.GamerId, "Invitation should come from P2"); Assert(e.Match.MatchId == createMatch.MatchId, "Should indicate the match ID"); // Test dismiss functionality (not needed in reality since we are stopping the loop it is registered to) gamer1.Matches.DismissInvitation(createMatch.MatchId).ExpectSuccess(done => { CompleteTest(); }); loopP1.Stop(); }; createMatch.InvitePlayer(gamer1.GamerId).ExpectSuccess(); }); }); return WaitForEndOfTest(); } [Test("Test if the Draw From Shoe functionnality works properly")] public IEnumerator ShouldDrawFromShoe() { Login2NewUsers(cloud, (gamer1, gamer2) => { DomainEventLoop l1 = gamer1.StartEventLoop(); DomainEventLoop l2 = gamer2.StartEventLoop(); gamer1.Matches.Create(2, shoe: Bundle.CreateArray(new Bundle(1), new Bundle(2))) .ExpectSuccess(createMatch => { int drawn1 = 0, drawn2 = 0; createMatch.OnShoeDrawn += (match, shoeEvent) => { match.DrawFromShoe() .ExpectSuccess(result => { drawn2 = result["drawnItems"].AsArray()[0]; if (drawn1 == 1) Assert(drawn2 == 2, "Expected to get 2 from shoe, got " + drawn2); else Assert(drawn2 == 1, "Expected to get 1 from shoe, got " + drawn2); return match.DrawFromShoe(2); }) .ExpectSuccess(result => { drawn1 = result["drawnItems"].AsArray()[0]; drawn2 = result["drawnItems"].AsArray()[1]; Assert((drawn1 == 1 && drawn2 == 2) || (drawn1 == 2 && drawn2 == 1), "Expected to get 1/2 or 2/1, got : " + drawn1 + "/" + drawn2); l1.Stop(); l2.Stop(); CompleteTest(); }); }; gamer2.Matches.Join(createMatch.MatchId) .ExpectSuccess(matchJoined => { matchJoined.DrawFromShoe() .ExpectSuccess(result => { drawn1 = result["drawnItems"].AsArray()[0]; Assert(drawn1 == 1 || drawn1 == 2, "Expected drawn 1 or 2 from shoe, got : " + drawn1); createMatch.DrawFromShoe(); }); }); }); }); return WaitForEndOfTest(); } #region Private private string RandomBoardName() { return "board-" + Guid.NewGuid().ToString(); } #endregion }
using System; namespace NServiceKit.Logging.Support.Logging { /// <summary> /// Default logger is to System.Diagnostics.Debug.WriteLine /// /// Made public so its testable /// </summary> public class DebugLogger : ILog { const string DEBUG = "DEBUG: "; const string ERROR = "ERROR: "; const string FATAL = "FATAL: "; const string INFO = "INFO: "; const string WARN = "WARN: "; /// <summary> /// Initializes a new instance of the <see cref="DebugLogger"/> class. /// </summary> /// <param name="type">The type.</param> public DebugLogger(string type) { } /// <summary> /// Initializes a new instance of the <see cref="DebugLogger"/> class. /// </summary> /// <param name="type">The type.</param> public DebugLogger(Type type) { } #region ILog Members /// <summary> /// Logs the specified message. /// </summary> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> private static void Log(object message, Exception exception) { string msg = message == null ? string.Empty : message.ToString(); if (exception != null) { msg += ", Exception: " + exception.Message; } System.Diagnostics.Debug.WriteLine(msg); } /// <summary> /// Logs the format. /// </summary> /// <param name="message">The message.</param> /// <param name="args">The args.</param> private static void LogFormat(object message, params object[] args) { string msg = message == null ? string.Empty : message.ToString(); System.Diagnostics.Debug.WriteLine(string.Format(msg, args)); } /// <summary> /// Logs the specified message. /// </summary> /// <param name="message">The message.</param> private static void Log(object message) { string msg = message == null ? string.Empty : message.ToString(); System.Diagnostics.Debug.WriteLine(msg); } /// <summary>Logs a Debug message and exception.</summary> /// /// <param name="message"> The message.</param> /// <param name="exception">The exception.</param> public void Debug(object message, Exception exception) { Log(DEBUG + message, exception); } /// <summary>Gets a value indicating whether this instance is debug enabled.</summary> /// /// <value><c>true</c> if this instance is debug enabled; otherwise, <c>false</c>.</value> public bool IsDebugEnabled { get { return true; } } /// <summary>Logs a Debug message.</summary> /// /// <param name="message">The message.</param> public void Debug(object message) { Log(DEBUG + message); } /// <summary>Logs a Debug format message.</summary> /// /// <param name="format">The format.</param> /// <param name="args"> The args.</param> public void DebugFormat(string format, params object[] args) { LogFormat(DEBUG + format, args); } /// <summary>Logs a Error message and exception.</summary> /// /// <param name="message"> The message.</param> /// <param name="exception">The exception.</param> public void Error(object message, Exception exception) { Log(ERROR + message, exception); } /// <summary>Logs a Error message.</summary> /// /// <param name="message">The message.</param> public void Error(object message) { Log(ERROR + message); } /// <summary>Logs a Error format message.</summary> /// /// <param name="format">The format.</param> /// <param name="args"> The args.</param> public void ErrorFormat(string format, params object[] args) { LogFormat(ERROR + format, args); } /// <summary>Logs a Fatal message and exception.</summary> /// /// <param name="message"> The message.</param> /// <param name="exception">The exception.</param> public void Fatal(object message, Exception exception) { Log(FATAL + message, exception); } /// <summary>Logs a Fatal message.</summary> /// /// <param name="message">The message.</param> public void Fatal(object message) { Log(FATAL + message); } /// <summary>Logs a Error format message.</summary> /// /// <param name="format">The format.</param> /// <param name="args"> The args.</param> public void FatalFormat(string format, params object[] args) { LogFormat(FATAL + format, args); } /// <summary>Logs an Info message and exception.</summary> /// /// <param name="message"> The message.</param> /// <param name="exception">The exception.</param> public void Info(object message, Exception exception) { Log(INFO + message, exception); } /// <summary>Logs an Info message and exception.</summary> /// /// <param name="message">The message.</param> public void Info(object message) { Log(INFO + message); } /// <summary>Logs an Info format message.</summary> /// /// <param name="format">The format.</param> /// <param name="args"> The args.</param> public void InfoFormat(string format, params object[] args) { LogFormat(INFO + format, args); } /// <summary>Logs a Warning message and exception.</summary> /// /// <param name="message"> The message.</param> /// <param name="exception">The exception.</param> public void Warn(object message, Exception exception) { Log(WARN + message, exception); } /// <summary>Logs a Warning message.</summary> /// /// <param name="message">The message.</param> public void Warn(object message) { Log(WARN + message); } /// <summary>Logs a Warning format message.</summary> /// /// <param name="format">The format.</param> /// <param name="args"> The args.</param> public void WarnFormat(string format, params object[] args) { LogFormat(WARN + format, args); } #endregion } }
using System.Linq; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.Collections; using FluentNHibernate.Testing.DomainModel.Mapping; using NUnit.Framework; namespace FluentNHibernate.Testing.FluentInterfaceTests { [TestFixture] public class OneToManyMutablePropertyModelGenerationTests : BaseModelFixture { [Test] public void AccessShouldSetModelAccessPropertyToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Access.Field()) .ModelShouldMatch(x => x.Access.ShouldEqual("field")); } [Test] public void BatchSizeShouldSetModelBatchSizePropertyToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.BatchSize(10)) .ModelShouldMatch(x => x.BatchSize.ShouldEqual(10)); } [Test] public void CacheShouldSetModelCachePropertyToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Cache.ReadOnly()) .ModelShouldMatch(x => { x.Cache.ShouldNotBeNull(); x.Cache.Usage.ShouldEqual("read-only"); }); } [Test] public void CascadeShouldSetModelCascadePropertyToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Cascade.All()) .ModelShouldMatch(x => x.Cascade.ShouldEqual("all")); } [Test] public void CascadeShouldAppendModelCascadePropertyToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => { m.Cascade.SaveUpdate(); m.Cascade.Merge(); }) .ModelShouldMatch(x => x.Cascade.ShouldEqual("save-update,merge")); } [Test] public void CollectionTypeShouldSetModelCollectionTypePropertyToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.CollectionType("type")) .ModelShouldMatch(x => x.CollectionType.ShouldEqual(new TypeReference("type"))); } [Test] public void ForeignKeyCascadeOnDeleteShouldSetModelKeyOnDeletePropertyToCascade() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.ForeignKeyCascadeOnDelete()) .ModelShouldMatch(x => x.Key.OnDelete.ShouldEqual("cascade")); } [Test] public void InverseShouldSetModelInversePropertyToTrue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Inverse()) .ModelShouldMatch(x => x.Inverse.ShouldBeTrue()); } [Test] public void NotInverseShouldSetModelInversePropertyToFalse() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Not.Inverse()) .ModelShouldMatch(x => x.Inverse.ShouldBeFalse()); } [Test] public void KeyColumnNameShouldAddColumnToModelKeyColumnsCollection() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.KeyColumn("col")) .ModelShouldMatch(x => x.Key.Columns.Count().ShouldEqual(1)); } [Test] public void KeyColumnNamesShouldAddColumnsToModelKeyColumnsCollection() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.KeyColumns.Add("col1", "col2")) .ModelShouldMatch(x => x.Key.Columns.Count().ShouldEqual(2)); } [Test] public void LazyLoadShouldSetModelLazyPropertyToTrue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.LazyLoad()) .ModelShouldMatch(x => x.Lazy.ShouldEqual(Lazy.True)); } [Test] public void NotLazyLoadShouldSetModelLazyPropertyToFalse() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Not.LazyLoad()) .ModelShouldMatch(x => x.Lazy.ShouldEqual(Lazy.False)); } [Test] public void ExtraLazyLoadShouldSetModelLazyPropertyToExtra() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.ExtraLazyLoad()) .ModelShouldMatch(x => x.Lazy.ShouldEqual(Lazy.Extra)); } [Test] public void NotExtraLazyLoadShouldSetModelLazyPropertyToTrue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Not.ExtraLazyLoad()) .ModelShouldMatch(x => x.Lazy.ShouldEqual(Lazy.True)); } [Test] public void NotFoundShouldSetModelRelationshipNotFoundPropertyToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.NotFound.Ignore()) .ModelShouldMatch(x => ((OneToManyMapping)x.Relationship).NotFound.ShouldEqual("ignore")); } [Test] public void WhereShouldSetModelWherePropertyToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Where("x = 1")) .ModelShouldMatch(x => x.Where.ShouldEqual("x = 1")); } [Test] public void WithForeignKeyConstraintNameShouldSetModelKeyForeignKeyPropertyToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.ForeignKeyConstraintName("fk")) .ModelShouldMatch(x => x.Key.ForeignKey.ShouldEqual("fk")); } [Test] public void WithTableNameShouldSetModelTableNamePropertyToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Table("t")) .ModelShouldMatch(x => x.TableName.ShouldEqual("t")); } [Test] public void SchemaIsShouldSetModelSchemaPropertyToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Schema("dto")) .ModelShouldMatch(x => x.Schema.ShouldEqual("dto")); } [Test] public void FetchShouldSetModelFetchPropertyToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Fetch.Select()) .ModelShouldMatch(x => x.Fetch.ShouldEqual("select")); } [Test] public void PersisterShouldSetModelPersisterPropertyToAssemblyQualifiedName() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Persister<CustomPersister>()) .ModelShouldMatch(x => x.Persister.GetUnderlyingSystemType().ShouldEqual(typeof(CustomPersister))); } [Test] public void CheckShouldSetModelCheckToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Check("x > 100")) .ModelShouldMatch(x => x.Check.ShouldEqual("x > 100")); } [Test] public void OptimisticLockShouldSetModelOptimisticLockToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.OptimisticLock()) .ModelShouldMatch(x => x.OptimisticLock.ShouldEqual(true)); } [Test] public void GenericShouldSetModelGenericToTrue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Generic()) .ModelShouldMatch(x => x.Generic.ShouldBeTrue()); } [Test] public void NotGenericShouldSetModelGenericToFalse() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Not.Generic()) .ModelShouldMatch(x => x.Generic.ShouldBeFalse()); } [Test] public void ReadOnlyShouldSetModelMutableToFalse() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.ReadOnly()) .ModelShouldMatch(x => x.Mutable.ShouldBeFalse()); } [Test] public void NotReadOnlyShouldSetModelMutableToTrue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Not.ReadOnly()) .ModelShouldMatch(x => x.Mutable.ShouldBeTrue()); } [Test] public void SubselectShouldSetModelSubselectToValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Subselect("whee")) .ModelShouldMatch(x => x.Subselect.ShouldEqual("whee")); } [Test] public void KeyUpdateShouldSetModelValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.KeyUpdate()) .ModelShouldMatch(x => x.Key.Update.ShouldBeTrue()); } [Test] public void KeyNullableShouldSetModelValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.KeyNullable()) .ModelShouldMatch(x => x.Key.NotNull.ShouldBeFalse()); } [Test] public void KeyNotNullableShouldSetModelValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.Not.KeyNullable()) .ModelShouldMatch(x => x.Key.NotNull.ShouldBeTrue()); } [Test] public void PropertyRefShouldSetModelValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.PropertyRef("prop1")) .ModelShouldMatch(x => x.Key.PropertyRef.ShouldEqual("prop1")); } [Test] public void EntityNameShouldSetModelValue() { OneToMany(x => x.BagOfChildren) .Mapping(m => m.EntityName("name")) .ModelShouldMatch(x => x.Relationship.EntityName.ShouldEqual("name")); } } }
// 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 Internal.Runtime; using Internal.Text; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace ILCompiler.DependencyAnalysis { public class GCStaticDescNode : EmbeddedObjectNode, ISymbolDefinitionNode { private MetadataType _type; private GCPointerMap _gcMap; private bool _isThreadStatic; public GCStaticDescNode(MetadataType type, bool isThreadStatic) { _type = type; _gcMap = isThreadStatic ? GCPointerMap.FromThreadStaticLayout(type) : GCPointerMap.FromStaticLayout(type); _isThreadStatic = isThreadStatic; } protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(GetMangledName(nameMangler, _type, _isThreadStatic)); } public static string GetMangledName(NameMangler nameMangler, MetadataType type, bool isThreadStatic) { string prefix = isThreadStatic ? "__ThreadStaticGCDesc_" : "__GCStaticDesc_"; return prefix + nameMangler.GetMangledTypeName(type); } public int NumSeries { get { return _gcMap.NumSeries; } } int ISymbolNode.Offset => 0; int ISymbolDefinitionNode.Offset => OffsetFromBeginningOfArray; private GCStaticDescRegionNode Region(NodeFactory factory) { UtcNodeFactory utcNodeFactory = (UtcNodeFactory)factory; if (_type.IsCanonicalSubtype(CanonicalFormKind.Any)) { return null; } else { if (_isThreadStatic) { return utcNodeFactory.ThreadStaticGCDescRegion; } else { return utcNodeFactory.GCStaticDescRegion; } } } private ISymbolNode GCStaticsSymbol(NodeFactory factory) { UtcNodeFactory utcNodeFactory = (UtcNodeFactory)factory; if (_isThreadStatic) { return utcNodeFactory.TypeThreadStaticsSymbol(_type); } else { return utcNodeFactory.TypeGCStaticsSymbol(_type); } } protected override void OnMarked(NodeFactory factory) { GCStaticDescRegionNode region = Region(factory); if (region != null) region.AddEmbeddedObject(this); } public override bool StaticDependenciesAreComputed { get { return true; } } public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory) { DependencyListEntry[] result; if (!_type.IsCanonicalSubtype(CanonicalFormKind.Any)) { result = new DependencyListEntry[2]; result[0] = new DependencyListEntry(Region(factory), "GCStaticDesc Region"); result[1] = new DependencyListEntry(GCStaticsSymbol(factory), "GC Static Base Symbol"); } else { Debug.Assert(Region(factory) == null); result = new DependencyListEntry[1]; result[0] = new DependencyListEntry(((UtcNodeFactory)factory).StandaloneGCStaticDescRegion(this), "Standalone GCStaticDesc holder"); } return result; } public override void EncodeData(ref ObjectDataBuilder builder, NodeFactory factory, bool relocsOnly) { int gcFieldCount = 0; int startIndex = 0; int numSeries = 0; for (int i = 0; i < _gcMap.Size; i++) { // Skip non-GC fields if (!_gcMap[i]) continue; gcFieldCount++; if (i == 0 || !_gcMap[i - 1]) { // The cell starts a new series startIndex = i; } if (i == _gcMap.Size - 1 || !_gcMap[i + 1]) { if (_type.IsCanonicalSubtype(CanonicalFormKind.Any)) { // The cell ends the current series builder.EmitInt(gcFieldCount * factory.Target.PointerSize); builder.EmitInt(startIndex * factory.Target.PointerSize); } else { // The cell ends the current series builder.EmitInt(gcFieldCount); if (_isThreadStatic) { builder.EmitReloc(factory.TypeThreadStaticsSymbol(_type), RelocType.IMAGE_REL_SECREL, startIndex * factory.Target.PointerSize); } else { builder.EmitReloc(factory.TypeGCStaticsSymbol(_type), RelocType.IMAGE_REL_BASED_RELPTR32, startIndex * factory.Target.PointerSize); } } gcFieldCount = 0; numSeries++; } } Debug.Assert(numSeries == NumSeries); } internal int CompareTo(GCStaticDescNode other, TypeSystemComparer comparer) { var compare = _isThreadStatic.CompareTo(other._isThreadStatic); return compare != 0 ? compare : comparer.Compare(_type, other._type); } protected internal override int ClassCode => 2142332918; protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) { return comparer.Compare(_type, ((GCStaticDescNode)other)._type); } } public class GCStaticDescRegionNode : ArrayOfEmbeddedDataNode<GCStaticDescNode> { public GCStaticDescRegionNode(string startSymbolMangledName, string endSymbolMangledName) : base(startSymbolMangledName, endSymbolMangledName, null) { } protected override void GetElementDataForNodes(ref ObjectDataBuilder builder, NodeFactory factory, bool relocsOnly) { int numSeries = 0; foreach (GCStaticDescNode descNode in NodesList) { numSeries += descNode.NumSeries; } builder.EmitInt(numSeries); foreach (GCStaticDescNode node in NodesList) { if (!relocsOnly) node.InitializeOffsetFromBeginningOfArray(builder.CountBytes); node.EncodeData(ref builder, factory, relocsOnly); builder.AddSymbol(node); } } } public class StandaloneGCStaticDescRegionNode : ObjectNode { GCStaticDescNode _standaloneGCStaticDesc; public StandaloneGCStaticDescRegionNode(GCStaticDescNode standaloneGCStaticDesc) { _standaloneGCStaticDesc = standaloneGCStaticDesc; } public override ObjectNodeSection Section => ObjectNodeSection.ReadOnlyDataSection; public override bool IsShareable => true; public override bool StaticDependenciesAreComputed => true; public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); builder.RequireInitialPointerAlignment(); builder.AddSymbol(_standaloneGCStaticDesc); _standaloneGCStaticDesc.InitializeOffsetFromBeginningOfArray(0); builder.EmitInt(_standaloneGCStaticDesc.NumSeries); _standaloneGCStaticDesc.EncodeData(ref builder, factory, relocsOnly); return builder.ToObjectData(); } protected override string GetName(NodeFactory context) { return "Standalone" + _standaloneGCStaticDesc.GetMangledName(context.NameMangler); } protected internal override int ClassCode => 2091208431; protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) { return _standaloneGCStaticDesc.CompareTo(((StandaloneGCStaticDescRegionNode)other)._standaloneGCStaticDesc, comparer); } } }
/* * Copyright 2002-2015 Drew Noakes * * Modified by Yakov Danilov <yakodani@gmail.com> for Imazen LLC (Ported from Java to C#) * 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. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ using System; using System.IO; using Com.Drew.Imaging.Jpeg; using Com.Drew.Lang; using JetBrains.Annotations; using Sharpen; namespace Com.Drew.Metadata.Iptc { /// <summary> /// Decodes IPTC binary data, populating a /// <see cref="Com.Drew.Metadata.Metadata"/> /// object with tag values in an /// <see cref="IptcDirectory"/> /// . /// <p> /// http://www.iptc.org/std/IIM/4.1/specification/IIMV4.1.pdf /// </summary> /// <author>Drew Noakes https://drewnoakes.com</author> public class IptcReader : JpegSegmentMetadataReader { // TODO consider breaking the IPTC section up into multiple directories and providing segregation of each IPTC directory /* public static final int DIRECTORY_IPTC = 2; public static final int ENVELOPE_RECORD = 1; public static final int APPLICATION_RECORD_2 = 2; public static final int APPLICATION_RECORD_3 = 3; public static final int APPLICATION_RECORD_4 = 4; public static final int APPLICATION_RECORD_5 = 5; public static final int APPLICATION_RECORD_6 = 6; public static final int PRE_DATA_RECORD = 7; public static final int DATA_RECORD = 8; public static final int POST_DATA_RECORD = 9; */ [NotNull] public virtual Iterable<JpegSegmentType> GetSegmentTypes() { return Arrays.AsList(JpegSegmentType.Appd).AsIterable(); } public virtual void ReadJpegSegments([NotNull] Iterable<sbyte[]> segments, [NotNull] Com.Drew.Metadata.Metadata metadata, [NotNull] JpegSegmentType segmentType) { foreach (sbyte[] segmentBytes in segments) { // Ensure data starts with the IPTC marker byte if (segmentBytes.Length != 0 && segmentBytes[0] == unchecked((int)(0x1c))) { Extract(new SequentialByteArrayReader(segmentBytes), metadata, segmentBytes.Length); } } } /// <summary> /// Performs the IPTC data extraction, adding found values to the specified instance of /// <see cref="Com.Drew.Metadata.Metadata"/> /// . /// </summary> public virtual void Extract([NotNull] SequentialReader reader, [NotNull] Com.Drew.Metadata.Metadata metadata, long length) { IptcDirectory directory = new IptcDirectory(); metadata.AddDirectory(directory); int offset = 0; // for each tag while (offset < length) { // identifies start of a tag short startByte; try { startByte = reader.GetUInt8(); offset++; } catch (IOException) { directory.AddError("Unable to read starting byte of IPTC tag"); return; } if (startByte != unchecked((int)(0x1c))) { // NOTE have seen images where there was one extra byte at the end, giving // offset==length at this point, which is not worth logging as an error. if (offset != length) { directory.AddError("Invalid IPTC tag marker at offset " + (offset - 1) + ". Expected '0x1c' but got '0x" + Sharpen.Extensions.ToHexString(startByte) + "'."); } return; } // we need at least five bytes left to read a tag if (offset + 5 >= length) { directory.AddError("Too few bytes remain for a valid IPTC tag"); return; } int directoryType; int tagType; int tagByteCount; try { directoryType = reader.GetUInt8(); tagType = reader.GetUInt8(); // TODO support Extended DataSet Tag (see 1.5(c), p14, IPTC-IIMV4.2.pdf) tagByteCount = reader.GetUInt16(); offset += 4; } catch (IOException) { directory.AddError("IPTC data segment ended mid-way through tag descriptor"); return; } if (offset + tagByteCount > length) { directory.AddError("Data for tag extends beyond end of IPTC segment"); return; } try { ProcessTag(reader, directory, directoryType, tagType, tagByteCount); } catch (IOException) { directory.AddError("Error processing IPTC tag"); return; } offset += tagByteCount; } } /// <exception cref="System.IO.IOException"/> private void ProcessTag([NotNull] SequentialReader reader, [NotNull] Com.Drew.Metadata.Directory directory, int directoryType, int tagType, int tagByteCount) { int tagIdentifier = tagType | (directoryType << 8); // Some images have been seen that specify a zero byte tag, which cannot be of much use. // We elect here to completely ignore the tag. The IPTC specification doesn't mention // anything about the interpretation of this situation. // https://raw.githubusercontent.com/wiki/drewnoakes/metadata-extractor/docs/IPTC-IIMV4.2.pdf if (tagByteCount == 0) { directory.SetString(tagIdentifier, string.Empty); return; } string @string = null; switch (tagIdentifier) { case IptcDirectory.TagCodedCharacterSet: { sbyte[] bytes = reader.GetBytes(tagByteCount); string charset = Iso2022Converter.ConvertISO2022CharsetToJavaCharset(bytes); if (charset == null) { // Unable to determine the charset, so fall through and treat tag as a regular string @string = Sharpen.Runtime.GetStringForBytes(bytes); break; } directory.SetString(tagIdentifier, charset); return; } case IptcDirectory.TagEnvelopeRecordVersion: case IptcDirectory.TagApplicationRecordVersion: case IptcDirectory.TagFileVersion: case IptcDirectory.TagArmVersion: case IptcDirectory.TagProgramVersion: { // short if (tagByteCount >= 2) { int shortValue = reader.GetUInt16(); reader.Skip(tagByteCount - 2); directory.SetInt(tagIdentifier, shortValue); return; } break; } case IptcDirectory.TagUrgency: { // byte directory.SetInt(tagIdentifier, reader.GetUInt8()); reader.Skip(tagByteCount - 1); return; } case IptcDirectory.TagReleaseDate: case IptcDirectory.TagDateCreated: { // Date object if (tagByteCount >= 8) { @string = reader.GetString(tagByteCount); try { int year = System.Convert.ToInt32(Sharpen.Runtime.Substring(@string, 0, 4)); int month = System.Convert.ToInt32(Sharpen.Runtime.Substring(@string, 4, 6)) - 1; int day = System.Convert.ToInt32(Sharpen.Runtime.Substring(@string, 6, 8)); DateTime date = new Sharpen.GregorianCalendar(year, month, day).GetTime(); directory.SetDate(tagIdentifier, date); return; } catch (FormatException) { } } else { // fall through and we'll process the 'string' value below reader.Skip(tagByteCount); } goto case IptcDirectory.TagReleaseTime; } case IptcDirectory.TagReleaseTime: case IptcDirectory.TagTimeCreated: default: { break; } } // time... // fall through // If we haven't returned yet, treat it as a string // NOTE that there's a chance we've already loaded the value as a string above, but failed to parse the value if (@string == null) { string encoding = directory.GetString(IptcDirectory.TagCodedCharacterSet); if (encoding != null) { @string = reader.GetString(tagByteCount, encoding); } else { sbyte[] bytes_1 = reader.GetBytes(tagByteCount); encoding = Iso2022Converter.GuessEncoding(bytes_1); @string = encoding != null ? Sharpen.Runtime.GetStringForBytes(bytes_1, encoding) : Sharpen.Runtime.GetStringForBytes(bytes_1); } } if (directory.ContainsTag(tagIdentifier)) { // this fancy string[] business avoids using an ArrayList for performance reasons string[] oldStrings = directory.GetStringArray(tagIdentifier); string[] newStrings; if (oldStrings == null) { newStrings = new string[1]; } else { newStrings = new string[oldStrings.Length + 1]; System.Array.Copy(oldStrings, 0, newStrings, 0, oldStrings.Length); } newStrings[newStrings.Length - 1] = @string; directory.SetStringArray(tagIdentifier, newStrings); } else { directory.SetString(tagIdentifier, @string); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // namespace System.Collections.ObjectModel { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.ComVisible(false)] [DebuggerTypeProxy(typeof(Mscorlib_KeyedCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public abstract class KeyedCollection<TKey,TItem>: Collection<TItem> { const int defaultThreshold = 0; IEqualityComparer<TKey> comparer; Dictionary<TKey,TItem> dict; int keyCount; int threshold; protected KeyedCollection(): this(null, defaultThreshold) {} protected KeyedCollection(IEqualityComparer<TKey> comparer): this(comparer, defaultThreshold) {} protected KeyedCollection(IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold) : base(new List<TItem>()) { // Be explicit about the use of List<T> so we can foreach over // Items internally without enumerator allocations. if (comparer == null) { comparer = EqualityComparer<TKey>.Default; } if (dictionaryCreationThreshold == -1) { dictionaryCreationThreshold = int.MaxValue; } if( dictionaryCreationThreshold < -1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.dictionaryCreationThreshold, ExceptionResource.ArgumentOutOfRange_InvalidThreshold); } this.comparer = comparer; this.threshold = dictionaryCreationThreshold; } /// <summary> /// Enables the use of foreach internally without allocations using <see cref="List{T}"/>'s struct enumerator. /// </summary> new private List<TItem> Items { get { Debug.Assert(base.Items is List<TItem>); return (List<TItem>)base.Items; } } public IEqualityComparer<TKey> Comparer { get { return comparer; } } public TItem this[TKey key] { get { if( key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (dict != null) { return dict[key]; } foreach (TItem item in Items) { if (comparer.Equals(GetKeyForItem(item), key)) return item; } ThrowHelper.ThrowKeyNotFoundException(); return default(TItem); } } public bool Contains(TKey key) { if( key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (dict != null) { return dict.ContainsKey(key); } foreach (TItem item in Items) { if (comparer.Equals(GetKeyForItem(item), key)) return true; } return false; } private bool ContainsItem(TItem item) { TKey key; if( (dict == null) || ((key = GetKeyForItem(item)) == null)) { return Items.Contains(item); } TItem itemInDict; bool exist = dict.TryGetValue(key, out itemInDict); if( exist) { return EqualityComparer<TItem>.Default.Equals(itemInDict, item); } return false; } public bool Remove(TKey key) { if( key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (dict != null) { if (dict.ContainsKey(key)) { return Remove(dict[key]); } return false; } for (int i = 0; i < Items.Count; i++) { if (comparer.Equals(GetKeyForItem(Items[i]), key)) { RemoveItem(i); return true; } } return false; } protected IDictionary<TKey,TItem> Dictionary { get { return dict; } } protected void ChangeItemKey(TItem item, TKey newKey) { // check if the item exists in the collection if( !ContainsItem(item)) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_ItemNotExist); } TKey oldKey = GetKeyForItem(item); if (!comparer.Equals(oldKey, newKey)) { if (newKey != null) { AddKey(newKey, item); } if (oldKey != null) { RemoveKey(oldKey); } } } protected override void ClearItems() { base.ClearItems(); if (dict != null) { dict.Clear(); } keyCount = 0; } protected abstract TKey GetKeyForItem(TItem item); protected override void InsertItem(int index, TItem item) { TKey key = GetKeyForItem(item); if (key != null) { AddKey(key, item); } base.InsertItem(index, item); } protected override void RemoveItem(int index) { TKey key = GetKeyForItem(Items[index]); if (key != null) { RemoveKey(key); } base.RemoveItem(index); } protected override void SetItem(int index, TItem item) { TKey newKey = GetKeyForItem(item); TKey oldKey = GetKeyForItem(Items[index]); if (comparer.Equals(oldKey, newKey)) { if (newKey != null && dict != null) { dict[newKey] = item; } } else { if (newKey != null) { AddKey(newKey, item); } if (oldKey != null) { RemoveKey(oldKey); } } base.SetItem(index, item); } private void AddKey(TKey key, TItem item) { if (dict != null) { dict.Add(key, item); } else if (keyCount == threshold) { CreateDictionary(); dict.Add(key, item); } else { if (Contains(key)) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); } keyCount++; } } private void CreateDictionary() { dict = new Dictionary<TKey,TItem>(comparer); foreach (TItem item in Items) { TKey key = GetKeyForItem(item); if (key != null) { dict.Add(key, item); } } } private void RemoveKey(TKey key) { Debug.Assert(key != null, "key shouldn't be null!"); if (dict != null) { dict.Remove(key); } else { keyCount--; } } } }
//----------------------------------------------------------------------------- // Author : hiyohiyo // Mail : hiyohiyo@crystalmark.info // Web : http://openlibsys.org/ // License : The modified BSD license // // Copyright 2007-2009 OpenLibSys.org. All rights reserved. //----------------------------------------------------------------------------- // This is support library for WinRing0 1.3.x. using System; using System.Runtime.InteropServices; namespace RoseHA { public class Ols : IDisposable { const string dllNameX64 = "WinRing0x64.dll"; const string dllName = "WinRing0.dll"; // for this support library public enum Status { NO_ERROR = 0, DLL_NOT_FOUND = 1, DLL_INCORRECT_VERSION = 2, DLL_INITIALIZE_ERROR = 3, } // for WinRing0 public enum OlsDllStatus { OLS_DLL_NO_ERROR = 0, OLS_DLL_UNSUPPORTED_PLATFORM = 1, OLS_DLL_DRIVER_NOT_LOADED = 2, OLS_DLL_DRIVER_NOT_FOUND = 3, OLS_DLL_DRIVER_UNLOADED = 4, OLS_DLL_DRIVER_NOT_LOADED_ON_NETWORK = 5, OLS_DLL_UNKNOWN_ERROR = 9 } // for WinRing0 public enum OlsDriverType { OLS_DRIVER_TYPE_UNKNOWN = 0, OLS_DRIVER_TYPE_WIN_9X = 1, OLS_DRIVER_TYPE_WIN_NT = 2, OLS_DRIVER_TYPE_WIN_NT4 = 3, // Obsolete OLS_DRIVER_TYPE_WIN_NT_X64 = 4, OLS_DRIVER_TYPE_WIN_NT_IA64 = 5 } // for WinRing0 public enum OlsErrorPci : uint { OLS_ERROR_PCI_BUS_NOT_EXIST = 0xE0000001, OLS_ERROR_PCI_NO_DEVICE = 0xE0000002, OLS_ERROR_PCI_WRITE_CONFIG = 0xE0000003, OLS_ERROR_PCI_READ_CONFIG = 0xE0000004 } // Bus Number, Device Number and Function Number to PCI Device Address public uint PciBusDevFunc(uint bus, uint dev, uint func) { return ((bus&0xFF)<<8) | ((dev&0x1F)<<3) | (func&7); } // PCI Device Address to Bus Number public uint PciGetBus(uint address) { return ((address>>8) & 0xFF); } // PCI Device Address to Device Number public uint PciGetDev(uint address) { return ((address>>3) & 0x1F); } // PCI Device Address to Function Number public uint PciGetFunc(uint address) { return (address&7); } [DllImport("kernel32")] public extern static IntPtr LoadLibrary(string lpFileName); [DllImport("kernel32", SetLastError = true)] private static extern bool FreeLibrary(IntPtr hModule); [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = false)] private static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName); private IntPtr module = IntPtr.Zero; private uint status = (uint)Status.NO_ERROR; public Ols() { string fileName; if (System.IntPtr.Size == 8) { fileName = dllNameX64; } else { fileName = dllName; } module = Ols.LoadLibrary(fileName); if (module == IntPtr.Zero) { status = (uint)Status.DLL_NOT_FOUND; } else { GetDllStatus = (_GetDllStatus)GetDelegate("GetDllStatus", typeof(_GetDllStatus)); GetDllVersion = (_GetDllVersion)GetDelegate("GetDllVersion", typeof(_GetDllVersion)); GetDriverVersion = (_GetDriverVersion)GetDelegate("GetDriverVersion", typeof(_GetDriverVersion)); GetDriverType = (_GetDriverType)GetDelegate("GetDriverType", typeof(_GetDriverType)); InitializeOls = (_InitializeOls)GetDelegate("InitializeOls", typeof(_InitializeOls)); DeinitializeOls = (_DeinitializeOls)GetDelegate("DeinitializeOls", typeof(_DeinitializeOls)); IsCpuid = (_IsCpuid)GetDelegate("IsCpuid", typeof(_IsCpuid)); IsMsr = (_IsMsr)GetDelegate("IsMsr", typeof(_IsMsr)); IsTsc = (_IsTsc)GetDelegate("IsTsc", typeof(_IsTsc)); Hlt = (_Hlt)GetDelegate("Hlt", typeof(_Hlt)); HltTx = (_HltTx)GetDelegate("HltTx", typeof(_HltTx)); HltPx = (_HltPx)GetDelegate("HltPx", typeof(_HltPx)); Rdmsr = (_Rdmsr)GetDelegate("Rdmsr", typeof(_Rdmsr)); RdmsrTx = (_RdmsrTx)GetDelegate("RdmsrTx", typeof(_RdmsrTx)); RdmsrPx = (_RdmsrPx)GetDelegate("RdmsrPx", typeof(_RdmsrPx)); Wrmsr = (_Wrmsr)GetDelegate("Wrmsr", typeof(_Wrmsr)); WrmsrTx = (_WrmsrTx)GetDelegate("WrmsrTx", typeof(_WrmsrTx)); WrmsrPx = (_WrmsrPx)GetDelegate("WrmsrPx", typeof(_WrmsrPx)); Rdpmc = (_Rdpmc)GetDelegate("Rdpmc", typeof(_Rdpmc)); RdpmcTx = (_RdpmcTx)GetDelegate("RdpmcTx", typeof(_RdpmcTx)); RdpmcPx = (_RdpmcPx)GetDelegate("RdpmcPx", typeof(_RdpmcPx)); Cpuid = (_Cpuid)GetDelegate("Cpuid", typeof(_Cpuid)); CpuidTx = (_CpuidTx)GetDelegate("CpuidTx", typeof(_CpuidTx)); CpuidPx = (_CpuidPx)GetDelegate("CpuidPx", typeof(_CpuidPx)); Rdtsc = (_Rdtsc)GetDelegate("Rdtsc", typeof(_Rdtsc)); RdtscTx = (_RdtscTx)GetDelegate("RdtscTx", typeof(_RdtscTx)); RdtscPx = (_RdtscPx)GetDelegate("RdtscPx", typeof(_RdtscPx)); ReadIoPortByte = (_ReadIoPortByte)GetDelegate("ReadIoPortByte", typeof(_ReadIoPortByte)); ReadIoPortWord = (_ReadIoPortWord)GetDelegate("ReadIoPortWord", typeof(_ReadIoPortWord)); ReadIoPortDword = (_ReadIoPortDword)GetDelegate("ReadIoPortDword", typeof(_ReadIoPortDword)); ReadIoPortByteEx = (_ReadIoPortByteEx)GetDelegate("ReadIoPortByteEx", typeof(_ReadIoPortByteEx)); ReadIoPortWordEx = (_ReadIoPortWordEx)GetDelegate("ReadIoPortWordEx", typeof(_ReadIoPortWordEx)); ReadIoPortDwordEx = (_ReadIoPortDwordEx)GetDelegate("ReadIoPortDwordEx", typeof(_ReadIoPortDwordEx)); WriteIoPortByte = (_WriteIoPortByte)GetDelegate("WriteIoPortByte", typeof(_WriteIoPortByte)); WriteIoPortWord = (_WriteIoPortWord)GetDelegate("WriteIoPortWord", typeof(_WriteIoPortWord)); WriteIoPortDword = (_WriteIoPortDword)GetDelegate("WriteIoPortDword", typeof(_WriteIoPortDword)); WriteIoPortByteEx = (_WriteIoPortByteEx)GetDelegate("WriteIoPortByteEx", typeof(_WriteIoPortByteEx)); WriteIoPortWordEx = (_WriteIoPortWordEx)GetDelegate("WriteIoPortWordEx", typeof(_WriteIoPortWordEx)); WriteIoPortDwordEx = (_WriteIoPortDwordEx)GetDelegate("WriteIoPortDwordEx", typeof(_WriteIoPortDwordEx)); SetPciMaxBusIndex = (_SetPciMaxBusIndex)GetDelegate("SetPciMaxBusIndex", typeof(_SetPciMaxBusIndex)); ReadPciConfigByte = (_ReadPciConfigByte)GetDelegate("ReadPciConfigByte", typeof(_ReadPciConfigByte)); ReadPciConfigWord = (_ReadPciConfigWord)GetDelegate("ReadPciConfigWord", typeof(_ReadPciConfigWord)); ReadPciConfigDword = (_ReadPciConfigDword)GetDelegate("ReadPciConfigDword", typeof(_ReadPciConfigDword)); ReadPciConfigByteEx = (_ReadPciConfigByteEx)GetDelegate("ReadPciConfigByteEx", typeof(_ReadPciConfigByteEx)); ReadPciConfigWordEx = (_ReadPciConfigWordEx)GetDelegate("ReadPciConfigWordEx", typeof(_ReadPciConfigWordEx)); ReadPciConfigDwordEx = (_ReadPciConfigDwordEx)GetDelegate("ReadPciConfigDwordEx", typeof(_ReadPciConfigDwordEx)); WritePciConfigByte = (_WritePciConfigByte)GetDelegate("WritePciConfigByte", typeof(_WritePciConfigByte)); WritePciConfigWord = (_WritePciConfigWord)GetDelegate("WritePciConfigWord", typeof(_WritePciConfigWord)); WritePciConfigDword = (_WritePciConfigDword)GetDelegate("WritePciConfigDword", typeof(_WritePciConfigDword)); WritePciConfigByteEx = (_WritePciConfigByteEx)GetDelegate("WritePciConfigByteEx", typeof(_WritePciConfigByteEx)); WritePciConfigWordEx = (_WritePciConfigWordEx)GetDelegate("WritePciConfigWordEx", typeof(_WritePciConfigWordEx)); WritePciConfigDwordEx = (_WritePciConfigDwordEx)GetDelegate("WritePciConfigDwordEx", typeof(_WritePciConfigDwordEx)); FindPciDeviceById = (_FindPciDeviceById)GetDelegate("FindPciDeviceById", typeof(_FindPciDeviceById)); FindPciDeviceByClass = (_FindPciDeviceByClass)GetDelegate("FindPciDeviceByClass", typeof(_FindPciDeviceByClass)); #if _PHYSICAL_MEMORY_SUPPORT ReadDmiMemory = (_ReadDmiMemory)GetDelegate("ReadDmiMemory", typeof(_ReadDmiMemory)); ReadPhysicalMemory = (_ReadPhysicalMemory)GetDelegate("ReadPhysicalMemory", typeof(_ReadPhysicalMemory)); WritePhysicalMemory = (_WritePhysicalMemory)GetDelegate("WritePhysicalMemory", typeof(_WritePhysicalMemory)); #endif if (! ( GetDllStatus != null && GetDllVersion != null && GetDriverVersion != null && GetDriverType != null && InitializeOls != null && DeinitializeOls != null && IsCpuid != null && IsMsr != null && IsTsc != null && Hlt != null && HltTx != null && HltPx != null && Rdmsr != null && RdmsrTx != null && RdmsrPx != null && Wrmsr != null && WrmsrTx != null && WrmsrPx != null && Rdpmc != null && RdpmcTx != null && RdpmcPx != null && Cpuid != null && CpuidTx != null && CpuidPx != null && Rdtsc != null && RdtscTx != null && RdtscPx != null && ReadIoPortByte != null && ReadIoPortWord != null && ReadIoPortDword != null && ReadIoPortByteEx != null && ReadIoPortWordEx != null && ReadIoPortDwordEx != null && WriteIoPortByte != null && WriteIoPortWord != null && WriteIoPortDword != null && WriteIoPortByteEx != null && WriteIoPortWordEx != null && WriteIoPortDwordEx != null && SetPciMaxBusIndex != null && ReadPciConfigByte != null && ReadPciConfigWord != null && ReadPciConfigDword != null && ReadPciConfigByteEx != null && ReadPciConfigWordEx != null && ReadPciConfigDwordEx != null && WritePciConfigByte != null && WritePciConfigWord != null && WritePciConfigDword != null && WritePciConfigByteEx != null && WritePciConfigWordEx != null && WritePciConfigDwordEx != null && FindPciDeviceById != null && FindPciDeviceByClass != null #if _PHYSICAL_MEMORY_SUPPORT && ReadDmiMemory != null && ReadPhysicalMemory != null && WritePhysicalMemory != null #endif )) { status = (uint)Status.DLL_INCORRECT_VERSION; } if (InitializeOls() == 0) { status = (uint)Status.DLL_INITIALIZE_ERROR; } } } public uint GetStatus() { return status; } public void Dispose() { if (module != IntPtr.Zero) { DeinitializeOls(); Ols.FreeLibrary(module); module = IntPtr.Zero; } } public Delegate GetDelegate(string procName, Type delegateType) { IntPtr ptr = GetProcAddress(module, procName); if (ptr != IntPtr.Zero) { Delegate d = Marshal.GetDelegateForFunctionPointer(ptr, delegateType); return d; } int result = Marshal.GetHRForLastWin32Error(); throw Marshal.GetExceptionForHR(result); } //----------------------------------------------------------------------------- // DLL Information //----------------------------------------------------------------------------- public delegate uint _GetDllStatus(); public delegate uint _GetDllVersion(ref byte major, ref byte minor, ref byte revision, ref byte release); public delegate uint _GetDriverVersion(ref byte major, ref byte minor, ref byte revision, ref byte release); public delegate uint _GetDriverType(); public delegate int _InitializeOls(); public delegate void _DeinitializeOls(); public _GetDllStatus GetDllStatus = null; public _GetDriverType GetDriverType = null; public _GetDllVersion GetDllVersion = null; public _GetDriverVersion GetDriverVersion = null; public _InitializeOls InitializeOls = null; public _DeinitializeOls DeinitializeOls = null; //----------------------------------------------------------------------------- // CPU //----------------------------------------------------------------------------- public delegate int _IsCpuid(); public delegate int _IsMsr(); public delegate int _IsTsc(); public delegate int _Hlt(); public delegate int _HltTx(UIntPtr threadAffinityMask); public delegate int _HltPx(UIntPtr processAffinityMask); public delegate int _Rdmsr(uint index, ref uint eax, ref uint edx); public delegate int _RdmsrTx(uint index, ref uint eax, ref uint edx, UIntPtr threadAffinityMask); public delegate int _RdmsrPx(uint index, ref uint eax, ref uint edx, UIntPtr processAffinityMask); public delegate int _Wrmsr(uint index, uint eax, uint edx); public delegate int _WrmsrTx(uint index, uint eax, uint edx, UIntPtr threadAffinityMask); public delegate int _WrmsrPx(uint index, uint eax, uint edx, UIntPtr processAffinityMask); public delegate int _Rdpmc(uint index, ref uint eax, ref uint edx); public delegate int _RdpmcTx(uint index, ref uint eax, ref uint edx, UIntPtr threadAffinityMask); public delegate int _RdpmcPx(uint index, ref uint eax, ref uint edx, UIntPtr processAffinityMask); public delegate int _Cpuid(uint index, ref uint eax, ref uint ebx, ref uint ecx, ref uint edx); public delegate int _CpuidTx(uint index, ref uint eax, ref uint ebx, ref uint ecx, ref uint edx, UIntPtr threadAffinityMask); public delegate int _CpuidPx(uint index, ref uint eax, ref uint ebx, ref uint ecx, ref uint edx, UIntPtr processAffinityMask); public delegate int _Rdtsc(ref uint eax, ref uint edx); public delegate int _RdtscTx(ref uint eax, ref uint edx, UIntPtr threadAffinityMask); public delegate int _RdtscPx(ref uint eax, ref uint edx, UIntPtr processAffinityMask); public _IsCpuid IsCpuid = null; public _IsMsr IsMsr = null; public _IsTsc IsTsc = null; public _Hlt Hlt = null; public _HltTx HltTx = null; public _HltPx HltPx = null; public _Rdmsr Rdmsr = null; public _RdmsrTx RdmsrTx = null; public _RdmsrPx RdmsrPx = null; public _Wrmsr Wrmsr = null; public _WrmsrTx WrmsrTx = null; public _WrmsrPx WrmsrPx = null; public _Rdpmc Rdpmc = null; public _RdpmcTx RdpmcTx = null; public _RdpmcPx RdpmcPx = null; public _Cpuid Cpuid = null; public _CpuidTx CpuidTx = null; public _CpuidPx CpuidPx = null; public _Rdtsc Rdtsc = null; public _RdtscTx RdtscTx = null; public _RdtscPx RdtscPx = null; //----------------------------------------------------------------------------- // I/O //----------------------------------------------------------------------------- public delegate byte _ReadIoPortByte(ushort port); public delegate ushort _ReadIoPortWord(ushort port); public delegate uint _ReadIoPortDword(ushort port); public _ReadIoPortByte ReadIoPortByte; public _ReadIoPortWord ReadIoPortWord; public _ReadIoPortDword ReadIoPortDword; public delegate int _ReadIoPortByteEx(ushort port, ref byte value); public delegate int _ReadIoPortWordEx(ushort port, ref ushort value); public delegate int _ReadIoPortDwordEx(ushort port, ref uint value); public _ReadIoPortByteEx ReadIoPortByteEx; public _ReadIoPortWordEx ReadIoPortWordEx; public _ReadIoPortDwordEx ReadIoPortDwordEx; public delegate void _WriteIoPortByte(ushort port, byte value); public delegate void _WriteIoPortWord(ushort port, ushort value); public delegate void _WriteIoPortDword(ushort port, uint value); public _WriteIoPortByte WriteIoPortByte; public _WriteIoPortWord WriteIoPortWord; public _WriteIoPortDword WriteIoPortDword; public delegate int _WriteIoPortByteEx(ushort port, byte value); public delegate int _WriteIoPortWordEx(ushort port, ushort value); public delegate int _WriteIoPortDwordEx(ushort port, uint value); public _WriteIoPortByteEx WriteIoPortByteEx; public _WriteIoPortWordEx WriteIoPortWordEx; public _WriteIoPortDwordEx WriteIoPortDwordEx; //----------------------------------------------------------------------------- // PCI //----------------------------------------------------------------------------- public delegate void _SetPciMaxBusIndex(byte max); public _SetPciMaxBusIndex SetPciMaxBusIndex; public delegate byte _ReadPciConfigByte(uint pciAddress, byte regAddress); public delegate ushort _ReadPciConfigWord(uint pciAddress, byte regAddress); public delegate uint _ReadPciConfigDword(uint pciAddress, byte regAddress); public _ReadPciConfigByte ReadPciConfigByte; public _ReadPciConfigWord ReadPciConfigWord; public _ReadPciConfigDword ReadPciConfigDword; public delegate int _ReadPciConfigByteEx(uint pciAddress, uint regAddress, ref byte value); public delegate int _ReadPciConfigWordEx(uint pciAddress, uint regAddress, ref ushort value); public delegate int _ReadPciConfigDwordEx(uint pciAddress, uint regAddress, ref uint value); public _ReadPciConfigByteEx ReadPciConfigByteEx; public _ReadPciConfigWordEx ReadPciConfigWordEx; public _ReadPciConfigDwordEx ReadPciConfigDwordEx; public delegate void _WritePciConfigByte(uint pciAddress, byte regAddress, byte value); public delegate void _WritePciConfigWord(uint pciAddress, byte regAddress, ushort value); public delegate void _WritePciConfigDword(uint pciAddress, byte regAddress, uint value); public _WritePciConfigByte WritePciConfigByte; public _WritePciConfigWord WritePciConfigWord; public _WritePciConfigDword WritePciConfigDword; public delegate int _WritePciConfigByteEx(uint pciAddress, uint regAddress, byte value); public delegate int _WritePciConfigWordEx(uint pciAddress, uint regAddress, ushort value); public delegate int _WritePciConfigDwordEx(uint pciAddress, uint regAddress, uint value); public _WritePciConfigByteEx WritePciConfigByteEx; public _WritePciConfigWordEx WritePciConfigWordEx; public _WritePciConfigDwordEx WritePciConfigDwordEx; public delegate uint _FindPciDeviceById(ushort vendorId, ushort deviceId, byte index); public delegate uint _FindPciDeviceByClass(byte baseClass, byte subClass, byte programIf, byte index); public _FindPciDeviceById FindPciDeviceById; public _FindPciDeviceByClass FindPciDeviceByClass; //----------------------------------------------------------------------------- // Physical Memory (unsafe) //----------------------------------------------------------------------------- #if _PHYSICAL_MEMORY_SUPPORT public unsafe delegate uint _ReadDmiMemory(byte* buffer, uint count, uint unitSize); public _ReadDmiMemory ReadDmiMemory; public unsafe delegate uint _ReadPhysicalMemory(UIntPtr address, byte* buffer, uint count, uint unitSize); public unsafe delegate uint _WritePhysicalMemory(UIntPtr address, byte* buffer, uint count, uint unitSize); public _ReadPhysicalMemory ReadPhysicalMemory; public _WritePhysicalMemory WritePhysicalMemory; #endif } }
using System; using System.Linq; using System.Text; using System.Collections.Generic; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using HETSAPI.Models; namespace HETSAPI.ViewModels { /// <summary> /// Rental Request Database Model /// </summary> [MetaData (Description = "A request from a Project for one or more of a type of equipment from a specific Local Area.")] public sealed class RentalRequestViewModel : IEquatable<RentalRequestViewModel> { /// <summary> /// Rental Request Database Model Constructor (required by entity framework) /// </summary> public RentalRequestViewModel() { Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="RentalRequestViewModel" /> class. /// </summary> /// <param name="id">A system-generated unique identifier for a Request (required).</param> /// <param name="project">Project (required).</param> /// <param name="localArea">A foreign key reference to the system-generated unique identifier for a Local Area (required).</param> /// <param name="status">The status of the Rental Request - whether it in progress, completed or was cancelled. (required).</param> /// <param name="districtEquipmentType">A foreign key reference to the system-generated unique identifier for an Equipment Type (required).</param> /// <param name="equipmentCount">The number of pieces of the equipment type wanted for hire as part of this request. (required).</param> /// <param name="expectedHours">The expected number of rental hours for each piece equipment hired against this request, as provided by the Project Manager making the request..</param> /// <param name="expectedStartDate">The expected start date of each piece of equipment hired against this request, as provided by the Project Manager making the request..</param> /// <param name="expectedEndDate">The expected end date of each piece of equipment hired against this request, as provided by the Project Manager making the request..</param> /// <param name="firstOnRotationList">The first piece of equipment on the rotation list at the time of the creation of the request..</param> /// <param name="notes">Notes.</param> /// <param name="attachments">Attachments.</param> /// <param name="history">History.</param> /// <param name="rentalRequestAttachments">RentalRequestAttachments.</param> /// <param name="rentalRequestRotationList">RentalRequestRotationList.</param> public RentalRequestViewModel(int id, Project project, LocalArea localArea, string status, DistrictEquipmentType districtEquipmentType, int equipmentCount, int? expectedHours = null, DateTime? expectedStartDate = null, DateTime? expectedEndDate = null, Equipment firstOnRotationList = null, List<Note> notes = null, List<Attachment> attachments = null, List<History> history = null, List<RentalRequestAttachment> rentalRequestAttachments = null, List<RentalRequestRotationList> rentalRequestRotationList = null) { Id = id; Project = project; LocalArea = localArea; Status = status; DistrictEquipmentType = districtEquipmentType; EquipmentCount = equipmentCount; ExpectedHours = expectedHours; ExpectedStartDate = expectedStartDate; ExpectedEndDate = expectedEndDate; FirstOnRotationList = firstOnRotationList; Notes = notes; Attachments = attachments; History = history; RentalRequestAttachments = rentalRequestAttachments; RentalRequestRotationList = rentalRequestRotationList; // calculate the Yes Count based on the RentalRequestList CalculateYesCount(); } /// <summary> /// The count of yes responses from Equipment Owners (calculated field) /// </summary> /// <value>A system-generated unique identifier for a Request</value> [MetaData(Description = "The count of yes responses from Equipment Owners")] [DataMember(Name = "yesCount")] public int YesCount { get; set; } /// <summary> /// Check how many Yes' we currently have from Owners /// </summary> /// <returns></returns> public int CalculateYesCount() { int temp = 0; if (RentalRequestRotationList != null) { foreach (RentalRequestRotationList equipment in RentalRequestRotationList) { if (equipment.OfferResponse != null && equipment.OfferResponse.Equals("Yes", StringComparison.InvariantCultureIgnoreCase)) { temp++; } if (equipment.IsForceHire != null && equipment.IsForceHire == true) { temp++; } } } // set the current Yes / Forced Hire Count YesCount = temp; return temp; } /// <summary> /// Returns the Number of Blocks for this Rotation List /// </summary> [DataMember(Name = "numberOfBlocks")] public int NumberOfBlocks { get; set; } #region Standard Rental Request Model Properties /// <summary> /// A system-generated unique identifier for a Request /// </summary> /// <value>A system-generated unique identifier for a Request</value> [MetaData (Description = "A system-generated unique identifier for a Request")] public int Id { get; set; } /// <summary> /// Gets or Sets Project /// </summary> public Project Project { get; set; } /// <summary> /// Foreign key for Project /// </summary> [ForeignKey("Project")] [JsonIgnore] public int? ProjectId { get; set; } /// <summary> /// A foreign key reference to the system-generated unique identifier for a Local Area /// </summary> /// <value>A foreign key reference to the system-generated unique identifier for a Local Area</value> [MetaData (Description = "A foreign key reference to the system-generated unique identifier for a Local Area")] public LocalArea LocalArea { get; set; } /// <summary> /// Foreign key for LocalArea /// </summary> [ForeignKey("LocalArea")] [JsonIgnore] [MetaData (Description = "A foreign key reference to the system-generated unique identifier for a Local Area")] public int? LocalAreaId { get; set; } /// <summary> /// The status of the Rental Request - whether it in progress, completed or was cancelled. /// </summary> /// <value>The status of the Rental Request - whether it in progress, completed or was cancelled.</value> [MetaData (Description = "The status of the Rental Request - whether it in progress, completed or was cancelled.")] [MaxLength(50)] public string Status { get; set; } /// <summary> /// A foreign key reference to the system-generated unique identifier for an Equipment Type /// </summary> /// <value>A foreign key reference to the system-generated unique identifier for an Equipment Type</value> [MetaData (Description = "A foreign key reference to the system-generated unique identifier for an Equipment Type")] public DistrictEquipmentType DistrictEquipmentType { get; set; } /// <summary> /// Foreign key for DistrictEquipmentType /// </summary> [ForeignKey("DistrictEquipmentType")] [JsonIgnore] [MetaData (Description = "A foreign key reference to the system-generated unique identifier for an Equipment Type")] public int? DistrictEquipmentTypeId { get; set; } /// <summary> /// The number of pieces of the equipment type wanted for hire as part of this request. /// </summary> /// <value>The number of pieces of the equipment type wanted for hire as part of this request.</value> [MetaData (Description = "The number of pieces of the equipment type wanted for hire as part of this request.")] public int EquipmentCount { get; set; } /// <summary> /// The expected number of rental hours for each piece equipment hired against this request, as provided by the Project Manager making the request. /// </summary> /// <value>The expected number of rental hours for each piece equipment hired against this request, as provided by the Project Manager making the request.</value> [MetaData (Description = "The expected number of rental hours for each piece equipment hired against this request, as provided by the Project Manager making the request.")] public int? ExpectedHours { get; set; } /// <summary> /// The expected start date of each piece of equipment hired against this request, as provided by the Project Manager making the request. /// </summary> /// <value>The expected start date of each piece of equipment hired against this request, as provided by the Project Manager making the request.</value> [MetaData (Description = "The expected start date of each piece of equipment hired against this request, as provided by the Project Manager making the request.")] public DateTime? ExpectedStartDate { get; set; } /// <summary> /// The expected end date of each piece of equipment hired against this request, as provided by the Project Manager making the request. /// </summary> /// <value>The expected end date of each piece of equipment hired against this request, as provided by the Project Manager making the request.</value> [MetaData (Description = "The expected end date of each piece of equipment hired against this request, as provided by the Project Manager making the request.")] public DateTime? ExpectedEndDate { get; set; } /// <summary> /// The first piece of equipment on the rotation list at the time of the creation of the request. /// </summary> /// <value>The first piece of equipment on the rotation list at the time of the creation of the request.</value> [MetaData (Description = "The first piece of equipment on the rotation list at the time of the creation of the request.")] public Equipment FirstOnRotationList { get; set; } /// <summary> /// Foreign key for FirstOnRotationList /// </summary> [ForeignKey("FirstOnRotationList")] [JsonIgnore] [MetaData (Description = "The first piece of equipment on the rotation list at the time of the creation of the request.")] public int? FirstOnRotationListId { get; set; } /// <summary> /// Gets or Sets Notes /// </summary> public List<Note> Notes { get; set; } /// <summary> /// Gets or Sets Attachments /// </summary> public List<Attachment> Attachments { get; set; } /// <summary> /// Gets or Sets History /// </summary> public List<History> History { get; set; } /// <summary> /// Gets or Sets RentalRequestAttachments /// </summary> public List<RentalRequestAttachment> RentalRequestAttachments { get; set; } /// <summary> /// Gets or Sets RentalRequestRotationList /// </summary> public List<RentalRequestRotationList> RentalRequestRotationList { get; set; } #endregion /// <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 RentalRequestViewModel {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Project: ").Append(Project).Append("\n"); sb.Append(" LocalArea: ").Append(LocalArea).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" DistrictEquipmentType: ").Append(DistrictEquipmentType).Append("\n"); sb.Append(" EquipmentCount: ").Append(EquipmentCount).Append("\n"); sb.Append(" ExpectedHours: ").Append(ExpectedHours).Append("\n"); sb.Append(" ExpectedStartDate: ").Append(ExpectedStartDate).Append("\n"); sb.Append(" ExpectedEndDate: ").Append(ExpectedEndDate).Append("\n"); sb.Append(" FirstOnRotationList: ").Append(FirstOnRotationList).Append("\n"); sb.Append(" Notes: ").Append(Notes).Append("\n"); sb.Append(" Attachments: ").Append(Attachments).Append("\n"); sb.Append(" History: ").Append(History).Append("\n"); sb.Append(" RentalRequestAttachments: ").Append(RentalRequestAttachments).Append("\n"); sb.Append(" RentalRequestRotationList: ").Append(RentalRequestRotationList).Append("\n"); sb.Append(" YesCount: ").Append(YesCount).Append("\n"); sb.Append(" NumberOfBlocks: ").Append(NumberOfBlocks).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) { if (obj is null) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj.GetType() == GetType() && Equals((RentalRequestViewModel)obj); } /// <summary> /// Returns true if RentalRequest instances are equal /// </summary> /// <param name="other">Instance of RentalRequest to be compared</param> /// <returns>Boolean</returns> public bool Equals(RentalRequestViewModel other) { if (other is null) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( Id == other.Id || Id.Equals(other.Id) ) && ( Project == other.Project || Project != null && Project.Equals(other.Project) ) && ( LocalArea == other.LocalArea || LocalArea != null && LocalArea.Equals(other.LocalArea) ) && ( Status == other.Status || Status != null && Status.Equals(other.Status) ) && ( DistrictEquipmentType == other.DistrictEquipmentType || DistrictEquipmentType != null && DistrictEquipmentType.Equals(other.DistrictEquipmentType) ) && ( EquipmentCount == other.EquipmentCount || EquipmentCount.Equals(other.EquipmentCount) ) && ( ExpectedHours == other.ExpectedHours || ExpectedHours != null && ExpectedHours.Equals(other.ExpectedHours) ) && ( ExpectedStartDate == other.ExpectedStartDate || ExpectedStartDate != null && ExpectedStartDate.Equals(other.ExpectedStartDate) ) && ( ExpectedEndDate == other.ExpectedEndDate || ExpectedEndDate != null && ExpectedEndDate.Equals(other.ExpectedEndDate) ) && ( FirstOnRotationList == other.FirstOnRotationList || FirstOnRotationList != null && FirstOnRotationList.Equals(other.FirstOnRotationList) ) && ( Notes == other.Notes || Notes != null && Notes.SequenceEqual(other.Notes) ) && ( Attachments == other.Attachments || Attachments != null && Attachments.SequenceEqual(other.Attachments) ) && ( History == other.History || History != null && History.SequenceEqual(other.History) ) && ( RentalRequestAttachments == other.RentalRequestAttachments || RentalRequestAttachments != null && RentalRequestAttachments.SequenceEqual(other.RentalRequestAttachments) ) && ( RentalRequestRotationList == other.RentalRequestRotationList || RentalRequestRotationList != null && RentalRequestRotationList.SequenceEqual(other.RentalRequestRotationList) ); } /// <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 hash = hash * 59 + Id.GetHashCode(); if (Project != null) { hash = hash * 59 + Project.GetHashCode(); } if (LocalArea != null) { hash = hash * 59 + LocalArea.GetHashCode(); } if (Status != null) { hash = hash * 59 + Status.GetHashCode(); } if (DistrictEquipmentType != null) { hash = hash * 59 + DistrictEquipmentType.GetHashCode(); } hash = hash * 59 + EquipmentCount.GetHashCode(); if (ExpectedHours != null) { hash = hash * 59 + ExpectedHours.GetHashCode(); } if (ExpectedStartDate != null) { hash = hash * 59 + ExpectedStartDate.GetHashCode(); } if (ExpectedEndDate != null) { hash = hash * 59 + ExpectedEndDate.GetHashCode(); } if (FirstOnRotationList != null) { hash = hash * 59 + FirstOnRotationList.GetHashCode(); } if (Notes != null) { hash = hash * 59 + Notes.GetHashCode(); } if (Attachments != null) { hash = hash * 59 + Attachments.GetHashCode(); } if (History != null) { hash = hash * 59 + History.GetHashCode(); } if (RentalRequestAttachments != null) { hash = hash * 59 + RentalRequestAttachments.GetHashCode(); } if (RentalRequestRotationList != null) { hash = hash * 59 + RentalRequestRotationList.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(RentalRequestViewModel left, RentalRequestViewModel right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(RentalRequestViewModel left, RentalRequestViewModel right) { return !Equals(left, right); } #endregion Operators } }
using System; using System.Linq; using System.Xml.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using PcapDotNet.Packets.IpV6; namespace PcapDotNet.Core.Test { internal class WiresharkDatagramComparerIpV6MobilityHeader : WiresharkDatagramComparerSimple { public WiresharkDatagramComparerIpV6MobilityHeader() { } protected override string PropertyName { get { return ""; } } protected override bool CompareField(XElement field, Datagram datagram) { IpV6Datagram ipV6Datagram = datagram as IpV6Datagram; if (ipV6Datagram == null) return true; if (ipV6Datagram.NextHeader == IpV4Protocol.Cftp || ipV6Datagram.ExtensionHeaders.Any(extensionHeader => extensionHeader.NextHeader == IpV4Protocol.Cftp)) return false; // TODO: Remove after https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=9996 is fixed. if (ipV6Datagram.ExtensionHeaders.Select(extensionHeader => extensionHeader.NextHeader).Concat(ipV6Datagram.NextHeader).Any( protocol => protocol == IpV4Protocol.WidebandMonitoring || protocol == IpV4Protocol.SunNetworkDisk || protocol == IpV4Protocol.Swipe || protocol == IpV4Protocol.AnyHostInternal || protocol == IpV4Protocol.SourceDemandRoutingProtocol || protocol == IpV4Protocol.MobileInternetworkingControlProtocol || protocol == IpV4Protocol.IsoIp || protocol == IpV4Protocol.Kryptolan || protocol == IpV4Protocol.LArp || protocol == IpV4Protocol.SecureVersatileMessageTransactionProtocol || protocol == IpV4Protocol.WangSpanNetwork || protocol == IpV4Protocol.Cbt || protocol == IpV4Protocol.Visa || protocol == IpV4Protocol.SimpleMessageProtocol || protocol == IpV4Protocol.InternetPacketCoreUtility || protocol == IpV4Protocol.BbnRccMonitoring || protocol == IpV4Protocol.IpIp || protocol == IpV4Protocol.FibreChannel || protocol == IpV4Protocol.ServiceSpecificConnectionOrientedProtocolInAMultilinkAndConnectionlessEnvironment || protocol == IpV4Protocol.SitaraNetworksProtocol || protocol == IpV4Protocol.Fire || protocol == IpV4Protocol.Leaf1 || protocol == IpV4Protocol.IpsilonFlowManagementProtocol || protocol == IpV4Protocol.CompaqPeer || protocol == IpV4Protocol.InterDomainPolicyRoutingProtocolControlMessageTransportProtocol || protocol == IpV4Protocol.BulkDataTransferProtocol || protocol == IpV4Protocol.SemaphoreCommunicationsSecondProtocol || protocol == IpV4Protocol.Mobile || protocol == IpV4Protocol.HostMonitoringProtocol || protocol == IpV4Protocol.Chaos || protocol == IpV4Protocol.DiiDataExchange || protocol == IpV4Protocol.Emcon || protocol == IpV4Protocol.ThirdPartyConnect || protocol == IpV4Protocol.Aris || protocol == IpV4Protocol.NetworkVoice || protocol == IpV4Protocol.AnyPrivateEncryptionScheme || protocol == IpV4Protocol.PacketVideoProtocol || protocol == IpV4Protocol.PacketRadioMeasurement || protocol == IpV4Protocol.AnyLocalNetwork || protocol == IpV4Protocol.Qnx || protocol == IpV4Protocol.Tcf || protocol == IpV4Protocol.Ttp || protocol == IpV4Protocol.ScheduleTransferProtocol || protocol == IpV4Protocol.TransportLayerSecurityProtocol || protocol == IpV4Protocol.Ax25 || protocol == IpV4Protocol.CombatRadioTransportProtocol || protocol == IpV4Protocol.PerformanceTransparencyProtocol || protocol == IpV4Protocol.IntegratedNetLayerSecurityProtocol || protocol == IpV4Protocol.DatagramDeliveryProtocol || protocol == IpV4Protocol.PrivateNetworkToNetworkInterface || protocol == IpV4Protocol.Pipe || protocol == IpV4Protocol.BackroomSatMon || protocol == IpV4Protocol.Iplt || protocol == IpV4Protocol.Any0HopProtocol || protocol == IpV4Protocol.Leaf2 || protocol == IpV4Protocol.InterDomainPolicyRoutingProtocol || protocol == IpV4Protocol.NationalScienceFoundationNetworkInteriorGatewayProtocol || protocol == IpV4Protocol.WidebandExpak || protocol == IpV4Protocol.Uti || protocol == IpV4Protocol.Multiplexing || protocol == IpV4Protocol.Il || protocol == IpV4Protocol.MulticastTransportProtocol || protocol == IpV4Protocol.AnyDistributedFileSystem || protocol == IpV4Protocol.InteractiveAgentTransferProtocol || protocol == IpV4Protocol.InternetPluribusPacketCore || protocol == IpV4Protocol.InternetworkPacketExchangeInIp || protocol == IpV4Protocol.IntermediateSystemToIntermediateSystemOverIpV4 || protocol == IpV4Protocol.ComputerProtocolNetworkExecutive || protocol == IpV4Protocol.EncapsulationHeader || protocol == IpV4Protocol.GatewayToGateway || protocol == IpV4Protocol.SatMon || protocol == IpV4Protocol.VersatileMessageTransactionProtocol || protocol == IpV4Protocol.ReliableDatagramProtocol || protocol == IpV4Protocol.InternetReliableTransactionProtocol || protocol == IpV4Protocol.MeritInternodalProtocol || protocol == IpV4Protocol.Skip || protocol == IpV4Protocol.BurroughsNetworkArchitecture || protocol == IpV4Protocol.InterDomainRoutingProtocol || protocol == IpV4Protocol.ActiveNetworks || protocol == IpV4Protocol.SpectraLinkRadioProtocol || protocol == IpV4Protocol.MobileAdHocNetwork || protocol == IpV4Protocol.DissimilarGatewayProtocol || protocol == IpV4Protocol.SpriteRpc || protocol == IpV4Protocol.CombatRadioUserDatagram || protocol == IpV4Protocol.Gmtp || protocol == IpV4Protocol.MobileHostRoutingProtocol || protocol == IpV4Protocol.Shim6 || // TODO: Implement Shim6. protocol == IpV4Protocol.RemoteVirtualDiskProtocol)) return false; int currentExtensionHeaderIndex = ipV6Datagram.ExtensionHeaders.TakeWhile(extensionHeader => extensionHeader.Protocol != IpV4Protocol.MobilityHeader).Count(); if (currentExtensionHeaderIndex >= ipV6Datagram.ExtensionHeaders.Headers.Count && !ipV6Datagram.IsValid) return false; IpV6ExtensionHeaderMobility mobilityHeader = (IpV6ExtensionHeaderMobility)ipV6Datagram.ExtensionHeaders[currentExtensionHeaderIndex]; switch (field.Name()) { case "mip6.proto": field.AssertShowDecimal((byte)mobilityHeader.NextHeader); field.AssertNoFields(); break; case "mip6.hlen": if (mobilityHeader.IsValid) field.AssertShowDecimal(mobilityHeader.Length / 8 - 1); field.AssertNoFields(); break; case "mip6.mhtype": field.AssertShowDecimal((byte)mobilityHeader.MobilityHeaderType); break; case "mip6.reserved": field.AssertShowDecimal(0); field.AssertNoFields(); break; case "mip6.csum": field.AssertShowDecimal(mobilityHeader.Checksum); break; case "mip6.em.data": IpV6ExtensionHeaderMobilityExperimental experimentalHeader = (IpV6ExtensionHeaderMobilityExperimental)mobilityHeader; field.AssertValue(experimentalHeader.MessageData); break; case "": switch (field.Show()) { case "Binding Refresh Request": Assert.AreEqual(IpV6MobilityHeaderType.BindingRefreshRequest, mobilityHeader.MobilityHeaderType); field.AssertNoFields(); break; case "Heartbeat": IpV6ExtensionHeaderMobilityHeartbeatMessage heartbeatMessage = (IpV6ExtensionHeaderMobilityHeartbeatMessage)mobilityHeader; foreach (XElement subfield in field.Fields()) { subfield.AssertNoFields(); switch (subfield.Name()) { case "mip6.hb.u_flag": subfield.AssertShowDecimal(heartbeatMessage.IsUnsolicitedHeartbeatResponse); break; case "mip6.hb.r_flag": subfield.AssertShowDecimal(heartbeatMessage.IsResponse); break; case "mip6.hb.seqnr": subfield.AssertShowDecimal(heartbeatMessage.SequenceNumber); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Heartbeat mobility header field {0}", subfield.Name())); } } break; case "Binding Revocation Indication": IpV6ExtensionHeaderMobilityBindingRevocationIndicationMessage bindingRevocationIndicationMessage = (IpV6ExtensionHeaderMobilityBindingRevocationIndicationMessage)mobilityHeader; foreach (XElement subfield in field.Fields()) { subfield.AssertNoFields(); switch (subfield.Name()) { case "mip6.bri_br.type": subfield.AssertShowDecimal((byte)bindingRevocationIndicationMessage.BindingRevocationType); break; case "mip6.bri_r.trigger": subfield.AssertShowDecimal((byte)bindingRevocationIndicationMessage.RevocationTrigger); break; case "mip6.bri_seqnr": subfield.AssertShowDecimal(bindingRevocationIndicationMessage.SequenceNumber); break; case "mip6.bri_ip": subfield.AssertShowDecimal(bindingRevocationIndicationMessage.ProxyBinding); break; case "mip6.bri_iv": subfield.AssertShowDecimal(bindingRevocationIndicationMessage.IpV4HomeAddressBindingOnly); break; case "mip6.bri_ig": subfield.AssertShowDecimal(bindingRevocationIndicationMessage.Global); break; case "mip6.bri_res": break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Binding Revocation Acknowledgement Message mobility header field {0}", subfield.Name())); } } break; case "Binding Revocation Acknowledge": IpV6ExtensionHeaderMobilityBindingRevocationAcknowledgementMessage bindingRevocationAcknowledgementMessage = (IpV6ExtensionHeaderMobilityBindingRevocationAcknowledgementMessage)mobilityHeader; foreach (XElement subfield in field.Fields()) { subfield.AssertNoFields(); switch (subfield.Name()) { case "mip6.bri_br.type": subfield.AssertShowDecimal((byte)bindingRevocationAcknowledgementMessage.BindingRevocationType); break; case "mip6.bri_status": subfield.AssertShowDecimal((byte)bindingRevocationAcknowledgementMessage.Status); break; case "mip6.bri_seqnr": subfield.AssertShowDecimal(bindingRevocationAcknowledgementMessage.SequenceNumber); break; case "mip6.bri_ap": subfield.AssertShowDecimal(bindingRevocationAcknowledgementMessage.ProxyBinding); break; case "mip6.bri_av": subfield.AssertShowDecimal(bindingRevocationAcknowledgementMessage.IpV4HomeAddressBindingOnly); break; case "mip6.bri_ag": subfield.AssertShowDecimal(bindingRevocationAcknowledgementMessage.Global); break; case "mip6.bri_res": break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Binding Revocation Acknowledgement Message mobility header field {0}", subfield.Name())); } } break; case "Care-of Test Init": IpV6ExtensionHeaderMobilityCareOfTestInit careOfTestInit = (IpV6ExtensionHeaderMobilityCareOfTestInit)mobilityHeader; foreach (XElement subfield in field.Fields()) { subfield.AssertNoFields(); switch (subfield.Name()) { case "mip6.coti.cookie": subfield.AssertShowDecimal(careOfTestInit.CareOfInitCookie); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Care Of Test Init mobility header field {0}", subfield.Name())); } } break; case "Care-of Test": IpV6ExtensionHeaderMobilityCareOfTest careOfTest = (IpV6ExtensionHeaderMobilityCareOfTest)mobilityHeader; foreach (XElement subfield in field.Fields()) { subfield.AssertNoFields(); switch (subfield.Name()) { case "mip6.cot.nindex": subfield.AssertShowDecimal(careOfTest.CareOfNonceIndex); break; case "mip6.cot.cookie": subfield.AssertShowDecimal(careOfTest.CareOfInitCookie); break; case "mip6.hot.token": subfield.AssertShowDecimal(careOfTest.CareOfKeygenToken); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Care Of Test mobility header field {0}", subfield.Name())); } } break; case "Fast Binding Acknowledgement": IpV6ExtensionHeaderMobilityFastBindingAcknowledgement fastBindingAcknowledgement = (IpV6ExtensionHeaderMobilityFastBindingAcknowledgement)mobilityHeader; foreach (XElement subfield in field.Fields()) { subfield.AssertNoFields(); switch (subfield.Name()) { case "fmip6.fback.status": subfield.AssertShowDecimal((byte)fastBindingAcknowledgement.Status); break; case "fmip6.fback.k_flag": subfield.AssertShowDecimal(fastBindingAcknowledgement.KeyManagementMobilityCapability); break; case "fmip6.fback.seqnr": subfield.AssertShowDecimal(fastBindingAcknowledgement.SequenceNumber); break; case "fmip6.fback.lifetime": subfield.AssertShowDecimal(fastBindingAcknowledgement.Lifetime); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Fast Binding Acknowledgement mobility header field {0}", subfield.Name())); } } break; case "Binding Error": IpV6ExtensionHeaderMobilityBindingError bindingError = (IpV6ExtensionHeaderMobilityBindingError)mobilityHeader; foreach (XElement subfield in field.Fields()) { subfield.AssertNoFields(); switch (subfield.Name()) { case "mip6.be.status": subfield.AssertShowDecimal((byte)bindingError.Status); break; case "mip6.be.haddr": subfield.AssertShow(bindingError.HomeAddress.ToString("x")); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Binding Error mobility header field {0}", subfield.Name())); } } break; case "Fast Neighbor Advertisement": Assert.AreEqual(IpV6MobilityHeaderType.FastNeighborAdvertisement, mobilityHeader.MobilityHeaderType); field.AssertNoFields(); break; case "Home Test": IpV6ExtensionHeaderMobilityHomeTest homeTest = (IpV6ExtensionHeaderMobilityHomeTest)mobilityHeader; foreach (XElement subfield in field.Fields()) { subfield.AssertNoFields(); switch (subfield.Name()) { case "mip6.hot.nindex": subfield.AssertShowDecimal(homeTest.HomeNonceIndex); break; case "mip6.hot.cookie": subfield.AssertShowDecimal(homeTest.HomeInitCookie); break; case "mip6.hot.token": subfield.AssertShowDecimal(homeTest.HomeKeygenToken); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Home Test mobility header field {0}", subfield.Name())); } } break; case "Home Test Init": IpV6ExtensionHeaderMobilityHomeTestInit homeTestInit = (IpV6ExtensionHeaderMobilityHomeTestInit)mobilityHeader; foreach (XElement subfield in field.Fields()) { subfield.AssertNoFields(); switch (subfield.Name()) { case "mip6.hoti.cookie": subfield.AssertShowDecimal(homeTestInit.HomeInitCookie); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Home Test Init mobility header field {0}", subfield.Name())); } } break; case "Binding Update": IpV6ExtensionHeaderMobilityBindingUpdate bindingUpdate = (IpV6ExtensionHeaderMobilityBindingUpdate)mobilityHeader; foreach (XElement subfield in field.Fields()) { subfield.AssertNoFields(); switch (subfield.Name()) { case "mip6.bu.seqnr": subfield.AssertShowDecimal(bindingUpdate.SequenceNumber); break; case "mip6.bu.a_flag": subfield.AssertShowDecimal(bindingUpdate.Acknowledge); break; case "mip6.bu.h_flag": subfield.AssertShowDecimal(bindingUpdate.HomeRegistration); break; case "mip6.bu.l_flag": subfield.AssertShowDecimal(bindingUpdate.LinkLocalAddressCompatibility); break; case "mip6.bu.k_flag": subfield.AssertShowDecimal(bindingUpdate.KeyManagementMobilityCapability); break; case "mip6.bu.m_flag": subfield.AssertShowDecimal(bindingUpdate.MapRegistration); break; case "mip6.nemo.bu.r_flag": subfield.AssertShowDecimal(bindingUpdate.MobileRouter); break; case "mip6.bu.p_flag": subfield.AssertShowDecimal(bindingUpdate.ProxyRegistration); break; case "mip6.bu.f_flag": subfield.AssertShowDecimal(bindingUpdate.ForcingUdpEncapsulation); break; case "mip6.bu.t_flag": subfield.AssertShowDecimal(bindingUpdate.TypeLengthValueHeaderFormat); break; case "mip6.bu.b_flag": subfield.AssertShowDecimal(bindingUpdate.BulkBindingUpdate); break; case "mip6.bu.lifetime": subfield.AssertShowDecimal(bindingUpdate.Lifetime); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Binding Update mobility header field {0}", subfield.Name())); } } break; case "Binding Acknowledgement": IpV6ExtensionHeaderMobilityBindingAcknowledgement bindingAcknowledgement = (IpV6ExtensionHeaderMobilityBindingAcknowledgement)mobilityHeader; foreach (XElement subfield in field.Fields()) { subfield.AssertNoFields(); switch (subfield.Name()) { case "mip6.ba.status": subfield.AssertShowDecimal((byte)bindingAcknowledgement.Status); break; case "mip6.ba.k_flag": subfield.AssertShowDecimal(bindingAcknowledgement.KeyManagementMobilityCapability); break; case "mip6.nemo.ba.r_flag": subfield.AssertShowDecimal(bindingAcknowledgement.MobileRouter); break; case "mip6.ba.p_flag": subfield.AssertShowDecimal(bindingAcknowledgement.ProxyRegistration); break; case "mip6.ba.t_flag": subfield.AssertShowDecimal(bindingAcknowledgement.TypeLengthValueHeaderFormat); break; case "mip6.ba.b_flag": // TODO: Support Bulk Binding Update Support for Proxy Mobile IPv6 (RFC 6602). break; case "mip6.ba.seqnr": subfield.AssertShowDecimal(bindingAcknowledgement.SequenceNumber); break; case "mip6.ba.lifetime": subfield.AssertShowDecimal(bindingAcknowledgement.Lifetime); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Binding Acknowledgement mobility header field {0}", subfield.Name())); } } break; case "Fast Binding Update": IpV6ExtensionHeaderMobilityFastBindingUpdate fastBindingUpdate = (IpV6ExtensionHeaderMobilityFastBindingUpdate)mobilityHeader; foreach (XElement subfield in field.Fields()) { subfield.AssertNoFields(); switch (subfield.Name()) { case "fmip6.fbu.seqnr": subfield.AssertShowDecimal(fastBindingUpdate.SequenceNumber); break; case "fmip6.fbu.a_flag": subfield.AssertShowDecimal(fastBindingUpdate.Acknowledge); break; case "fmip6.fbu.h_flag": subfield.AssertShowDecimal(fastBindingUpdate.HomeRegistration); break; case "fmip6.fbu.l_flag": subfield.AssertShowDecimal(fastBindingUpdate.LinkLocalAddressCompatibility); break; case "fmip6.fbu.k_flag": subfield.AssertShowDecimal(fastBindingUpdate.KeyManagementMobilityCapability); break; case "fmip6.fbu.lifetime": subfield.AssertShowDecimal(fastBindingUpdate.Lifetime); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Fast Binding Update mobility header field {0}", subfield.Name())); } } break; case "Handover Acknowledge ": var handoverAcknowledgeMessage = (IpV6ExtensionHeaderMobilityHandoverAcknowledgeMessage)mobilityHeader; foreach (XElement subfield in field.Fields()) { subfield.AssertNoFields(); switch (subfield.Name()) { case "mip6.hack.seqnr": subfield.AssertShowDecimal(handoverAcknowledgeMessage.SequenceNumber); break; case "mip6.hack.code": subfield.AssertShowDecimal((byte)handoverAcknowledgeMessage.Code); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Handover Acknowledge mobility header field {0}", subfield.Name())); } } break; case "Handover Initiate": var handoverInitiateMessage = (IpV6ExtensionHeaderMobilityHandoverInitiateMessage)mobilityHeader; foreach (XElement subfield in field.Fields()) { subfield.AssertNoFields(); switch (subfield.Name()) { case "mip6.hi.seqnr": subfield.AssertShowDecimal(handoverInitiateMessage.SequenceNumber); break; case "mip6.hi.s_flag": subfield.AssertShowDecimal(handoverInitiateMessage.AssignedAddressConfiguration); break; case "mip6.hi.u_flag": subfield.AssertShowDecimal(handoverInitiateMessage.Buffer); break; case "mip6.hi.code": subfield.AssertShowDecimal((byte)handoverInitiateMessage.Code); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 mobility header field {0}", subfield.Name())); } } break; case "Mobility Options": int optionIndex = 0; foreach (XElement optionField in field.Fields()) { IpV6MobilityOption option = mobilityHeader.MobilityOptions[optionIndex]; switch (optionField.Name()) { case "": switch (option.OptionType) { case IpV6MobilityOptionType.LinkLayerAddress: optionField.AssertShow("Mobility Header Link-Layer Address"); IpV6MobilityOptionLinkLayerAddress linkLayerAddress = (IpV6MobilityOptionLinkLayerAddress)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "": optionSubfield.AssertShow("Mobility Header Link-Layer Address option"); foreach (XElement optionSubsubfield in optionSubfield.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubsubfield, option)) continue; switch (optionSubsubfield.Name()) { case "mip6.lla.optcode": optionSubsubfield.AssertShowDecimal((byte)linkLayerAddress.Code); break; case "": // TODO: Uncomment when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10627 is fixed. // optionSubsubfield.AssertValue(linkLayerAddress.LinkLayerAddress); break; default: throw new InvalidOperationException(string.Format( "Invalid IPv6 Link Layer Address option subfield {0}", optionSubsubfield.Name())); } } break; default: throw new InvalidOperationException(string.Format( "Invalid IPv6 Link Layer Address option field {0}", optionSubfield.Name())); } } // TODO: Change to break when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10043 or https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10627 is fixed. return false; case IpV6MobilityOptionType.IpV4DefaultRouterAddress: var ipV4DefaultRouterAddress = (IpV6MobilityOptionIpV4DefaultRouterAddress)option; optionField.AssertShow("IPv4 Default-Router Address: " + ipV4DefaultRouterAddress.DefaultRouterAddress); foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.ipv4dra.reserved": optionSubfield.AssertShowDecimal(0); break; case "mip6.ipv4dra.dra": optionSubfield.AssertShow(ipV4DefaultRouterAddress.DefaultRouterAddress.ToString()); break; default: throw new InvalidOperationException( string.Format("Invalid IPv6 IPv4 Default Router Address option field {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.Pad1: optionField.AssertShow("Pad1"); optionField.AssertNoFields(); break; case IpV6MobilityOptionType.PadN: if (optionField.Show() != "PadN" && optionIndex == mobilityHeader.MobilityOptions.Count - 1) { Assert.IsFalse(mobilityHeader.IsValid); return true; } optionField.AssertShow("PadN"); IpV6MobilityOptionPadN padN = (IpV6MobilityOptionPadN)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "": optionSubfield.AssertShow(string.Format("PadN: {0} bytes", padN.PaddingDataLength)); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.IpV4HomeAddressReply: IpV6MobilityOptionIpV4HomeAddressReply ipV4HomeAddressReply = (IpV6MobilityOptionIpV4HomeAddressReply)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.ipv4aa.sts": optionSubfield.AssertShowDecimal((byte)ipV4HomeAddressReply.Status); break; default: ValidateIpV6MobilityOptionIpV4HomeAddressField(optionSubfield, ipV4HomeAddressReply); break; } } break; case IpV6MobilityOptionType.IpV4HomeAddressRequest: var ipV4HomeAddressRequest = (IpV6MobilityOptionIpV4HomeAddressRequest)option; optionField.AssertShow("IPv4 Home Address Request: " + ipV4HomeAddressRequest.HomeAddress); foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); ValidateIpV6MobilityOptionIpV4HomeAddressField(optionSubfield, ipV4HomeAddressRequest); } break; case IpV6MobilityOptionType.IpV4AddressAcknowledgement: optionField.AssertShow("IPv4 Address Acknowledgement"); var ipV4AddressAcknowledgement = (IpV6MobilityOptionIpV4AddressAcknowledgement)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "": optionSubfield.AssertShow("IPv4 Address Acknowledgement"); foreach (XElement optionSubsubfield in optionSubfield.Fields()) { optionSubsubfield.AssertNoFields(); switch (optionSubsubfield.Name()) { case "mip6.ipv4aa.sts": optionSubsubfield.AssertShowDecimal((byte)ipV4AddressAcknowledgement.Status); break; default: ValidateIpV6MobilityOptionIpV4HomeAddressField(optionSubsubfield, ipV4AddressAcknowledgement); break; } } break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.MobileNetworkPrefix: optionField.AssertShow("Mobile Network Prefix"); var mobileNetworkPrefix = (IpV6MobilityOptionMobileNetworkPrefix)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "": optionSubfield.AssertShow("Mobile Network Prefix"); foreach (XElement optionSubsubfield in optionSubfield.Fields()) { optionSubsubfield.AssertNoFields(); switch (optionSubsubfield.Name()) { case "mip6.nemo.mnp.mnp": optionSubsubfield.AssertShow(mobileNetworkPrefix.NetworkPrefix.ToString("x")); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subsubfield {0}", optionSubsubfield.Name())); } } break; case "mip6.nemo.mnp.pfl": optionSubfield.AssertNoFields(); optionSubfield.AssertShowDecimal(mobileNetworkPrefix.PrefixLength); break; default: optionSubfield.AssertNoFields(); throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.HomeNetworkPrefix: optionField.AssertShow("Home Network Prefix"); var homeNetworkPrefix = (IpV6MobilityOptionHomeNetworkPrefix)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "": optionSubfield.AssertShow("Home Network Prefix"); foreach (XElement optionSubsubfield in optionSubfield.Fields()) { switch (optionSubsubfield.Name()) { case "mip6.nemo.mnp.mnp": optionSubsubfield.AssertShow(homeNetworkPrefix.NetworkPrefix.ToString("x")); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Network Prefix option subfield {0}", optionSubsubfield.Name())); } } break; case "mip6.nemo.mnp.pfl": optionSubfield.AssertShowDecimal(homeNetworkPrefix.PrefixLength); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Network Prefix option field {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.VendorSpecific: Assert.IsTrue(optionField.Show().StartsWith("Vendor Specific: ")); IpV6MobilityOptionVendorSpecific vendorSpecific = (IpV6MobilityOptionVendorSpecific)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.vsm.vendorId": optionSubfield.AssertShowDecimal(vendorSpecific.VendorId); break; case "mip6.vsm.subtype": optionSubfield.AssertShowDecimal(vendorSpecific.Subtype); break; case "": optionSubfield.AssertValue(vendorSpecific.Data); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Vendor Specific option field {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.NonceIndexes: optionField.AssertShow("Nonce Indices"); IpV6MobilityOptionNonceIndexes nonceIndexes = (IpV6MobilityOptionNonceIndexes)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "": optionSubfield.AssertShow("Nonce Indices"); foreach (XElement optionSubsubfield in optionSubfield.Fields()) { optionSubsubfield.AssertNoFields(); switch (optionSubsubfield.Name()) { case "mip6.ni.hni": optionSubsubfield.AssertShowDecimal(nonceIndexes.HomeNonceIndex); break; case "mip6.ni.cni": optionSubsubfield.AssertShowDecimal(nonceIndexes.CareOfNonceIndex); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Nonce Indices option subfield {0}", optionSubsubfield.Name())); } } break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Nonce Indices option field {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.LinkLocalAddress: optionField.AssertShow("Link-local Address"); IpV6MobilityOptionLinkLocalAddress linkLocalAddress = (IpV6MobilityOptionLinkLocalAddress)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "": optionSubfield.AssertShow("Link-local Address"); foreach (XElement optionSubsubfield in optionSubfield.Fields()) { optionSubsubfield.AssertNoFields(); switch (optionSubsubfield.Name()) { case "mip6.lila_lla": optionSubsubfield.AssertShow(linkLocalAddress.LinkLocalAddress.ToString("x")); break; default: throw new InvalidOperationException(string.Format( "Invalid IPv6 Link-local Address option field {0}", optionSubsubfield.Name())); } } break; default: throw new InvalidOperationException(string.Format( "Invalid IPv6 Link-local Address option field {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.MobileNodeIdentifier: Assert.IsTrue(optionField.Show().StartsWith("Mobile Node Identifier")); IpV6MobilityOptionMobileNodeIdentifier mobileNodeIdentifier = (IpV6MobilityOptionMobileNodeIdentifier)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.mnid.subtype": optionSubfield.AssertShowDecimal((byte)mobileNodeIdentifier.Subtype); break; case "": optionSubfield.AssertValue(mobileNodeIdentifier.Identifier); break; default: throw new InvalidOperationException( string.Format("Invalid IPv6 Mobile Node Identifier option field {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.BindingAuthorizationData: optionField.AssertShow("Authorization Data"); IpV6MobilityOptionBindingAuthorizationData authorizationData = (IpV6MobilityOptionBindingAuthorizationData)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "": foreach (XElement authSubfield in optionSubfield.Fields()) { switch (authSubfield.Name()) { case "mip6.bad.auth": authSubfield.AssertValue(authorizationData.Authenticator); break; default: throw new InvalidOperationException( string.Format("Invalid IPv6 Authorization Data option subfield {0}", authSubfield.Name())); } } break; default: throw new InvalidOperationException(string.Format( "Invalid IPv6 Authorization Data option field {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.IpV4HomeAddress: optionField.AssertShow("IPv4 Home Address"); IpV6MobilityOptionIpV4HomeAddress ipV4HomeAddress = (IpV6MobilityOptionIpV4HomeAddress)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "": foreach (XElement optionSubsubfield in optionSubfield.Fields()) { optionSubsubfield.AssertNoFields(); switch (optionSubsubfield.Name()) { case "mip6.ipv4ha.p_flag": optionSubsubfield.AssertShowDecimal(ipV4HomeAddress.RequestPrefix); break; default: ValidateIpV6MobilityOptionIpV4HomeAddressField(optionSubsubfield, ipV4HomeAddress); break; } } break; default: throw new InvalidOperationException(string.Format( "Invalid IPv6 Authorization Data option field {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.ServiceSelection: IpV6MobilityOptionServiceSelection serviceSelection = (IpV6MobilityOptionServiceSelection)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.ss.identifier": optionSubfield.AssertValue(serviceSelection.Identifier); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.RedirectCapability: IpV6MobilityOptionRedirectCapability redirectCapability = (IpV6MobilityOptionRedirectCapability)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.recap.reserved": optionSubfield.AssertShowDecimal(0); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.BindingIdentifier: IpV6MobilityOptionBindingIdentifier bindingIdentifier = (IpV6MobilityOptionBindingIdentifier)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.bi.bid": optionSubfield.AssertShowDecimal(bindingIdentifier.BindingId); break; case "mip6.bi.status": optionSubfield.AssertShowDecimal((byte)bindingIdentifier.Status); break; case "mip6.bi.h_flag": optionSubfield.AssertShowDecimal(bindingIdentifier.SimultaneousHomeAndForeignBinding); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.LoadInformation: IpV6MobilityOptionLoadInformation loadInformation = (IpV6MobilityOptionLoadInformation)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.load_inf.priority": optionSubfield.AssertShowDecimal(loadInformation.Priority); break; case "mip6.load_inf.sessions_in_use": optionSubfield.AssertShowDecimal(loadInformation.SessionsInUse); break; case "mip6.load_inf.maximum_sessions": optionSubfield.AssertShowDecimal(loadInformation.MaximumSessions); break; case "mip6.load_inf.used_capacity": optionSubfield.AssertShowDecimal(loadInformation.UsedCapacity); break; case "mip6.load_inf.maximum_capacity": optionSubfield.AssertShowDecimal(loadInformation.MaximumCapacity); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.IpV4CareOfAddress: IpV6MobilityOptionIpV4CareOfAddress ipV4CareOfAddress = (IpV6MobilityOptionIpV4CareOfAddress)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.ipv4coa.reserved": optionSubfield.AssertShowDecimal(0); break; case "mip6.ipv4coa.addr": optionSubfield.AssertShow(ipV4CareOfAddress.CareOfAddress.ToString()); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.CryptographicallyGeneratedAddressParametersRequest: foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.IpV6AddressPrefix: var ipV6AddressPrefix = (IpV6MobilityOptionIpV6AddressPrefix)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.mhipv6ap.opt_code": optionSubfield.AssertShowDecimal((byte)ipV6AddressPrefix.Code); break; case "mip6.mhipv6ap.len": optionSubfield.AssertShowDecimal(ipV6AddressPrefix.PrefixLength); break; case "mip6.mhipv6ap.ipv6_address": optionSubfield.AssertValue(ipV6AddressPrefix.AddressOrPrefix.ToValue()); break; case "mip6.mhipv6ap.ipv6_address_prefix": Assert.IsTrue(optionSubfield.Value().EndsWith(ipV6AddressPrefix.AddressOrPrefix.ToValue().ToString("x32"))); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.MobileNodeGroupIdentifier: var mobileNodeGroupIdentifier = (IpV6MobilityOptionMobileNodeGroupIdentifier)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.mng.sub_type": optionSubfield.AssertShowDecimal((byte)mobileNodeGroupIdentifier.Subtype); break; case "mip6.mng.reserved": optionSubfield.AssertShowDecimal(0); break; case "mip6.mng._mng_id": optionSubfield.AssertShowDecimal(mobileNodeGroupIdentifier.MobileNodeGroupIdentifier); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.BindingAuthorizationDataForFmIpV6: var bindingAuthorizationDataForFmIpV6 = (IpV6MobilityOptionBindingAuthorizationDataForFmIpV6)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.badff.spi": optionSubfield.AssertShowDecimal(bindingAuthorizationDataForFmIpV6.SecurityParameterIndex); break; case "mip6.badff.auth": optionSubfield.AssertValue(bindingAuthorizationDataForFmIpV6.Authenticator); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.MobileNodeLinkLayerIdentifier: var mobileNodeLinkLayerIdentifier = (IpV6MobilityOptionMobileNodeLinkLayerIdentifier)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.mnlli.reserved": optionSubfield.AssertShowDecimal(0); break; case "mip6.mnlli.lli": optionSubfield.AssertValue(mobileNodeLinkLayerIdentifier.LinkLayerIdentifier); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.AccessTechnologyType: var accessTechnologyType = (IpV6MobilityOptionAccessTechnologyType)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.att.reserved": optionSubfield.AssertShowDecimal(0); break; case "mip6.att": optionSubfield.AssertShowDecimal((byte)accessTechnologyType.AccessTechnologyType); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.AccessNetworkIdentifier: foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "_ws.expert": break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.BindingRefreshAdvice: var bindingRefreshAdvice = (IpV6MobilityOptionBindingRefreshAdvice)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.bra.interval": optionSubfield.AssertShowDecimal(bindingRefreshAdvice.RefreshInterval); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.PermanentHomeKeygenToken: var permanentHomeKeygenToken = (IpV6MobilityOptionPermanentHomeKeygenToken)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.phkt.phkt": optionSubfield.AssertValue(permanentHomeKeygenToken.PermanentHomeKeygenToken); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.Redirect: var redirect = (IpV6MobilityOptionRedirect)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.redir.k": optionSubfield.AssertShowDecimal(redirect.LocalMobilityAddressIpV6 != null); break; case "mip6.redir.n": optionSubfield.AssertShowDecimal(redirect.LocalMobilityAddressIpV4 != null); break; case "mip6.redir.reserved": optionSubfield.AssertShowDecimal(0); break; case "mip6.redir.addr_r2lma_ipv4": optionSubfield.AssertShow(redirect.LocalMobilityAddressIpV4.ToString()); break; case "mip6.redir.addr_r2lma_ipv6": optionSubfield.AssertValue(redirect.LocalMobilityAddressIpV6.Value.ToValue()); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.CareOfTest: var careOfTestOption = (IpV6MobilityOptionCareOfTest)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.mocot.co_keygen_tok": optionSubfield.AssertValue(careOfTestOption.CareOfKeygenToken); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.ReplayProtection: var replayProtection = (IpV6MobilityOptionReplayProtection)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "mip6.mseg_id.timestamp": optionSubfield.AssertValue(replayProtection.Timestamp); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.Authentication: var authentication = (IpV6MobilityOptionAuthentication)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.auth.subtype": optionSubfield.AssertShowDecimal((byte)authentication.Subtype); break; case "mip6.auth.mobility_spi": optionSubfield.AssertShowDecimal(authentication.MobilitySecurityParameterIndex); break; case "mip6.auth.auth_data": // TODO: Uncomment when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10626 is fixed. // optionSubfield.AssertValue(authentication.AuthenticationData); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.HandoffIndicator: var handoffIndicator = (IpV6MobilityOptionHandoffIndicator)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.hi.reserved": optionSubfield.AssertShowDecimal(0); break; case "mip6.hi": optionSubfield.AssertShowDecimal((byte)handoffIndicator.HandoffIndicator); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.IpV4DhcpSupportMode: var ipV4DhcpSupportMode = (IpV6MobilityOptionIpV4DhcpSupportMode)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.ipv4dsm.reserved": optionSubfield.AssertShowDecimal(0); break; case "mip6.ipv4dsm.s_flag": optionSubfield.AssertShowDecimal(ipV4DhcpSupportMode.IsServer); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.DnsUpdate: var dnsUpdate = (IpV6MobilityOptionDnsUpdate)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.dnsu.status": optionSubfield.AssertShowDecimal((byte)dnsUpdate.Status); break; case "mip6.dnsu.flag.r": optionSubfield.AssertShowDecimal(dnsUpdate.Remove); break; case "mip6.dnsu.mn_id": optionSubfield.AssertValue(dnsUpdate.MobileNodeIdentity); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.LocalMobilityAnchorAddress: var localMobilityAnchorAddress = (IpV6MobilityOptionLocalMobilityAnchorAddress)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mmip6.lmaa.opt_code": optionSubfield.AssertShowDecimal((byte)localMobilityAnchorAddress.Code); break; case "mmip6.lmaa.reserved": optionSubfield.AssertShowDecimal(0); break; case "mip6.lmaa.ipv6": // TODO: Uncomment when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10961 is fixed. // optionSubfield.AssertValue(localMobilityAnchorAddress.LocalMobilityAnchorAddressIpV6.Value.ToValue()); break; case "mip6.lmaa.ipv4": // TODO: Uncomment when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10961 is fixed. // optionSubfield.AssertShow(localMobilityAnchorAddress.LocalMobilityAnchorAddressIpV4.Value.ToString()); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.ContextRequest: var contextRequest = (IpV6MobilityOptionContextRequest)option; optionField.AssertShow("Context Request" + (contextRequest.Requests.Any() ? "" : " (with option length = 2 bytes; should be >= 4)")); int requestIndex = 0; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.cr.reserved": optionSubfield.AssertShowDecimal(0); break; case "mmip6.cr.req_type": optionSubfield.AssertShowDecimal(contextRequest.Requests[requestIndex].RequestType); break; case "mmip6.cr.req_length": optionSubfield.AssertShowDecimal(contextRequest.Requests[requestIndex].OptionLength); if (contextRequest.Requests[requestIndex].OptionLength == 0) ++requestIndex; break; case "mip6.vsm.vendorId": optionSubfield.AssertValue(contextRequest.Requests[requestIndex].Option.Subsegment(0, 4)); break; case "mip6.vsm.subtype": optionSubfield.AssertValue(contextRequest.Requests[requestIndex].Option.Subsegment(4, 1)); ++requestIndex; break; case "": optionSubfield.AssertValue(contextRequest.Requests[requestIndex].Option); ++requestIndex; break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.AlternateIpV4CareOfAddress: var alternateIpV4CareOfAddress = (IpV6MobilityOptionAlternateIpV4CareOfAddress)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.alt_ip4": optionSubfield.AssertShow(alternateIpV4CareOfAddress.AlternateCareOfAddress.ToString()); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.Signature: var signature = (IpV6MobilityOptionSignature)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.sign.sign": optionSubfield.AssertValue(signature.Signature); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.TransientBinding: optionField.AssertShow("Transient Binding(2 bytes)"); foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "_ws.expert": break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.Timestamp: var timestamp = (IpV6MobilityOptionTimestamp)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.timestamp_tmp": optionSubfield.AssertValue(timestamp.Timestamp); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.RestartCounter: var restartCounter = (IpV6MobilityOptionRestartCounter)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.rc": optionSubfield.AssertShowDecimal(restartCounter.RestartCounter); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.CryptographicallyGeneratedAddressParameters: var cryptographicallyGeneratedAddressParameters = (IpV6MobilityOptionCryptographicallyGeneratedAddressParameters)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.cgar.cga_par": optionSubfield.AssertValue(cryptographicallyGeneratedAddressParameters.CryptographicallyGeneratedAddressParameters); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.FlowIdentification: optionField.AssertShow("Flow Identification(" + (option.Length - 2) + " bytes)"); foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "_ws.expert": break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.NatDetection: optionField.AssertShow("NAT Detection"); var natDetection = (IpV6MobilityOptionNatDetection)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.natd.f_flag": optionSubfield.AssertShowDecimal(natDetection.UdpEncapsulationRequired); break; case "mip6.natd.reserved": optionSubfield.AssertShowDecimal(0); break; case "mip6.natd.refresh_t": optionSubfield.AssertShowDecimal(natDetection.RefreshTime); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.FlowSummary: optionField.AssertShow("Flow Summary(" + (option.Length - 2) + " bytes)"); foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "_ws.expert": break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.Experimental: optionField.AssertShow("Experimental" + (option.Length == 2 ? " (with option length = 0 bytes; should be >= 1)" : "")); var experimental = (IpV6MobilityOptionExperimental)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.em.data": optionSubfield.AssertValue(experimental.Data); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.MobileAccessGatewayIpV6Address: optionField.AssertShow("MAG IPv6 Address(18 bytes)"); // TODO: Dedup this code. foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "_ws.expert": break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.CareOfTestInit: optionField.AssertShow("Care-of Test Init"); foreach (XElement optionSubfield in optionField.Fields()) { Assert.IsTrue(HandleCommonMobilityOptionSubfield(optionSubfield, option)); } break; case IpV6MobilityOptionType.MobileNodeLinkLocalAddressInterfaceIdentifier: optionField.AssertShow("Mobile Node Link-local Address Interface Identifier(10 bytes)"); foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; switch (optionSubfield.Name()) { case "_ws.expert": break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.AlternateCareOfAddress: optionField.AssertShow("Alternate Care-of Address"); var alternateCareOfAddress = (IpV6MobilityOptionAlternateCareOfAddress)option; foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.acoa.acoa": optionSubfield.AssertValue(alternateCareOfAddress.AlternateCareOfAddress.ToValue()); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; case IpV6MobilityOptionType.GreKey: var greKey = (IpV6MobilityOptionGreKey)option; optionField.AssertShow("GRE Key: " + greKey.GreKeyIdentifier); foreach (XElement optionSubfield in optionField.Fields()) { if (HandleCommonMobilityOptionSubfield(optionSubfield, option)) continue; optionSubfield.AssertNoFields(); switch (optionSubfield.Name()) { case "mip6.ipv4dra.reserved": optionSubfield.AssertShowDecimal(0); break; case "mip6.gre_key": optionSubfield.AssertShowDecimal(greKey.GreKeyIdentifier); break; default: throw new InvalidOperationException(string.Format("Invalid IPv6 Mobility option subfield {0}", optionSubfield.Name())); } } break; default: throw new InvalidOperationException(string.Format("Unsupported IPv6 mobility option type {0}", option.OptionType)); } ++optionIndex; break; default: throw new InvalidOperationException(string.Format("Invalid ipv6 mobility header option field {0}", optionField.Name())); } } break; default: field.AssertShow("Unknown MH Type"); Assert.IsTrue(mobilityHeader.MobilityHeaderType == IpV6MobilityHeaderType.Experimental || mobilityHeader.MobilityHeaderType == IpV6MobilityHeaderType.HomeAgentSwitchMessage || mobilityHeader.MobilityHeaderType == IpV6MobilityHeaderType.LocalizedRoutingInitiation || mobilityHeader.MobilityHeaderType == IpV6MobilityHeaderType.LocalizedRoutingAcknowledgement); field.AssertNoFields(); break; } break; default: throw new InvalidOperationException(string.Format("Invalid ipv6 mobility header field {0}", field.Name())); } return true; } private bool HandleCommonMobilityOptionSubfield(XElement optionSubfield, IpV6MobilityOption option) { switch (optionSubfield.Name()) { case "mip6.mobility_opt": optionSubfield.AssertNoFields(); optionSubfield.AssertShowDecimal((byte)option.OptionType); return true; case "mip6.mobility_opt.len": optionSubfield.AssertNoFields(); optionSubfield.AssertShowDecimal(option.Length - 2); return true; default: return false; } } private void ValidateIpV6MobilityOptionIpV4HomeAddressField(XElement field, IIpV6MobilityOptionIpV4HomeAddress ipV4HomeAddress) { switch (field.Name()) { case "mip6.ipv4ha.preflen": field.AssertShowDecimal(ipV4HomeAddress.PrefixLength); break; case "mip6.ipv4ha.ha": field.AssertShow(ipV4HomeAddress.HomeAddress.ToString()); break; default: throw new InvalidOperationException(string.Format("Invalid IpV6 IpV4 Home Address option field {0}", field.Name())); } } } }
#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; #if !(PORTABLE || PORTABLE40 || NET35 || NET20) using System.Numerics; #endif using System.Reflection; using System.Collections; using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Text; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Newtonsoft.Json.Serialization; namespace Newtonsoft.Json.Utilities { #if (NETFX_CORE || PORTABLE || PORTABLE40) internal enum MemberTypes { Property, Field, Event, Method, Other } #endif #if NETFX_CORE || PORTABLE [Flags] internal enum BindingFlags { Default = 0, IgnoreCase = 1, DeclaredOnly = 2, Instance = 4, Static = 8, Public = 16, NonPublic = 32, FlattenHierarchy = 64, InvokeMethod = 256, CreateInstance = 512, GetField = 1024, SetField = 2048, GetProperty = 4096, SetProperty = 8192, PutDispProperty = 16384, ExactBinding = 65536, PutRefDispProperty = 32768, SuppressChangeType = 131072, OptionalParamBinding = 262144, IgnoreReturn = 16777216 } #endif internal static class ReflectionUtils { public static readonly Type[] EmptyTypes; static ReflectionUtils() { #if !(NETFX_CORE || PORTABLE40 || PORTABLE) EmptyTypes = Type.EmptyTypes; #else EmptyTypes = new Type[0]; #endif } public static bool IsVirtual(this PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo"); MethodInfo m = propertyInfo.GetGetMethod(); if (m != null && m.IsVirtual) return true; m = propertyInfo.GetSetMethod(); if (m != null && m.IsVirtual) return true; return false; } public static MethodInfo GetBaseDefinition(this PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo"); MethodInfo m = propertyInfo.GetGetMethod(); if (m != null) return m.GetBaseDefinition(); m = propertyInfo.GetSetMethod(); if (m != null) return m.GetBaseDefinition(); return null; } public static bool IsPublic(PropertyInfo property) { if (property.GetGetMethod() != null && property.GetGetMethod().IsPublic) return true; if (property.GetSetMethod() != null && property.GetSetMethod().IsPublic) return true; return false; } public static Type GetObjectType(object v) { return (v != null) ? v.GetType() : null; } public static string GetTypeName(Type t, FormatterAssemblyStyle assemblyFormat, SerializationBinder binder) { string fullyQualifiedTypeName; #if !(NET20 || NET35) if (binder != null) { string assemblyName, typeName; binder.BindToName(t, out assemblyName, out typeName); fullyQualifiedTypeName = typeName + (assemblyName == null ? "" : ", " + assemblyName); } else { fullyQualifiedTypeName = t.AssemblyQualifiedName; } #else fullyQualifiedTypeName = t.AssemblyQualifiedName; #endif switch (assemblyFormat) { case FormatterAssemblyStyle.Simple: return RemoveAssemblyDetails(fullyQualifiedTypeName); case FormatterAssemblyStyle.Full: return fullyQualifiedTypeName; default: throw new ArgumentOutOfRangeException(); } } private static string RemoveAssemblyDetails(string fullyQualifiedTypeName) { StringBuilder builder = new StringBuilder(); // loop through the type name and filter out qualified assembly details from nested type names bool writingAssemblyName = false; bool skippingAssemblyDetails = false; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': writingAssemblyName = false; skippingAssemblyDetails = false; builder.Append(current); break; case ']': writingAssemblyName = false; skippingAssemblyDetails = false; builder.Append(current); break; case ',': if (!writingAssemblyName) { writingAssemblyName = true; builder.Append(current); } else { skippingAssemblyDetails = true; } break; default: if (!skippingAssemblyDetails) builder.Append(current); break; } } return builder.ToString(); } public static bool HasDefaultConstructor(Type t, bool nonPublic) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType()) return true; return (GetDefaultConstructor(t, nonPublic) != null); } public static ConstructorInfo GetDefaultConstructor(Type t) { return GetDefaultConstructor(t, false); } public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (nonPublic) bindingFlags = bindingFlags | BindingFlags.NonPublic; return t.GetConstructors(bindingFlags).SingleOrDefault(c => !c.GetParameters().Any()); } public static bool IsNullable(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType()) return IsNullableType(t); return true; } public static bool IsNullableType(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); return (t.IsGenericType() && t.GetGenericTypeDefinition() == typeof(Nullable<>)); } public static Type EnsureNotNullableType(Type t) { return (IsNullableType(t)) ? Nullable.GetUnderlyingType(t) : t; } public static bool IsGenericDefinition(Type type, Type genericInterfaceDefinition) { if (!type.IsGenericType()) return false; Type t = type.GetGenericTypeDefinition(); return (t == genericInterfaceDefinition); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition) { Type implementingType; return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, "genericInterfaceDefinition"); if (!genericInterfaceDefinition.IsInterface() || !genericInterfaceDefinition.IsGenericTypeDefinition()) throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition)); if (type.IsInterface()) { if (type.IsGenericType()) { Type interfaceDefinition = type.GetGenericTypeDefinition(); if (genericInterfaceDefinition == interfaceDefinition) { implementingType = type; return true; } } } foreach (Type i in type.GetInterfaces()) { if (i.IsGenericType()) { Type interfaceDefinition = i.GetGenericTypeDefinition(); if (genericInterfaceDefinition == interfaceDefinition) { implementingType = i; return true; } } } implementingType = null; return false; } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition) { Type implementingType; return InheritsGenericDefinition(type, genericClassDefinition, out implementingType); } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericClassDefinition, "genericClassDefinition"); if (!genericClassDefinition.IsClass() || !genericClassDefinition.IsGenericTypeDefinition()) throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition)); return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType); } private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType) { if (currentType.IsGenericType()) { Type currentGenericClassDefinition = currentType.GetGenericTypeDefinition(); if (genericClassDefinition == currentGenericClassDefinition) { implementingType = currentType; return true; } } if (currentType.BaseType() == null) { implementingType = null; return false; } return InheritsGenericDefinitionInternal(currentType.BaseType(), genericClassDefinition, out implementingType); } /// <summary> /// Gets the type of the typed collection's items. /// </summary> /// <param name="type">The type.</param> /// <returns>The type of the typed collection's items.</returns> public static Type GetCollectionItemType(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); Type genericListType; if (type.IsArray) { return type.GetElementType(); } else if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType)) { if (genericListType.IsGenericTypeDefinition()) throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); return genericListType.GetGenericArguments()[0]; } else if (typeof(IEnumerable).IsAssignableFrom(type)) { return null; } else { throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); } } public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType) { ValidationUtils.ArgumentNotNull(dictionaryType, "type"); Type genericDictionaryType; if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType)) { if (genericDictionaryType.IsGenericTypeDefinition()) throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments(); keyType = dictionaryGenericArguments[0]; valueType = dictionaryGenericArguments[1]; return; } else if (typeof(IDictionary).IsAssignableFrom(dictionaryType)) { keyType = null; valueType = null; return; } else { throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); } } /// <summary> /// Gets the member's underlying type. /// </summary> /// <param name="member">The member.</param> /// <returns>The underlying type of the member.</returns> public static Type GetMemberUnderlyingType(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, "member"); switch (member.MemberType()) { case MemberTypes.Field: return ((FieldInfo)member).FieldType; case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; case MemberTypes.Event: return ((EventInfo)member).EventHandlerType; default: throw new ArgumentException("MemberInfo must be of type FieldInfo, PropertyInfo or EventInfo", "member"); } } /// <summary> /// Determines whether the member is an indexed property. /// </summary> /// <param name="member">The member.</param> /// <returns> /// <c>true</c> if the member is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, "member"); PropertyInfo propertyInfo = member as PropertyInfo; if (propertyInfo != null) return IsIndexedProperty(propertyInfo); else return false; } /// <summary> /// Determines whether the property is an indexed property. /// </summary> /// <param name="property">The property.</param> /// <returns> /// <c>true</c> if the property is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(PropertyInfo property) { ValidationUtils.ArgumentNotNull(property, "property"); return (property.GetIndexParameters().Length > 0); } /// <summary> /// Gets the member's value on the object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target object.</param> /// <returns>The member's value on the object.</returns> public static object GetMemberValue(MemberInfo member, object target) { ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); switch (member.MemberType()) { case MemberTypes.Field: return ((FieldInfo)member).GetValue(target); case MemberTypes.Property: try { return ((PropertyInfo)member).GetValue(target, null); } catch (TargetParameterCountException e) { throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(CultureInfo.InvariantCulture, member.Name), e); } default: throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture, member.Name), "member"); } } /// <summary> /// Sets the member's value on the target object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target.</param> /// <param name="value">The value.</param> public static void SetMemberValue(MemberInfo member, object target, object value) { ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); switch (member.MemberType()) { case MemberTypes.Field: ((FieldInfo)member).SetValue(target, value); break; case MemberTypes.Property: ((PropertyInfo)member).SetValue(target, value, null); break; default: throw new ArgumentException("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, member.Name), "member"); } } /// <summary> /// Determines whether the specified MemberInfo can be read. /// </summary> /// <param name="member">The MemberInfo to determine whether can be read.</param> /// /// <param name="nonPublic">if set to <c>true</c> then allow the member to be gotten non-publicly.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>. /// </returns> public static bool CanReadMemberValue(MemberInfo member, bool nonPublic) { switch (member.MemberType()) { case MemberTypes.Field: FieldInfo fieldInfo = (FieldInfo)member; if (nonPublic) return true; else if (fieldInfo.IsPublic) return true; return false; case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo)member; if (!propertyInfo.CanRead) return false; if (nonPublic) return true; return (propertyInfo.GetGetMethod(nonPublic) != null); default: return false; } } /// <summary> /// Determines whether the specified MemberInfo can be set. /// </summary> /// <param name="member">The MemberInfo to determine whether can be set.</param> /// <param name="nonPublic">if set to <c>true</c> then allow the member to be set non-publicly.</param> /// <param name="canSetReadOnly">if set to <c>true</c> then allow the member to be set if read-only.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>. /// </returns> public static bool CanSetMemberValue(MemberInfo member, bool nonPublic, bool canSetReadOnly) { switch (member.MemberType()) { case MemberTypes.Field: FieldInfo fieldInfo = (FieldInfo)member; if (fieldInfo.IsInitOnly && !canSetReadOnly) return false; if (nonPublic) return true; else if (fieldInfo.IsPublic) return true; return false; case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo)member; if (!propertyInfo.CanWrite) return false; if (nonPublic) return true; return (propertyInfo.GetSetMethod(nonPublic) != null); default: return false; } } public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr) { List<MemberInfo> targetMembers = new List<MemberInfo>(); targetMembers.AddRange(GetFields(type, bindingAttr)); targetMembers.AddRange(GetProperties(type, bindingAttr)); // for some reason .NET returns multiple members when overriding a generic member on a base class // http://social.msdn.microsoft.com/Forums/en-US/b5abbfee-e292-4a64-8907-4e3f0fb90cd9/reflection-overriden-abstract-generic-properties?forum=netfxbcl // filter members to only return the override on the topmost class // update: I think this is fixed in .NET 3.5 SP1 - leave this in for now... List<MemberInfo> distinctMembers = new List<MemberInfo>(targetMembers.Count); foreach (var groupedMember in targetMembers.GroupBy(m => m.Name)) { int count = groupedMember.Count(); IList<MemberInfo> members = groupedMember.ToList(); if (count == 1) { distinctMembers.Add(members.First()); } else { IList<MemberInfo> resolvedMembers = new List<MemberInfo>(); foreach (MemberInfo memberInfo in members) { // this is a bit hacky // if the hiding property is hiding a base property and it is virtual // then this ensures the derived property gets used if (resolvedMembers.Count == 0) resolvedMembers.Add(memberInfo); else if (!IsOverridenGenericMember(memberInfo, bindingAttr) || memberInfo.Name == "Item") resolvedMembers.Add(memberInfo); } distinctMembers.AddRange(resolvedMembers); } } return distinctMembers; } private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr) { if (memberInfo.MemberType() != MemberTypes.Property) return false; PropertyInfo propertyInfo = (PropertyInfo)memberInfo; if (!IsVirtual(propertyInfo)) return false; Type declaringType = propertyInfo.DeclaringType; if (!declaringType.IsGenericType()) return false; Type genericTypeDefinition = declaringType.GetGenericTypeDefinition(); if (genericTypeDefinition == null) return false; MemberInfo[] members = genericTypeDefinition.GetMember(propertyInfo.Name, bindingAttr); if (members.Length == 0) return false; Type memberUnderlyingType = GetMemberUnderlyingType(members[0]); if (!memberUnderlyingType.IsGenericParameter) return false; return true; } public static T GetAttribute<T>(object attributeProvider) where T : Attribute { return GetAttribute<T>(attributeProvider, true); } public static T GetAttribute<T>(object attributeProvider, bool inherit) where T : Attribute { T[] attributes = GetAttributes<T>(attributeProvider, inherit); return (attributes != null) ? attributes.SingleOrDefault() : null; } #if !(NETFX_CORE || PORTABLE) public static T[] GetAttributes<T>(object attributeProvider, bool inherit) where T : Attribute { ValidationUtils.ArgumentNotNull(attributeProvider, "attributeProvider"); object provider = attributeProvider; // http://hyperthink.net/blog/getcustomattributes-gotcha/ // ICustomAttributeProvider doesn't do inheritance if (provider is Type) return (T[])((Type)provider).GetCustomAttributes(typeof(T), inherit); if (provider is Assembly) return (T[])Attribute.GetCustomAttributes((Assembly)provider, typeof(T)); if (provider is MemberInfo) return (T[])Attribute.GetCustomAttributes((MemberInfo)provider, typeof(T), inherit); #if !PORTABLE40 if (provider is Module) return (T[])Attribute.GetCustomAttributes((Module)provider, typeof(T), inherit); #endif if (provider is ParameterInfo) return (T[])Attribute.GetCustomAttributes((ParameterInfo)provider, typeof(T), inherit); #if !PORTABLE40 return (T[])((ICustomAttributeProvider)attributeProvider).GetCustomAttributes(typeof(T), inherit); #endif throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider)); } #else public static T[] GetAttributes<T>(object provider, bool inherit) where T : Attribute { if (provider is Type) return ((Type) provider).GetTypeInfo().GetCustomAttributes<T>(inherit).ToArray(); if (provider is Assembly) return ((Assembly) provider).GetCustomAttributes<T>().ToArray(); if (provider is MemberInfo) return ((MemberInfo) provider).GetCustomAttributes<T>(inherit).ToArray(); if (provider is Module) return ((Module) provider).GetCustomAttributes<T>().ToArray(); if (provider is ParameterInfo) return ((ParameterInfo) provider).GetCustomAttributes<T>(inherit).ToArray(); throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider)); } #endif public static void SplitFullyQualifiedTypeName(string fullyQualifiedTypeName, out string typeName, out string assemblyName) { int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName); if (assemblyDelimiterIndex != null) { typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.Value).Trim(); assemblyName = fullyQualifiedTypeName.Substring(assemblyDelimiterIndex.Value + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.Value - 1).Trim(); } else { typeName = fullyQualifiedTypeName; assemblyName = null; } } private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName) { // we need to get the first comma following all surrounded in brackets because of generic types // e.g. System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 int scope = 0; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': scope++; break; case ']': scope--; break; case ',': if (scope == 0) return i; break; } } return null; } public static MemberInfo GetMemberInfoFromType(Type targetType, MemberInfo memberInfo) { const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; switch (memberInfo.MemberType()) { case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo)memberInfo; Type[] types = propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray(); return targetType.GetProperty(propertyInfo.Name, bindingAttr, null, propertyInfo.PropertyType, types, null); default: return targetType.GetMember(memberInfo.Name, memberInfo.MemberType(), bindingAttr).SingleOrDefault(); } } public static IEnumerable<FieldInfo> GetFields(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, "targetType"); List<MemberInfo> fieldInfos = new List<MemberInfo>(targetType.GetFields(bindingAttr)); #if !(NETFX_CORE || PORTABLE) // Type.GetFields doesn't return inherited private fields // manually find private fields from base class GetChildPrivateFields(fieldInfos, targetType, bindingAttr); #endif return fieldInfos.Cast<FieldInfo>(); } private static void GetChildPrivateFields(IList<MemberInfo> initialFields, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private FieldInfos only being returned for the current Type // find base type fields and add them to result if ((bindingAttr & BindingFlags.NonPublic) != 0) { // modify flags to not search for public fields BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); while ((targetType = targetType.BaseType()) != null) { // filter out protected fields IEnumerable<MemberInfo> childPrivateFields = targetType.GetFields(nonPublicBindingAttr).Where(f => f.IsPrivate).Cast<MemberInfo>(); initialFields.AddRange(childPrivateFields); } } } public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, "targetType"); List<PropertyInfo> propertyInfos = new List<PropertyInfo>(targetType.GetProperties(bindingAttr)); GetChildPrivateProperties(propertyInfos, targetType, bindingAttr); // a base class private getter/setter will be inaccessable unless the property was gotten from the base class for (int i = 0; i < propertyInfos.Count; i++) { PropertyInfo member = propertyInfos[i]; if (member.DeclaringType != targetType) { PropertyInfo declaredMember = (PropertyInfo)GetMemberInfoFromType(member.DeclaringType, member); propertyInfos[i] = declaredMember; } } return propertyInfos; } public static BindingFlags RemoveFlag(this BindingFlags bindingAttr, BindingFlags flag) { return ((bindingAttr & flag) == flag) ? bindingAttr ^ flag : bindingAttr; } private static void GetChildPrivateProperties(IList<PropertyInfo> initialProperties, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private PropertyInfos only being returned for the current Type // find base type properties and add them to result // also find base properties that have been hidden by subtype properties with the same name while ((targetType = targetType.BaseType()) != null) { foreach (PropertyInfo propertyInfo in targetType.GetProperties(bindingAttr)) { PropertyInfo subTypeProperty = propertyInfo; if (!IsPublic(subTypeProperty)) { // have to test on name rather than reference because instances are different // depending on the type that GetProperties was called on int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name); if (index == -1) { initialProperties.Add(subTypeProperty); } else { PropertyInfo childProperty = initialProperties[index]; // don't replace public child with private base if (!IsPublic(childProperty)) { // replace nonpublic properties for a child, but gotten from // the parent with the one from the child // the property gotten from the child will have access to private getter/setter initialProperties[index] = subTypeProperty; } } } else { if (!subTypeProperty.IsVirtual()) { int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name && p.DeclaringType == subTypeProperty.DeclaringType); if (index == -1) initialProperties.Add(subTypeProperty); } else { int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name && p.IsVirtual() && p.GetBaseDefinition() != null && p.GetBaseDefinition().DeclaringType.IsAssignableFrom(subTypeProperty.DeclaringType)); if (index == -1) initialProperties.Add(subTypeProperty); } } } } } public static bool IsMethodOverridden(Type currentType, Type methodDeclaringType, string method) { bool isMethodOverriden = currentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Any(info => info.Name == method && // check that the method overrides the original on DynamicObjectProxy info.DeclaringType != methodDeclaringType && info.GetBaseDefinition().DeclaringType == methodDeclaringType ); return isMethodOverriden; } public static object GetDefaultValue(Type type) { if (!type.IsValueType()) return null; switch (ConvertUtils.GetTypeCode(type)) { case PrimitiveTypeCode.Boolean: return false; case PrimitiveTypeCode.Char: case PrimitiveTypeCode.SByte: case PrimitiveTypeCode.Byte: case PrimitiveTypeCode.Int16: case PrimitiveTypeCode.UInt16: case PrimitiveTypeCode.Int32: case PrimitiveTypeCode.UInt32: return 0; case PrimitiveTypeCode.Int64: case PrimitiveTypeCode.UInt64: return 0L; case PrimitiveTypeCode.Single: return 0f; case PrimitiveTypeCode.Double: return 0.0; case PrimitiveTypeCode.Decimal: return 0m; case PrimitiveTypeCode.DateTime: return new DateTime(); #if !(PORTABLE || PORTABLE40 || NET35 || NET20) case PrimitiveTypeCode.BigInteger: return new BigInteger(); #endif case PrimitiveTypeCode.Guid: return new Guid(); #if !NET20 case PrimitiveTypeCode.DateTimeOffset: return new DateTimeOffset(); #endif } if (IsNullable(type)) return null; // possibly use IL initobj for perf here? return Activator.CreateInstance(type); } } }
using System; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; using System.Xml.Linq; using Microsoft.Deployment.WindowsInstaller; using WixSharp.CommonTasks; using WixSharp.UI.Forms; using WixSharp.UI.ManagedUI; namespace WixSharp { /// <summary> /// Implements as standard dialog-based MSI embedded UI. /// <para> /// This class allows defining separate sequences of UI dialogs for 'install' /// and 'modify' MSI executions. The dialog sequence can contain any mixture /// of built-in standard dialogs and/or custom dialogs (Form inherited from <see cref="T:WixSharp.UI.Forms.ManagedForm"/>). /// </para> /// </summary> /// <example>The following is an example of installing <c>MyLibrary.dll</c> assembly and registering it in GAC. /// <code> /// ... /// project.ManagedUI = new ManagedUI(); /// project.ManagedUI.InstallDialogs.Add(Dialogs.Welcome) /// .Add(Dialogs.Licence) /// .Add(Dialogs.SetupType) /// .Add(Dialogs.Features) /// .Add(Dialogs.InstallDir) /// .Add(Dialogs.Progress) /// .Add(Dialogs.Exit); /// /// project.ManagedUI.ModifyDialogs.Add(Dialogs.MaintenanceType) /// .Add(Dialogs.Features) /// .Add(Dialogs.Progress) /// .Add(Dialogs.Exit); /// /// </code> /// </example> public class ManagedUI : IManagedUI, IEmbeddedUI { /// <summary> /// The default WPF implementation of ManagedUI. It implements all major dialogs of a typical MSI UI. /// </summary> static public IManagedUI DefaultWpf { get { var assembly = "WixSharp.UI.WPF"; var type = "ManagedWpfUI"; var ManagedWpfUI = System.Reflection.Assembly.Load(assembly)?.GetType($"{assembly}.{type}"); if (ManagedWpfUI == null) throw new Exception($"Cannot load {assembly}.{type}. Make sure you are referencing {assembly} package/assembly."); return ManagedWpfUI.GetProperty("Default") .GetValue(null) as IManagedUI; } } /// <summary> /// The default WinForm implementation of ManagedUI. It implements all major dialogs of a typical MSI UI. /// </summary> static public ManagedUI Default = new ManagedUI { InstallDialogs = new ManagedDialogs() .Add<WelcomeDialog>() .Add<LicenceDialog>() .Add<SetupTypeDialog>() .Add<FeaturesDialog>() .Add<InstallDirDialog>() .Add<ProgressDialog>() .Add<ExitDialog>(), ModifyDialogs = new ManagedDialogs() .Add<MaintenanceTypeDialog>() .Add<FeaturesDialog>() .Add<ProgressDialog>() .Add<ExitDialog>() }; /// <summary> /// The default implementation of ManagedUI with no UI dialogs. /// </summary> static public ManagedUI Empty = new ManagedUI(); /// <summary> /// Initializes a new instance of the <see cref="ManagedUI"/> class. /// </summary> public ManagedUI() { InstallDialogs = new ManagedDialogs(); ModifyDialogs = new ManagedDialogs(); } /// <summary> /// This method is called (indirectly) by Wix# compiler just before building the MSI. It allows embedding UI specific resources (e.g. license file, properties) /// into the MSI. /// </summary> /// <param name="project">The project.</param> public void BeforeBuild(ManagedProject project) { var file = LocalizationFileFor(project); ValidateUITextFile(file); project.AddBinary(new Binary(new Id("WixSharp_UIText"), file)); project.AddBinary(new Binary(new Id("WixSharp_LicenceFile"), LicenceFileFor(project))); project.AddBinary(new Binary(new Id("WixUI_Bmp_Dialog"), DialogBitmapFileFor(project))); project.AddBinary(new Binary(new Id("WixUI_Bmp_Banner"), DialogBannerFileFor(project))); } /// <summary> /// Validates the UI text file (localization file) for being compatible with ManagedUI. /// </summary> /// <param name="file">The file.</param> /// <param name="throwOnError">if set to <c>true</c> [throw on error].</param> /// <returns></returns> public static bool ValidateUITextFile(string file, bool throwOnError = true) { try { var data = new ResourcesData(); data.InitFromWxl(System.IO.File.ReadAllBytes(file)); } catch (Exception e) { //may need to do extra logging; not important for now if (throwOnError) throw new Exception("Localization file is incompatible with ManagedUI.", e); else return false; } return true; } /// <summary> /// Gets or sets the id of the 'installdir' (destination folder) directory. It is the directory, /// which is bound to the input UI elements of the Browse dialog (e.g. WiX BrowseDlg, Wix# InstallDirDialog). /// </summary> /// <value> /// The install dir identifier. /// </value> public string InstallDirId { get; set; } internal string LocalizationFileFor(Project project) { return UIExtensions.UserOrDefaultContentOf(project.LocalizationFile, project.SourceBaseDir, project.OutDir, project.Name + ".wxl", Resources.WixUI_en_us); } internal string LicenceFileFor(Project project) { return UIExtensions.UserOrDefaultContentOf(project.LicenceFile, project.SourceBaseDir, project.OutDir, project.Name + ".licence.rtf", Resources.WixSharp_LicenceFile); } internal string DialogBitmapFileFor(Project project) { return UIExtensions.UserOrDefaultContentOf(project.BackgroundImage, project.SourceBaseDir, project.OutDir, project.Name + ".dialog_bmp.png", Resources.WixUI_Bmp_Dialog); } internal string DialogBannerFileFor(Project project) { return UIExtensions.UserOrDefaultContentOf(project.BannerImage, project.SourceBaseDir, project.OutDir, project.Name + ".dialog_banner.png", Resources.WixUI_Bmp_Banner); } /// <summary> /// Sequence of the dialogs to be displayed during the installation of the product. /// </summary> public ManagedDialogs InstallDialogs { get; set; } /// <summary> /// Sequence of the dialogs to be displayed during the customization of the installed product. /// </summary> public ManagedDialogs ModifyDialogs { get; set; } /// <summary> /// A window icon that appears in the left top corner of the UI shell window. /// </summary> public string Icon { get; set; } ManualResetEvent uiExitEvent = new ManualResetEvent(false); IUIContainer shell; void ReadDialogs(Session session) { // System.Diagnostics.Debug.Assert(false); InstallDialogs.Clear() .AddRange(ManagedProject.ReadDialogs(session.Property("WixSharp_InstallDialogs"))); ModifyDialogs.Clear() .AddRange(ManagedProject.ReadDialogs(session.Property("WixSharp_ModifyDialogs"))); } Mutex cancelRequest = null; /// <summary> /// Initializes the specified session. /// </summary> /// <param name="session">The session.</param> /// <param name="resourcePath">The resource path.</param> /// <param name="uiLevel">The UI level.</param> /// <returns></returns> /// <exception cref="Microsoft.Deployment.WindowsInstaller.InstallCanceledException"></exception> public bool Initialize(Session session, string resourcePath, ref InstallUIOptions uiLevel) { if (session != null && (session.IsUninstalling() || uiLevel.IsBasic())) return false; //use built-in MSI basic UI string upgradeCode = session["UpgradeCode"]; using (cancelRequest) { try { ReadDialogs(session); var startEvent = new ManualResetEvent(false); var uiThread = new Thread(() => { session["WIXSHARP_MANAGED_UI"] = System.Reflection.Assembly.GetExecutingAssembly().ToString(); shell = new UIShell(); //important to create the instance in the same thread that call ShowModal shell.ShowModal( new MsiRuntime(session) { StartExecute = () => startEvent.Set(), CancelExecute = () => { // NOTE: IEmbeddedUI interface has no way to cancel the installation, which has been started // (e.g. ProgressDialog is displayed). What is even worse is that UI can pass back to here // a signal the user pressed 'Cancel' but nothing we can do with it. Install is already started // and session object is now invalid. // To solve this we use this work around - set a unique "cancel request mutex" form here // and ManagedProjectActions.CancelRequestHandler built-in CA will pick the request and yield // return code UserExit. cancelRequest = new Mutex(true, "WIXSHARP_UI_CANCEL_REQUEST." + upgradeCode); } }, this); uiExitEvent.Set(); }); uiThread.SetApartmentState(ApartmentState.STA); uiThread.Start(); int waitResult = WaitHandle.WaitAny(new[] { startEvent, uiExitEvent }); if (waitResult == 1) { //UI exited without starting the install. Cancel the installation. throw new InstallCanceledException(); } else { // Start the installation with a silenced internal UI. // This "embedded external UI" will handle message types except for source resolution. uiLevel = InstallUIOptions.NoChange | InstallUIOptions.SourceResolutionOnly; shell.OnExecuteStarted(); return true; } } catch (Exception e) { session.Log("Cannot attach ManagedUI: " + e); throw; } } } /// <summary> /// Processes information and progress messages sent to the user interface. /// </summary> /// <param name="messageType">Message type.</param> /// <param name="messageRecord">Record that contains message data.</param> /// <param name="buttons">Message buttons.</param> /// <param name="icon">Message box icon.</param> /// <param name="defaultButton">Message box default button.</param> /// <returns> /// Result of processing the message. /// </returns> /// <remarks> /// <p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/embeddeduihandler.asp">EmbeddedUIHandler</a></p> /// </remarks> public MessageResult ProcessMessage(InstallMessage messageType, Record messageRecord, MessageButtons buttons, MessageIcon icon, MessageDefaultButton defaultButton) { return shell.ProcessMessage(messageType, messageRecord, buttons, icon, defaultButton); } /// <summary> /// Shuts down the embedded UI at the end of the installation. /// </summary> /// <remarks> /// If the installation was canceled during initialization, this method will not be called. /// If the installation was canceled or failed at any later point, this method will be called at the end. /// <p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/shutdownembeddedui.asp">ShutdownEmbeddedUI</a></p> /// </remarks> public void Shutdown() { shell.OnExecuteComplete(); uiExitEvent.WaitOne(); } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class TitleGUI : MonoBehaviour { #region Variables / Properties public bool DebugMode = false; public bool DrawElements = true; public string NewGameScene; public Vector3 NewGameTransform; public MainForm MainForm; public SettingsForm SettingsForm; public CreditsForm CreditsForm; public InstructionsForm InstructionsForm; // Private elements private Maestro _maestro; private Ambassador _ambassador; private SaveFileAccess _saveFileAccess; private TransitionManager _transition; #endregion Variables / Properties #region Engine Hooks public void Start() { _maestro = Maestro.DetectLastInstance(); _ambassador = Ambassador.Instance; _transition = TransitionManager.Instance; _saveFileAccess = _ambassador.gameObject.GetComponent<SaveFileAccess>(); MainForm.Initialize(_maestro); SettingsForm.Initialize(_maestro); CreditsForm.Initialize(_maestro); InstructionsForm.Initialize(_maestro); MainForm.SetVisibility(true); SettingsForm.SetVisibility(false); CreditsForm.SetVisibility(false); InstructionsForm.SetVisibility(false); } public void OnGUI() { if(! DrawElements) return; MainForm.DrawMe(); switch(MainForm.FormResult) { case MainForm.Feedback.Settings: MainForm.SetVisibility(false); SettingsForm.SetVisibility(true); break; case MainForm.Feedback.Instructions: MainForm.SetVisibility(false); InstructionsForm.SetVisibility(true); break; case MainForm.Feedback.Credits: MainForm.SetVisibility(false); CreditsForm.SetVisibility(true); break; case MainForm.Feedback.Support: Application.ExternalEval("window.open('http://www.patreon.com/Asvarduil');"); break; case MainForm.Feedback.NewGame: MainForm.SetVisibility(false); NewGame(); break; case MainForm.Feedback.LoadGame: MainForm.SetVisibility(false); if(_saveFileAccess.LoadGameState()) { if(DebugMode) Debug.Log("Game state loaded. Transitioning to scene..."); _transition.ChangeScenes(); } else { if(DebugMode) Debug.LogWarning("Unable to load game state! Starting a new game."); NewGame(); } break; default: break; } SettingsForm.DrawMe(); switch(SettingsForm.FormResult) { case SettingsForm.Feedback.Back: SettingsForm.SetVisibility(false); MainForm.SetVisibility(true); break; default: break; } CreditsForm.DrawMe(); switch(CreditsForm.FormResult) { case CreditsForm.Feedback.Back: CreditsForm.SetVisibility(false); MainForm.SetVisibility(true); break; default: break; } InstructionsForm.DrawMe(); switch(InstructionsForm.FormResult) { case InstructionsForm.Feedback.Back: InstructionsForm.SetVisibility(false); MainForm.SetVisibility(true); break; default: break; } } public void FixedUpdate() { MainForm.Tween(); SettingsForm.Tween(); CreditsForm.Tween(); InstructionsForm.Tween(); } #endregion Engine Hooks #region Methods private void NewGame() { ResetStats(); ResetItems(); ResetPhases(); _transition.PrepareTransition(NewGameTransform, Vector3.zero, NewGameScene); _transition.ChangeScenes(); } private void ResetStats() { _ambassador.MaxHP = 8; _ambassador.Damage = 1; } private void ResetItems() { _ambassador.ItemList = new List<ObtainableItem>(); } private void ResetPhases() { _ambassador.SequenceCounters = new List<SequenceCounter>(); SequenceCounter main = new SequenceCounter { Name = "Main", Phase = 0, QuestTitle = "Main Quest", QuestDetails = "Talk to King Aylea XXXIII" }; SequenceCounter side = new SequenceCounter { Name = "Goldensage", Phase = 0, QuestTitle = "Side Quest", QuestDetails = "Talk to everyone to find the side quest." }; _ambassador.SequenceCounters.Add(main); _ambassador.SequenceCounters.Add(side); } #endregion Methods } [Serializable] public class MainForm : AsvarduilForm { #region Enumerations public enum Feedback { None, Settings, NewGame, LoadGame, Credits, Instructions, Support } #endregion Enumerations #region Constructor public MainForm(AsvarduilImage background, AsvarduilLabel label) : base(background, label) { } #endregion Constructor #region Variables / Properties public GUISkin Skin; public AudioClip ButtonSound; public AsvarduilImage SplashBackground; public AsvarduilImage TitlePane; public AsvarduilImageButton SettingsButton; public AsvarduilButton NewGameButton; public AsvarduilButton LoadGameButton; public AsvarduilButton SupportThisGameButton; public AsvarduilImageButton InstructionButton; public AsvarduilImageButton CreditsButton; public Feedback FormResult { get { Feedback result = Feedback.None; if(_settingsClicked) result = Feedback.Settings; if(_newGameClicked) result = Feedback.NewGame; if(_loadGameClicked) result = Feedback.LoadGame; if(_creditsClicked) result = Feedback.Credits; if(_instructionsClicked) result = Feedback.Instructions; if(_supportGameClicked) result = Feedback.Support; return result; } } private bool _settingsClicked = false; private bool _newGameClicked = false; private bool _loadGameClicked = false; private bool _creditsClicked = false; private bool _instructionsClicked = false; private bool _supportGameClicked = false; private Maestro _maestro; #endregion Variables / Properties #region Methods public void Initialize(Maestro maestro) { _maestro = maestro; } public void SetVisibility(bool visible) { float opacity = visible ? 1.0f : 0.0f; SplashBackground.TargetTint.a = opacity; TitlePane.TargetTint.a = opacity; SettingsButton.TargetTint.a = opacity; NewGameButton.TargetTint.a = opacity; LoadGameButton.TargetTint.a = opacity; SupportThisGameButton.TargetTint.a = opacity; InstructionButton.TargetTint.a = opacity; CreditsButton.TargetTint.a = opacity; } public override void DrawMe() { GUI.skin = Skin; SplashBackground.DrawMe(); TitlePane.DrawMe(); _settingsClicked = SettingsButton.IsClicked(); _loadGameClicked = LoadGameButton.IsClicked(); _newGameClicked = NewGameButton.IsClicked(); _creditsClicked = CreditsButton.IsClicked(); _instructionsClicked = InstructionButton.IsClicked(); _supportGameClicked = SupportThisGameButton.IsClicked(); if(FormResult != Feedback.None) _maestro.PlaySoundEffect(ButtonSound); } public override void Tween() { SplashBackground.Tween(); TitlePane.Tween(); SettingsButton.Tween(); NewGameButton.Tween(); LoadGameButton.Tween(); CreditsButton.Tween(); InstructionButton.Tween(); SupportThisGameButton.Tween(); } #endregion Methods } [Serializable] public class SettingsForm : AsvarduilForm { #region Enumerations public enum Feedback { None, Back } #endregion Enumerations #region Constructor public SettingsForm(AsvarduilImage background, AsvarduilLabel label) : base(background, label) { } #endregion Constructor #region Variables / Properties public GUISkin Skin; public AudioClip ButtonSound; public AsvarduilCheckbox AudioEnabledCheckbox; public AsvarduilSlider MasterVolume; public AsvarduilSlider MusicVolume; public AsvarduilSlider EffectsVolume; public AsvarduilSlider GraphicsQuality; public AsvarduilButton BackButton; public Feedback FormResult { get { Feedback result = Feedback.None; if(_backClicked) result = Feedback.Back; return result; } } private bool _backClicked = false; private Maestro _maestro; #endregion Variables / Properties #region Methods public void Initialize(Maestro maestro) { _maestro = maestro; AudioEnabledCheckbox.Value = Settings.soundEnabled; MasterVolume.Value = Settings.soundEnabled ? Settings.masterVolume : 0.0f; MusicVolume.Value = Settings.musVolume; EffectsVolume.Value = Settings.sfxVolume; GraphicsQuality.Value = QualitySettings.GetQualityLevel(); } public void SaveSettings() { Settings.soundEnabled = AudioEnabledCheckbox.Value; Settings.masterVolume = Settings.soundEnabled ? MasterVolume.Value : 0.0f; Settings.musVolume = MusicVolume.Value; Settings.sfxVolume = EffectsVolume.Value; if(DebugMode) Debug.Log("(Save) State of Settings static object:\r\n" + "Sound Enabled? " + Settings.soundEnabled + "\r\n" + "Master Volume: " + Settings.masterVolume + "\r\n" + "Music Volume: " + Settings.musVolume + "\r\n" + "Effects Volume: " + Settings.sfxVolume); } public void LoadSettings() { if(DebugMode) Debug.Log("(Load) State of Settings static object:\r\n" + "Sound Enabled? " + Settings.soundEnabled + "\r\n" + "Master Volume: " + Settings.masterVolume + "\r\n" + "Music Volume: " + Settings.musVolume + "\r\n" + "Effects Volume: " + Settings.sfxVolume); AudioEnabledCheckbox.Value = Settings.soundEnabled; MasterVolume.Value = Settings.masterVolume; MusicVolume.Value = Settings.musVolume; EffectsVolume.Value = Settings.sfxVolume; } public void SetVisibility(bool visible) { float opacity = visible ? 1.0f : 0.0f; Background.TargetTint.a = opacity; WindowName.TargetTint.a = opacity; BackButton.TargetTint.a = opacity; AudioEnabledCheckbox.TargetTint.a = opacity; MasterVolume.TargetTint.a = opacity; MasterVolume.Label.TargetTint.a = opacity; MusicVolume.TargetTint.a = opacity; MusicVolume.Label.TargetTint.a = opacity; EffectsVolume.TargetTint.a = opacity; EffectsVolume.Label.TargetTint.a = opacity; GraphicsQuality.TargetTint.a = opacity; GraphicsQuality.Label.TargetTint.a = opacity; } public override void DrawMe() { GUI.skin = Skin; Background.DrawMe(); WindowName.DrawMe(); //Settings.soundEnabled = AudioEnabledCheckbox.IsClicked(); if(AudioEnabledCheckbox.IsClicked()) { Settings.soundEnabled = AudioEnabledCheckbox.Value; } Settings.masterVolume = Settings.soundEnabled ? MasterVolume.IsMoved() : 0.0f; Settings.musVolume = MusicVolume.IsMoved(); Settings.sfxVolume = EffectsVolume.IsMoved(); QualitySettings.SetQualityLevel((int) GraphicsQuality.IsMoved()); _backClicked = BackButton.IsClicked(); if(_backClicked) _maestro.PlaySoundEffect(ButtonSound); } public override void Tween() { Background.Tween(); WindowName.Tween(); BackButton.Tween(); AudioEnabledCheckbox.Tween(); MasterVolume.Tween(); MusicVolume.Tween(); EffectsVolume.Tween(); GraphicsQuality.Tween(); } #endregion Methods } [Serializable] public class InstructionsForm : AsvarduilForm { #region Enumerations public enum Feedback { None, Back } #endregion Enumerations #region Variables / Properties public GUISkin Skin; public AudioClip ButtonSound; public AsvarduilImage WorldMapPane; public AsvarduilImage SidescrollingPane; public AsvarduilButton BackButton; private Maestro _maestro; private bool _backClicked; public Feedback FormResult { get { if(_backClicked) return Feedback.Back; return Feedback.None; } } #endregion Variables / Properties #region Constructors public InstructionsForm(AsvarduilImage bg, AsvarduilLabel header) : base(bg, header) { } #endregion Constructors #region Overrides public void Initialize(Maestro maestro) { _maestro = maestro; } public void SetVisibility(bool isVisible) { float opacity = isVisible ? 1.0f : 0.0f; Background.TargetTint.a = opacity; WorldMapPane.TargetTint.a = opacity; SidescrollingPane.TargetTint.a = opacity; BackButton.TargetTint.a = opacity; } public override void Tween () { Background.Tween(); WorldMapPane.Tween(); SidescrollingPane.Tween(); BackButton.Tween(); } public override void DrawMe() { GUI.skin = Skin; Background.DrawMe(); WorldMapPane.DrawMe(); SidescrollingPane.DrawMe(); _backClicked = BackButton.IsClicked(); if(_backClicked) { _maestro.PlaySoundEffect(ButtonSound); } } #endregion Overrides } [Serializable] public class CreditsForm : AsvarduilForm { #region Enumerations public enum Feedback { None, Back } #endregion Enumerations #region Constructors public CreditsForm(AsvarduilImage bg, AsvarduilLabel header) : base(bg, header) { } #endregion Constructors #region Variables / Properties public GUISkin skin; public AudioClip buttonSound; public AsvarduilButton BackButton; public AsvarduilLabel ThanksHeader; public AsvarduilLabel ThanksContributors; public AsvarduilLabel SpecialThanksHeader; public AsvarduilLabel SpecialThanksContributors; private bool _backClicked; private Maestro _maestro; public Feedback FormResult { get { if(_backClicked) return Feedback.Back; return Feedback.None; } } #endregion Variables / Properties #region Methods public void Initialize(Maestro maestro) { _maestro = maestro; } public void SetVisibility(bool visible) { float opacity = visible ? 1.0f : 0.0f; Background.TargetTint.a = opacity; BackButton.TargetTint.a = opacity; ThanksHeader.TargetTint.a = opacity; ThanksContributors.TargetTint.a = opacity; SpecialThanksHeader.TargetTint.a = opacity; SpecialThanksContributors.TargetTint.a = opacity; } public override void DrawMe() { GUI.skin = skin; Background.DrawMe(); ThanksHeader.DrawMe(); ThanksContributors.DrawMe(); SpecialThanksHeader.DrawMe(); SpecialThanksContributors.DrawMe(); _backClicked = BackButton.IsClicked(); if(_backClicked) { _maestro.PlaySoundEffect(buttonSound); } } public override void Tween() { Background.Tween(); ThanksHeader.Tween(); ThanksContributors.Tween(); SpecialThanksHeader.Tween(); SpecialThanksContributors.Tween(); BackButton.Tween(); } #endregion Methods }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using Cuyahoga.Core.Domain; using Cuyahoga.Core.Service; using Cuyahoga.Web.Admin.UI; using Cuyahoga.Web.UI; namespace Cuyahoga.Web.Admin { /// <summary> /// Summary description for MenuEdit. /// </summary> public class MenuEdit : AdminBasePage { private CustomMenu _activeMenu; protected System.Web.UI.WebControls.TextBox txtName; protected System.Web.UI.WebControls.Button btnSave; protected System.Web.UI.WebControls.DropDownList ddlPlaceholder; protected System.Web.UI.WebControls.RequiredFieldValidator rfvName; protected System.Web.UI.WebControls.Button btnBack; protected System.Web.UI.WebControls.ListBox lbxAvailableNodes; protected System.Web.UI.WebControls.ListBox lbxSelectedNodes; protected System.Web.UI.WebControls.Button btnAdd; protected System.Web.UI.WebControls.Button btnRemove; protected System.Web.UI.WebControls.Button btnUp; protected System.Web.UI.WebControls.Button btnDown; protected System.Web.UI.WebControls.Button btnDelete; private void Page_Load(object sender, System.EventArgs e) { base.Title = "Edit custom menu"; if (Context.Request.QueryString["MenuId"] != null) { if (Int32.Parse(Context.Request.QueryString["MenuId"]) == -1) { // Create a new CustomMenu instance this._activeMenu = new CustomMenu(); this._activeMenu.RootNode = base.ActiveNode; this.btnDelete.Visible = false; } else { // Get Menu data this._activeMenu = (CustomMenu)base.CoreRepository.GetObjectById(typeof(CustomMenu), Int32.Parse(Context.Request.QueryString["MenuId"])); this.btnDelete.Visible = true; this.btnDelete.Attributes.Add("onclick", "return confirm('Are you sure?');"); } } if (! this.IsPostBack) { this.txtName.Text = this._activeMenu.Name; BindPlaceholders(); BindAvailableNodes(); BindSelectedNodes(); } } private void BindPlaceholders() { string templatePath = Util.UrlHelper.GetApplicationPath() + this.ActiveNode.Template.Path; BaseTemplate template = (BaseTemplate)this.LoadControl(templatePath); this.ddlPlaceholder.DataSource = template.Containers; this.ddlPlaceholder.DataValueField = "Key"; this.ddlPlaceholder.DataTextField = "Key"; this.ddlPlaceholder.DataBind(); if (this._activeMenu.Id != -1) { ListItem li = this.ddlPlaceholder.Items.FindByValue(this._activeMenu.Placeholder); if (li != null) { li.Selected = true; } } } private void BindAvailableNodes() { IList rootNodes = this.ActiveNode.Site.RootNodes; AddAvailableNodes(rootNodes); } private void BindSelectedNodes() { foreach (Node node in this._activeMenu.Nodes) { this.lbxSelectedNodes.Items.Add(new ListItem(node.Title, node.Id.ToString())); // also remove from available nodes ListItem item = this.lbxAvailableNodes.Items.FindByValue(node.Id.ToString()); if (item != null) { this.lbxAvailableNodes.Items.Remove(item); } } } private void AddAvailableNodes(IList nodes) { foreach (Node node in nodes) { int indentSpaces = node.Level * 5; string itemIndentSpaces = String.Empty; for (int i = 0; i < indentSpaces; i++) { itemIndentSpaces += "&nbsp;"; } ListItem li = new ListItem(Context.Server.HtmlDecode(itemIndentSpaces) + node.Title, node.Id.ToString()); this.lbxAvailableNodes.Items.Add(li); if (node.ChildNodes.Count > 0) { AddAvailableNodes(node.ChildNodes); } } } private void AttachSelectedNodes() { this._activeMenu.Nodes.Clear(); foreach (ListItem item in this.lbxSelectedNodes.Items) { Node node = (Node)base.CoreRepository.GetObjectById(typeof(Node), Int32.Parse(item.Value)); this._activeMenu.Nodes.Add(node); } } private void SaveMenu() { base.CoreRepository.ClearQueryCache("Menus"); if (this._activeMenu.Id > 0) { base.CoreRepository.UpdateObject(this._activeMenu); } else { base.CoreRepository.SaveObject(this._activeMenu); Context.Response.Redirect(String.Format("NodeEdit.aspx?NodeId={0}", this.ActiveNode.Id)); } } private void SynchronizeNodeListBoxes() { // First fetch a fresh list of available nodes because everything has to be // nice in place. this.lbxAvailableNodes.Items.Clear(); BindAvailableNodes(); // make sure the selected nodes are not in the available nodes list. int itemCount = this.lbxAvailableNodes.Items.Count; for (int i = itemCount - 1; i >= 0; i--) { ListItem item = this.lbxAvailableNodes.Items[i]; if (this.lbxSelectedNodes.Items.FindByValue(item.Value) != null) { this.lbxAvailableNodes.Items.RemoveAt(i); } } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); this.btnUp.Click += new System.EventHandler(this.btnUp_Click); this.btnDown.Click += new System.EventHandler(this.btnDown_Click); this.btnSave.Click += new System.EventHandler(this.btnSave_Click); this.btnBack.Click += new System.EventHandler(this.btnBack_Click); this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void btnBack_Click(object sender, System.EventArgs e) { Context.Response.Redirect("NodeEdit.aspx?NodeId=" + this.ActiveNode.Id.ToString()); } private void btnSave_Click(object sender, System.EventArgs e) { if (this.IsValid) { this._activeMenu.Name = this.txtName.Text; this._activeMenu.Placeholder = this.ddlPlaceholder.SelectedValue; try { AttachSelectedNodes(); SaveMenu(); ShowMessage("Menu saved"); } catch (Exception ex) { ShowError(ex.Message); } } } private void btnDelete_Click(object sender, System.EventArgs e) { if (this._activeMenu != null) { base.CoreRepository.ClearQueryCache("Menus"); try { base.CoreRepository.DeleteObject(this._activeMenu); Context.Response.Redirect("NodeEdit.aspx?NodeId=" + this.ActiveNode.Id.ToString()); } catch (Exception ex) { ShowError(ex.Message); } } } private void btnAdd_Click(object sender, System.EventArgs e) { ListItem item = this.lbxAvailableNodes.SelectedItem; if (item != null) { this.lbxSelectedNodes.Items.Add(item); item.Selected = false; } SynchronizeNodeListBoxes(); } private void btnRemove_Click(object sender, System.EventArgs e) { ListItem item = this.lbxSelectedNodes.SelectedItem; if (item != null) { this.lbxSelectedNodes.Items.Remove(this.lbxSelectedNodes.SelectedItem); item.Selected = false; } SynchronizeNodeListBoxes(); } private void btnUp_Click(object sender, System.EventArgs e) { ListItem item = this.lbxSelectedNodes.SelectedItem; if (item != null) { int origPosition = this.lbxSelectedNodes.SelectedIndex; if (origPosition > 0) { this.lbxSelectedNodes.Items.Remove(item); this.lbxSelectedNodes.Items.Insert(origPosition - 1, item); } } } private void btnDown_Click(object sender, System.EventArgs e) { ListItem item = this.lbxSelectedNodes.SelectedItem; if (item != null) { int origPosition = this.lbxSelectedNodes.SelectedIndex; if (origPosition < this.lbxSelectedNodes.Items.Count -1) { this.lbxSelectedNodes.Items.Remove(item); this.lbxSelectedNodes.Items.Insert(origPosition + 1, item); } } } } }
using UnityEngine; using System.Collections; using System.Linq; using System.Collections.Generic; namespace RadicalLibrary { public static class QuadBez { public static Vector3 Interp(Vector3 st, Vector3 en, Vector3 ctrl, float t) { float d = 1f - t; return d * d * st + 2f * d * t * ctrl + t * t * en; } public static Vector3 Velocity(Vector3 st, Vector3 en, Vector3 ctrl, float t) { return (2f * st - 4f * ctrl + 2f * en) * t + 2f * ctrl - 2f * st; } public static void GizmoDraw(Vector3 st, Vector3 en, Vector3 ctrl, float t) { Gizmos.color = Color.red; Gizmos.DrawLine(st, ctrl); Gizmos.DrawLine(ctrl, en); Gizmos.color = Color.white; Vector3 prevPt = st; for (int i = 1; i <= 20; i++) { float pm = (float) i / 20f; Vector3 currPt = Interp(st,en,ctrl,pm); Gizmos.DrawLine(currPt, prevPt); prevPt = currPt; } Gizmos.color = Color.blue; Vector3 pos = Interp(st,en, ctrl,t); Gizmos.DrawLine(pos, pos + Velocity(st,en,ctrl,t)); } } public static class CubicBez { public static Vector3 Interp(Vector3 st, Vector3 en, Vector3 ctrl1, Vector3 ctrl2, float t) { float d = 1f - t; return d * d * d * st + 3f * d * d * t * ctrl1 + 3f * d * t * t * ctrl2 + t * t * t * en; } public static Vector3 Velocity(Vector3 st, Vector3 en, Vector3 ctrl1, Vector3 ctrl2,float t) { return (-3f * st + 9f * ctrl1 - 9f * ctrl2 + 3f * en) * t * t + (6f * st - 12f * ctrl1 + 6f * ctrl2) * t - 3f * st + 3f * ctrl1; } public static void GizmoDraw(Vector3 st, Vector3 en, Vector3 ctrl1, Vector3 ctrl2,float t) { Gizmos.color = Color.red; Gizmos.DrawLine(st, ctrl1); Gizmos.DrawLine(ctrl2, en); Gizmos.color = Color.white; Vector3 prevPt = st; for (int i = 1; i <= 20; i++) { float pm = (float) i / 20f; Vector3 currPt = Interp(st,en,ctrl1, ctrl2, pm); Gizmos.DrawLine(currPt, prevPt); prevPt = currPt; } Gizmos.color = Color.blue; Vector3 pos = Interp(st,en,ctrl1, ctrl2, t); Gizmos.DrawLine(pos, pos + Velocity(st,en,ctrl1,ctrl2,t)); } } public static class CRSpline { public static Vector3 Interp(Vector3[] pts, float t) { int numSections = pts.Length - 3; int currPt = Mathf.Min(Mathf.FloorToInt(t * (float) numSections), numSections - 1); float u = t * (float) numSections - (float) currPt; Vector3 a = pts[currPt]; Vector3 b = pts[currPt + 1]; Vector3 c = pts[currPt + 2]; Vector3 d = pts[currPt + 3]; return .5f * ( (-a + 3f * b - 3f * c + d) * (u * u * u) + (2f * a - 5f * b + 4f * c - d) * (u * u) + (-a + c) * u + 2f * b ); } public static Vector3 InterpConstantSpeedOld(Vector3[] pts, float t) { int numSections = pts.Length - 3; float mag = 0; float [] sizes = new float[pts.Length-1]; for(var i = 0; i < pts.Length-1; i++) { var m = (pts[i+1] - pts[i]).magnitude; sizes[i] = m; mag += m; } int currPt=1; float s=0; double u = 0; do { double tAtBeginning = s/mag; double tAtEnd = (s + sizes[currPt+0])/mag; u = (t-tAtBeginning) / (tAtEnd - tAtBeginning); if(double.IsNaN(u) || u<0 || u>1) { s+=sizes[currPt]; currPt++; } else break; } while(currPt < numSections+1); u = Mathf.Clamp01((float)u); Vector3 a = pts[currPt-1]; Vector3 b = pts[currPt + 0]; Vector3 c = pts[currPt + 1]; Vector3 d = pts[currPt + 2]; //return CubicBez.Interp(a,d,b,c,(float)u); return .5f * ( (-a + 3f * b - 3f * c + d) * (float)(u * u * u) + (2f * a - 5f * b + 4f * c - d) * (float)(u * u) + (-a + c) * (float)u + 2f * b ); } public static Vector3 InterpConstantSpeed(Vector3[] pts, float t) { int numSections = pts.Length - 3; float mag = 0; float [] sizes = new float[pts.Length-1]; for(var i = 0; i < pts.Length-1; i++) { var m = (pts[i+1] - pts[i]).magnitude; sizes[i] = m; mag += m; } int currPt=1; float s=0; double u = 0; do { double tAtBeginning = s/mag; double tAtEnd = (s + sizes[currPt+0])/mag; u = (t-tAtBeginning) / (tAtEnd - tAtBeginning); if(double.IsNaN(u) || u<0 || u>1) { s+=sizes[currPt]; currPt++; } else break; } while(currPt < numSections+1); u = Mathf.Clamp01((float)u); Vector3 a = pts[currPt-1]; Vector3 b = pts[currPt + 0]; Vector3 c = pts[currPt + 1]; Vector3 d = pts[currPt + 2]; //return CubicBez.Interp(a,d,b,c,(float)u); return .5f * ( (-a + 3f * b - 3f * c + d) * (float)(u * u * u) + (2f * a - 5f * b + 4f * c - d) * (float)(u * u) + (-a + c) * (float)u + 2f * b ); } public static Vector3 Velocity(Vector3[] pts, float t) { int numSections = pts.Length - 3; int currPt = Mathf.Min(Mathf.FloorToInt(t * (float) numSections), numSections - 1); float u = t * (float) numSections - (float) currPt; Vector3 a = pts[currPt]; Vector3 b = pts[currPt + 1]; Vector3 c = pts[currPt + 2]; Vector3 d = pts[currPt + 3]; return 1.5f * (-a + 3f * b - 3f * c + d) * (u * u) + (2f * a -5f * b + 4f * c - d) * u + .5f * c - .5f * a; } public static void GizmoDraw(Vector3[] pts, float t) { Gizmos.color = Color.white; Vector3 prevPt = Interp(pts, 0); for (int i = 1; i <= 20; i++) { float pm = (float) i / 20f; Vector3 currPt = Interp(pts, pm); Gizmos.DrawLine(currPt, prevPt); prevPt = currPt; } Gizmos.color = Color.blue; Vector3 pos = Interp(pts, t); Gizmos.DrawLine(pos, pos + Velocity(pts, t)); } } public class Interesting { } public static class Spline { public static Vector3 Interp(Path pts, float t) { return Interp ( pts, t, EasingType.Linear); } public static Vector3 Interp(Path pts, float t, EasingType ease) { return Interp ( pts, t, ease, true); } public static Vector3 Interp(Path pts, float t, EasingType ease, bool easeIn) { return Interp ( pts, t, ease, easeIn, true); } public static Vector3 Interp(Path pts, float t, EasingType ease, bool easeIn, bool easeOut) { t = Ease(t, ease, easeIn, easeOut); if(pts.Length == 0) { return Vector3.zero; } else if(pts.Length ==1 ) { return pts[0]; } else if(pts.Length == 2) { return Vector3.Lerp(pts[0], pts[1], t); } else if(pts.Length == 3) { return QuadBez.Interp(pts[0], pts[2], pts[1], t); } else if(pts.Length == 4) { return CubicBez.Interp(pts[0], pts[3], pts[1], pts[2], t); } else { return CRSpline.Interp(Wrap(pts), t); } } private static float Ease(float t) { return Ease ( t, EasingType.Linear); } private static float Ease(float t, EasingType ease) { return Ease ( t, ease, true); } private static float Ease(float t, EasingType ease, bool easeIn) { return Ease ( t, ease, easeIn, true); } private static float Ease(float t, EasingType ease, bool easeIn, bool easeOut) { t = Mathf.Clamp01(t); if(easeIn && easeOut) { t = Easing.EaseInOut(t, ease); } else if(easeIn) { t = Easing.EaseIn(t, ease); } else if(easeOut) { t = Easing.EaseOut(t, ease); } return t; } public static Vector3 InterpConstantSpeed(Path pts, float t) { return InterpConstantSpeed( pts, t, EasingType.Linear); } public static Vector3 InterpConstantSpeed(Path pts, float t, EasingType ease) { return InterpConstantSpeed( pts, t, ease, true); } public static Vector3 InterpConstantSpeed(Path pts, float t, EasingType ease, bool easeIn) { return InterpConstantSpeed( pts, t, ease, easeIn, true); } public static Vector3 InterpConstantSpeed(Path pts, float t, EasingType ease, bool easeIn, bool easeOut ) { t = Ease(t, ease, easeIn, easeOut); if (pts.Length == 0) { return Vector3.zero; } else if (pts.Length == 1) { return pts[0]; } else if (pts.Length == 2) { return Vector3.Lerp(pts[0], pts[1], t); } else if (pts.Length == 3) { return QuadBez.Interp(pts[0], pts[2], pts[1], t); } else if (pts.Length == 4) { return CubicBez.Interp(pts[0], pts[3], pts[1], pts[2], t); } else { return CRSpline.InterpConstantSpeed(Wrap(pts), t); } } static float Clamp(float f) { return Mathf.Clamp01(f); } public static Vector3 MoveOnPath(Path pts, Vector3 currentPosition, ref float pathPosition) { return MoveOnPath( pts, currentPosition, ref pathPosition, 1f); } public static Vector3 MoveOnPath(Path pts, Vector3 currentPosition, ref float pathPosition, float maxSpeed) { return MoveOnPath( pts, currentPosition, ref pathPosition, maxSpeed, 100); } public static Vector3 MoveOnPath(Path pts, Vector3 currentPosition, ref float pathPosition, float maxSpeed, float smoothnessFactor) { return MoveOnPath( pts, currentPosition, ref pathPosition, maxSpeed, smoothnessFactor, EasingType.Linear); } public static Vector3 MoveOnPath(Path pts, Vector3 currentPosition, ref float pathPosition, float maxSpeed, float smoothnessFactor, EasingType ease) { return MoveOnPath( pts, currentPosition, ref pathPosition, maxSpeed, smoothnessFactor, ease, true); } public static Vector3 MoveOnPath(Path pts, Vector3 currentPosition, ref float pathPosition, float maxSpeed, float smoothnessFactor, EasingType ease, bool easeIn) { return MoveOnPath( pts, currentPosition, ref pathPosition, maxSpeed, smoothnessFactor, ease, easeIn, true); } public static Vector3 MoveOnPath(Path pts, Vector3 currentPosition, ref float pathPosition, float maxSpeed, float smoothnessFactor, EasingType ease, bool easeIn, bool easeOut) { maxSpeed *= Time.deltaTime; pathPosition = Clamp(pathPosition); var goal = InterpConstantSpeed(pts, pathPosition, ease, easeIn, easeOut); float distance; while((distance = (goal - currentPosition).magnitude) <= maxSpeed && pathPosition != 1) { //currentPosition = goal; //maxSpeed -= distance; pathPosition = Clamp(pathPosition + 1/smoothnessFactor); goal = InterpConstantSpeed(pts, pathPosition, ease, easeIn, easeOut); } if(distance != 0) { currentPosition = Vector3.MoveTowards(currentPosition, goal, maxSpeed); } return currentPosition; } public static Vector3 MoveOnPath(Path pts, Vector3 currentPosition, ref float pathPosition, ref Quaternion rotation) { return MoveOnPath( pts, currentPosition, ref pathPosition, ref rotation, 1f); } public static Vector3 MoveOnPath(Path pts, Vector3 currentPosition, ref float pathPosition, ref Quaternion rotation, float maxSpeed) { return MoveOnPath( pts, currentPosition, ref pathPosition, ref rotation, maxSpeed, 100); } public static Vector3 MoveOnPath(Path pts, Vector3 currentPosition, ref float pathPosition, ref Quaternion rotation, float maxSpeed, float smoothnessFactor) { return MoveOnPath( pts, currentPosition, ref pathPosition, ref rotation, maxSpeed, smoothnessFactor, EasingType.Linear); } public static Vector3 MoveOnPath(Path pts, Vector3 currentPosition, ref float pathPosition, ref Quaternion rotation, float maxSpeed, float smoothnessFactor, EasingType ease) { return MoveOnPath( pts, currentPosition, ref pathPosition, ref rotation, maxSpeed, smoothnessFactor, ease, true); } public static Vector3 MoveOnPath(Path pts, Vector3 currentPosition, ref float pathPosition, ref Quaternion rotation, float maxSpeed, float smoothnessFactor, EasingType ease, bool easeIn) { return MoveOnPath( pts, currentPosition, ref pathPosition, ref rotation, maxSpeed, smoothnessFactor, ease, easeIn, true); } public static Vector3 MoveOnPath(Path pts, Vector3 currentPosition, ref float pathPosition, ref Quaternion rotation, float maxSpeed, float smoothnessFactor, EasingType ease, bool easeIn, bool easeOut) { var result = MoveOnPath(pts, currentPosition, ref pathPosition, maxSpeed, smoothnessFactor, ease, easeIn, easeOut); rotation = result.Equals(currentPosition) ? Quaternion.identity : Quaternion.LookRotation(result - currentPosition); return result; } public static Quaternion RotationBetween(Path pts, float t1, float t2) { return RotationBetween( pts, t1, t2, EasingType.Linear); } public static Quaternion RotationBetween(Path pts, float t1, float t2, EasingType ease) { return RotationBetween( pts, t1, t2, ease, true); } public static Quaternion RotationBetween(Path pts, float t1, float t2, EasingType ease, bool easeIn) { return RotationBetween( pts, t1, t2, ease, easeIn, true); } public static Quaternion RotationBetween(Path pts, float t1, float t2, EasingType ease, bool easeIn, bool easeOut) { return Quaternion.LookRotation(Interp(pts, t2, ease, easeIn, easeOut) - Interp(pts, t1, ease, easeIn, easeOut)); } public static Vector3 Velocity(Path pts, float t) { return Velocity ( pts, t, EasingType.Linear); } public static Vector3 Velocity(Path pts, float t, EasingType ease) { return Velocity ( pts, t, ease, true); } public static Vector3 Velocity(Path pts, float t, EasingType ease, bool easeIn ) { return Velocity ( pts, t, ease, easeIn, true); } public static Vector3 Velocity(Path pts, float t, EasingType ease, bool easeIn, bool easeOut) { t = Ease(t); if(pts.Length == 0) { return Vector3.zero; } else if(pts.Length ==1 ) { return pts[0]; } else if(pts.Length == 2) { return Vector3.Lerp(pts[0], pts[1], t); } else if(pts.Length == 3) { return QuadBez.Velocity(pts[0], pts[2], pts[1], t); } else if(pts.Length == 3) { return CubicBez.Velocity(pts[0], pts[3], pts[1], pts[2], t); } else { return CRSpline.Velocity(Wrap(pts), t); } } public static Vector3[] Wrap(Vector3[] path) { return (new Vector3[] { path[0] }).Concat(path).Concat(new Vector3[] { path[path.Length-1]}).ToArray(); } public static void GizmoDraw( Vector3[] pts, float t) { GizmoDraw( pts, t, EasingType.Linear); } public static void GizmoDraw( Vector3[] pts, float t, EasingType ease) { GizmoDraw( pts, t, ease, true); } public static void GizmoDraw( Vector3[] pts, float t, EasingType ease, bool easeIn) { GizmoDraw( pts, t, ease, easeIn, true); } public static void GizmoDraw( Vector3[] pts, float t, EasingType ease, bool easeIn, bool easeOut) { Gizmos.color = Color.white; Vector3 prevPt = Interp(pts, 0); for (int i = 1; i <= 20; i++) { float pm = (float) i / 20f; Vector3 currPt = Interp(pts, pm, ease, easeIn, easeOut); Gizmos.DrawLine(currPt, prevPt); prevPt = currPt; } Gizmos.color = Color.blue; Vector3 pos = Interp(pts, t, ease, easeIn, easeOut); Gizmos.DrawLine(pos, pos + Velocity(pts, t, ease, easeIn, easeOut)); } public class Path { private Vector3[] _path; public Vector3[] path { get { return _path; } set { _path = value; } } public int Length { get { return path != null ? path.Length : 0; } } public Vector3 this[int index] { get { return path[index]; } } public static implicit operator Path(Vector3[] path) { return new Path() {path = path}; } public static implicit operator Vector3[](Path p) { return p != null ? p.path : new Vector3[0]; } public static implicit operator Path(Transform[] path) { return new Path() {path = path.Select(p=>p.position).ToArray()}; } public static implicit operator Path(GameObject[] path) { return new Path() {path = path.Select(p=>p.transform.position).ToArray()}; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using BugReport.DataModel; namespace BugReport.Query { public class InvalidQueryException : Exception { public InvalidQueryException(string message, string queryString, int position) : base($"{message} at position {position}") { } } public class QueryParser : IDisposable { QuerySyntaxParser _parser; string _queryString; IReadOnlyDictionary<string, Expression> _customIsValues; public QueryParser(string queryString, IReadOnlyDictionary<string, Expression> customIsValues) { _queryString = queryString; _customIsValues = customIsValues ?? new Dictionary<string, Expression>(); _parser = new QuerySyntaxParser(queryString); } public static Expression Parse(string queryString, IReadOnlyDictionary<string, Expression> customIsValues) { QueryParser queryParser = new QueryParser(queryString, customIsValues); return queryParser.Parse(); } public Expression Parse() { Expression expr = ParseExpression_Or(); if (expr == null) { throw new InvalidQueryException("The query is empty", _queryString, 0); } return expr; } Expression ParseExpression_Or() { Expression expr = ParseExpression_And(); Token token = _parser.Peek(); if (!token.IsOperatorOr()) { return expr; } _parser.Skip(); if (expr == null) { throw new InvalidQueryException("Expression expected before OR operator", _queryString, token.Position); } List<Expression> expressions = new List<Expression>(); expressions.Add(expr); for (;;) { expr = ParseExpression_And(); expressions.Add(expr); if (expr == null) { throw new InvalidQueryException("Expression expected after OR operator", _queryString, token.Position); } token = _parser.Peek(); if (!token.IsOperatorOr()) { return new ExpressionOr(expressions); } _parser.Skip(); } } Expression ParseExpression_And() { Token token = _parser.Peek(); if (token.IsEndOfQuery() || token.IsOperatorOr() || token.IsBracketRight()) { return null; } if (token.IsOperatorAnd()) { throw new InvalidQueryException("Expression expected before AND operator", _queryString, token.Position); } Expression expr = ParseExpression_Single(); token = _parser.Peek(); if (token.IsEndOfQuery() || token.IsOperatorOr() || token.IsBracketRight()) { return expr; } List<Expression> expressions = new List<Expression>(); expressions.Add(expr); for (;;) { bool hasOperatorAnd = false; token = _parser.Peek(); if (token.IsOperatorAnd()) { hasOperatorAnd = true; _parser.Skip(); } expr = ParseExpression_Single(); if (expr == null) { if (hasOperatorAnd) { throw new InvalidQueryException("Expression expected after AND operator", _queryString, token.Position); } Debug.Assert(expressions.Count > 1); return new ExpressionAnd(expressions); } expressions.Add(expr); } } Expression ParseExpression_Single() { Token token = _parser.Peek(); if (token.IsEndOfQuery() || token.IsOperatorOr() || token.IsOperatorAnd() || token.IsBracketRight()) { return null; } if (token.IsOperatorNot()) { _parser.Skip(); Expression expr = new ExpressionNot(ParseExpression_Single()); if (expr == null) { throw new InvalidQueryException("The sub-expression after NOT operator is empty", _queryString, token.Position); } return expr; } if (token.IsKeyValuePair()) { Expression expr; if (token.IsKeyValuePair("label")) { if (IsRegex(token.Word2)) { expr = new ExpressionLabelPattern(token.Word2); } else { expr = new ExpressionLabel(token.Word2); } } else if (token.IsKeyValuePair("-label")) { if (IsRegex(token.Word2)) { expr = new ExpressionNot(new ExpressionLabelPattern(token.Word2)); } else { expr = new ExpressionNot(new ExpressionLabel(token.Word2)); } } else if (token.IsKeyValuePair("milestone")) { if (IsRegex(token.Word2)) { expr = new ExpressionMilestonePattern(token.Word2); } else { expr = new ExpressionMilestone(token.Word2); } } else if (token.IsKeyValuePair("-milestone")) { if (IsRegex(token.Word2)) { expr = new ExpressionNot(new ExpressionMilestonePattern(token.Word2)); } else { expr = new ExpressionNot(new ExpressionMilestone(token.Word2)); } } else if (token.IsKeyValuePair("is")) { if (token.IsKeyValuePair("is", "issue")) { expr = new ExpressionIsIssue(true); } else if (token.IsKeyValuePair("is", "pr")) { expr = new ExpressionIsIssue(false); } else if (token.IsKeyValuePair("is", "open")) { expr = new ExpressionIsOpen(true); } else if (token.IsKeyValuePair("is", "closed")) { expr = new ExpressionIsOpen(false); } else if (_customIsValues.TryGetValue(token.Word2, out expr)) { } else { throw new InvalidQueryException($"Unexpected value '{token}' in key-value pair, expected: [pr|issue|open|close]", _queryString, token.Position); } } else if (token.IsKeyValuePair("assignee")) { expr = new ExpressionAssignee(token.Word2); } else if (token.IsKeyValuePair("-assignee")) { expr = new ExpressionNot(new ExpressionAssignee(token.Word2)); } else if (token.IsKeyValuePair("no")) { if (token.IsKeyValuePair("no", "milestone")) { expr = new ExpressionMilestone(null); } else if (token.IsKeyValuePair("no", "assignee")) { expr = new ExpressionAssignee(null); } else { throw new InvalidQueryException($"Unexpected value '{token}' in key-value pair, expected: [milestone|assignee]", _queryString, token.Position); } } else { throw new InvalidQueryException($"Unexpected key '{token}' in key-value pair, expected: [label|-label|milestone|is|assignee]", _queryString, token.Position); } _parser.Skip(); return expr; } if (token.IsBracketLeft()) { _parser.Skip(); Expression expr = Parse(); if (expr == null) { throw new InvalidQueryException("The sub-expression in brackets is empty", _queryString, token.Position); } Token rightBracketToken = _parser.Read(); if (!rightBracketToken.IsBracketRight()) { throw new InvalidQueryException("Cannot find matching bracket ')'", _queryString, token.Position); } return expr; } throw new InvalidQueryException("Unexpected expression -- expected ! or ( or key-value pair", _queryString, token.Position); } public static bool IsRegex(string value) { return (value.Contains(".*") || value.Contains("..")); } public void Close() { if (_parser != null) { _parser.Close(); } } public void Dispose() { if (_parser != null) { _parser.Dispose(); _parser = null; } } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using StackExchange.Redis; using System; using System.Abstract; using System.Collections.Generic; namespace Contoso.Abstract { /// <summary> /// IRedisServiceCache /// </summary> public interface IRedisServiceCache : IDistributedServiceCache { /// <summary> /// Gets the cache. /// </summary> IDatabase Cache { get; } } /// <summary> /// RedisServiceCache /// </summary> public partial class RedisServiceCache : IRedisServiceCache, ServiceCacheManager.ISetupRegistration { static RedisServiceCache() { ServiceCacheManager.EnsureRegistration(); } /// <summary> /// Initializes a new instance of the <see cref="RedisServiceCache" /> class. /// </summary> /// <param name="configuration">The configuration.</param> public RedisServiceCache(string configuration) : this(ConnectionMultiplexer.Connect(configuration), 0) { } /// <summary> /// Initializes a new instance of the <see cref="RedisServiceCache" /> class. /// </summary> /// <param name="connection">The connection.</param> /// <param name="db">The database.</param> public RedisServiceCache(ConnectionMultiplexer connection, int db) : this(connection.GetDatabase(0)) { } /// <summary> /// Initializes a new instance of the <see cref="MemcachedServiceCache" /> class. /// </summary> /// <param name="connection">The connection.</param> /// <exception cref="System.ArgumentNullException">connection</exception> public RedisServiceCache(IDatabase database) { if (database == null) throw new ArgumentNullException("database"); Cache = database; Settings = new ServiceCacheSettings(); } Action<IServiceLocator, string> ServiceCacheManager.ISetupRegistration.DefaultServiceRegistrar { get { return (locator, name) => ServiceCacheManager.RegisterInstance<IRedisServiceCache>(this, locator, name); } } /// <summary> /// Gets the service object of the specified type. /// </summary> /// <param name="serviceType">An object that specifies the type of service object to get.</param> /// <returns> /// A service object of type <paramref name="serviceType"/>. /// -or- /// null if there is no service object of type <paramref name="serviceType"/>. /// </returns> public object GetService(Type serviceType) { throw new NotImplementedException(); } /// <summary> /// Gets or sets the <see cref="System.Object"/> with the specified name. /// </summary> public object this[string name] { get { return Get(null, name); } set { Set(null, name, CacheItemPolicy.Default, value, ServiceCacheByDispatcher.Empty); } } /// <summary> /// Adds the specified tag. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="itemPolicy">The item policy.</param> /// <param name="value">The value.</param> /// <param name="dispatch">The dispatch.</param> /// <returns></returns> public object Add(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch) { if (itemPolicy == null) throw new ArgumentNullException("itemPolicy"); var updateCallback = itemPolicy.UpdateCallback; if (updateCallback != null) updateCallback(name, value); // if (itemPolicy.SlidingExpiration != ServiceCache.NoSlidingExpiration) throw new ArgumentOutOfRangeException("itemPolicy.SlidingExpiration", "not supported."); if (itemPolicy.RemovedCallback != null) throw new ArgumentOutOfRangeException("itemPolicy.RemovedCallback", "not supported."); // throw new NotImplementedException(); } /// <summary> /// Gets the item from cache associated with the key provided. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <returns> /// The cached item. /// </returns> public object Get(object tag, string name) { throw new NotSupportedException(); } /// <summary> /// Gets the specified tag. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="registration">The registration.</param> /// <param name="header">The header.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public object Get(object tag, string name, IServiceCacheRegistration registration, out CacheItemHeader header) { if (registration == null) throw new ArgumentNullException("registration"); throw new NotImplementedException(); } /// <summary> /// Gets the specified tag. /// </summary> /// <param name="tag">The tag.</param> /// <param name="names">The names.</param> /// <returns></returns> public object Get(object tag, IEnumerable<string> names) { throw new NotImplementedException(); } /// <summary> /// Gets the specified registration. /// </summary> /// <param name="tag">The tag.</param> /// <param name="registration">The registration.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.NotImplementedException"></exception> public IEnumerable<CacheItemHeader> Get(object tag, IServiceCacheRegistration registration) { if (registration == null) throw new ArgumentNullException("registration"); throw new NotImplementedException(); } /// <summary> /// Tries the get. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <returns></returns> public bool TryGet(object tag, string name, out object value) { throw new NotSupportedException(); } /// <summary> /// Removes from cache the item associated with the key provided. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="registration">The registration.</param> /// <returns> /// The item removed from the Cache. If the value in the key parameter is not found, returns null. /// </returns> public object Remove(object tag, string name, IServiceCacheRegistration registration) { throw new NotSupportedException(); } /// <summary> /// Adds an object into cache based on the parameters provided. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="itemPolicy">The itemPolicy object.</param> /// <param name="value">The value to store in cache.</param> /// <param name="dispatch">The dispatch.</param> /// <returns></returns> public object Set(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch) { if (itemPolicy == null) throw new ArgumentNullException("itemPolicy"); var updateCallback = itemPolicy.UpdateCallback; if (updateCallback != null) updateCallback(name, value); // throw new NotImplementedException(); } /// <summary> /// Settings /// </summary> public ServiceCacheSettings Settings { get; private set; } #region TouchableCacheItem ///// <summary> ///// DefaultTouchableCacheItem ///// </summary> //public class DefaultTouchableCacheItem : ITouchableCacheItem //{ // private MemcachedServiceCache _parent; // private ITouchableCacheItem _base; // public DefaultTouchableCacheItem(MemcachedServiceCache parent, ITouchableCacheItem @base) { _parent = parent; _base = @base; } // public void Touch(object tag, string[] names) // { // if (names == null || names.Length == 0) // return; // throw new NotSupportedException(); // } // public object MakeDependency(object tag, string[] names) // { // if (names == null || names.Length == 0) // return null; // throw new NotSupportedException(); // } //} #endregion #region Domain-specific /// <summary> /// Gets the cache. /// </summary> public IDatabase Cache { get; private set; } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; // using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Framework.Capabilities { /// <summary> /// XXX Probably not a particularly nice way of allow us to get the scene presence from the scene (chiefly so that /// we can popup a message on the user's client if the inventory service has permanently failed). But I didn't want /// to just pass the whole Scene into CAPS. /// </summary> public delegate IClientAPI GetClientDelegate(UUID agentID); public class Caps { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_httpListenerHostName; private uint m_httpListenPort; /// <summary> /// This is the uuid portion of every CAPS path. It is used to make capability urls private to the requester. /// </summary> private string m_capsObjectPath; public string CapsObjectPath { get { return m_capsObjectPath; } } private CapsHandlers m_capsHandlers; private Dictionary<string, PollServiceEventArgs> m_pollServiceHandlers = new Dictionary<string, PollServiceEventArgs>(); private Dictionary<string, string> m_externalCapsHandlers = new Dictionary<string, string>(); private IHttpServer m_httpListener; private UUID m_agentID; private string m_regionName; private ManualResetEvent m_capsActive = new ManualResetEvent(false); public UUID AgentID { get { return m_agentID; } } public string RegionName { get { return m_regionName; } } public string HostName { get { return m_httpListenerHostName; } } public uint Port { get { return m_httpListenPort; } } public IHttpServer HttpListener { get { return m_httpListener; } } public bool SSLCaps { get { return m_httpListener.UseSSL; } } public string SSLCommonName { get { return m_httpListener.SSLCommonName; } } public CapsHandlers CapsHandlers { get { return m_capsHandlers; } } public Dictionary<string, string> ExternalCapsHandlers { get { return m_externalCapsHandlers; } } public Caps(IHttpServer httpServer, string httpListen, uint httpPort, string capsPath, UUID agent, string regionName) { m_capsObjectPath = capsPath; m_httpListener = httpServer; m_httpListenerHostName = httpListen; m_httpListenPort = httpPort; if (httpServer != null && httpServer.UseSSL) { m_httpListenPort = httpServer.SSLPort; httpListen = httpServer.SSLCommonName; httpPort = httpServer.SSLPort; } m_agentID = agent; m_capsHandlers = new CapsHandlers(httpServer, httpListen, httpPort); m_regionName = regionName; m_capsActive.Reset(); } ~Caps() { m_capsActive.Dispose(); } /// <summary> /// Register a handler. This allows modules to register handlers. /// </summary> /// <param name="capName"></param> /// <param name="handler"></param> public void RegisterHandler(string capName, IRequestHandler handler) { //m_log.DebugFormat("[CAPS]: Registering handler for \"{0}\": path {1}", capName, handler.Path); m_capsHandlers[capName] = handler; } public void RegisterPollHandler(string capName, PollServiceEventArgs pollServiceHandler) { // m_log.DebugFormat( // "[CAPS]: Registering handler with name {0}, url {1} for {2}", // capName, pollServiceHandler.Url, m_agentID, m_regionName); m_pollServiceHandlers.Add(capName, pollServiceHandler); m_httpListener.AddPollServiceHTTPHandler(pollServiceHandler.Url, pollServiceHandler); // uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port; // string protocol = "http"; // string hostName = m_httpListenerHostName; // // if (MainServer.Instance.UseSSL) // { // hostName = MainServer.Instance.SSLCommonName; // port = MainServer.Instance.SSLPort; // protocol = "https"; // } // RegisterHandler( // capName, String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, pollServiceHandler.Url)); } /// <summary> /// Register an external handler. The service for this capability is somewhere else /// given by the URL. /// </summary> /// <param name="capsName"></param> /// <param name="url"></param> public void RegisterHandler(string capsName, string url) { m_externalCapsHandlers.Add(capsName, url); } /// <summary> /// Remove all CAPS service handlers. /// </summary> public void DeregisterHandlers() { foreach (string capsName in m_capsHandlers.Caps) { m_capsHandlers.Remove(capsName); } foreach (PollServiceEventArgs handler in m_pollServiceHandlers.Values) { m_httpListener.RemovePollServiceHTTPHandler("", handler.Url); } } public bool TryGetPollHandler(string name, out PollServiceEventArgs pollHandler) { return m_pollServiceHandlers.TryGetValue(name, out pollHandler); } public Dictionary<string, PollServiceEventArgs> GetPollHandlers() { return new Dictionary<string, PollServiceEventArgs>(m_pollServiceHandlers); } /// <summary> /// Return an LLSD-serializable Hashtable describing the /// capabilities and their handler details. /// </summary> /// <param name="excludeSeed">If true, then exclude the seed cap.</param> public Hashtable GetCapsDetails(bool excludeSeed, List<string> requestedCaps) { Hashtable caps = CapsHandlers.GetCapsDetails(excludeSeed, requestedCaps); lock (m_pollServiceHandlers) { foreach (KeyValuePair <string, PollServiceEventArgs> kvp in m_pollServiceHandlers) { if (!requestedCaps.Contains(kvp.Key)) continue; string hostName = m_httpListenerHostName; uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port; string protocol = "http"; if (MainServer.Instance.UseSSL) { hostName = MainServer.Instance.SSLCommonName; port = MainServer.Instance.SSLPort; protocol = "https"; } // // caps.RegisterHandler("FetchInventoryDescendents2", String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, capUrl)); caps[kvp.Key] = string.Format("{0}://{1}:{2}{3}", protocol, hostName, port, kvp.Value.Url); } } // Add the external too foreach (KeyValuePair<string, string> kvp in ExternalCapsHandlers) { if (!requestedCaps.Contains(kvp.Key)) continue; caps[kvp.Key] = kvp.Value; } return caps; } public void Activate() { m_capsActive.Set(); } public bool WaitForActivation() { // Wait for 30s. If that elapses, return false and run without caps return m_capsActive.WaitOne(120000); } } }
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 NewEmployee.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; } } }
namespace Microsoft.Protocols.TestSuites.SharedAdapter { using System.Collections.Generic; /// <summary> /// Object Group data element /// </summary> public class ObjectGroupDataElementData : DataElementData { /// <summary> /// Initializes a new instance of the ObjectGroupDataElementData class. /// </summary> public ObjectGroupDataElementData() { this.ObjectGroupDeclarations = new ObjectGroupDeclarations(); // The ObjectMetadataDeclaration is only present for MOSS2013, so leave null for default value. this.ObjectMetadataDeclaration = null; // The DataElementHash is only present for MOSS2013, so leave null for default value. this.DataElementHash = null; this.ObjectGroupData = new ObjectGroupData(); } /// <summary> /// Gets or sets an optional data element hash for the object data group. /// </summary> public DataElementHash DataElementHash { get; set; } /// <summary> /// Gets or sets an optional array of object declarations that specifies the object. /// </summary> public ObjectGroupDeclarations ObjectGroupDeclarations { get; set; } /// <summary> /// Gets or sets an object metadata declaration. If no object metadata exists, this field must be omitted. /// </summary> public ObjectGroupMetadataDeclarations ObjectMetadataDeclaration { get; set; } /// <summary> /// Gets or sets an object group data. /// </summary> public ObjectGroupData ObjectGroupData { get; set; } /// <summary> /// Used to convert the element into a byte List. /// </summary> /// <returns>A Byte list</returns> public override List<byte> SerializeToByteList() { List<byte> result = new List<byte>(); if (this.DataElementHash != null) { result.AddRange(this.DataElementHash.SerializeToByteList()); } result.AddRange(this.ObjectGroupDeclarations.SerializeToByteList()); if (this.ObjectMetadataDeclaration != null) { result.AddRange(this.ObjectMetadataDeclaration.SerializeToByteList()); } result.AddRange(this.ObjectGroupData.SerializeToByteList()); return result; } /// <summary> /// Used to return the length of this element. /// </summary> /// <param name="byteArray">A Byte array</param> /// <param name="startIndex">Start position</param> /// <returns>The length of the element</returns> public override int DeserializeDataElementDataFromByteArray(byte[] byteArray, int startIndex) { int index = startIndex; DataElementHash dataElementHash; if (StreamObject.TryGetCurrent<DataElementHash>(byteArray, ref index, out dataElementHash)) { this.DataElementHash = dataElementHash; } this.ObjectGroupDeclarations = StreamObject.GetCurrent<ObjectGroupDeclarations>(byteArray, ref index); ObjectGroupMetadataDeclarations objectMetadataDeclaration = new ObjectGroupMetadataDeclarations(); if (StreamObject.TryGetCurrent<ObjectGroupMetadataDeclarations>(byteArray, ref index, out objectMetadataDeclaration)) { this.ObjectMetadataDeclaration = objectMetadataDeclaration; } this.ObjectGroupData = StreamObject.GetCurrent<ObjectGroupData>(byteArray, ref index); return index - startIndex; } /// <summary> /// The internal class for build a list of DataElement from an node object. /// </summary> public class Builder { /// <summary> /// This method is used to build a list of DataElement from an node object. /// </summary> /// <param name="node">Specify the node object.</param> /// <returns>Return the list of data elements build from the specified node object.</returns> public List<DataElement> Build(NodeObject node) { List<DataElement> dataElements = new List<DataElement>(); this.TravelNodeObject(node, ref dataElements); return dataElements; } /// <summary> /// This method is used to travel the node tree and build the ObjectGroupDataElementData and the extra data element list. /// </summary> /// <param name="node">Specify the object node.</param> /// <param name="dataElements">Specify the list of data elements.</param> private void TravelNodeObject(NodeObject node, ref List<DataElement> dataElements) { if (node is IntermediateNodeObject) { ObjectGroupDataElementData data = new ObjectGroupDataElementData(); data.ObjectGroupDeclarations.ObjectDeclarationList.Add(this.CreateObjectDeclare(node)); data.ObjectGroupData.ObjectGroupObjectDataList.Add(this.CreateObjectData(node as IntermediateNodeObject)); dataElements.Add(new DataElement(DataElementType.ObjectGroupDataElementData, data)); foreach (LeafNodeObject child in (node as IntermediateNodeObject).IntermediateNodeObjectList) { this.TravelNodeObject(child, ref dataElements); } } else if (node is LeafNodeObject) { LeafNodeObject intermediateNode = node as LeafNodeObject; ObjectGroupDataElementData data = new ObjectGroupDataElementData(); data.ObjectGroupDeclarations.ObjectDeclarationList.Add(this.CreateObjectDeclare(node)); data.ObjectGroupData.ObjectGroupObjectDataList.Add(this.CreateObjectData(intermediateNode)); if (intermediateNode.DataNodeObjectData != null) { data.ObjectGroupDeclarations.ObjectDeclarationList.Add(this.CreateObjectDeclare(intermediateNode.DataNodeObjectData)); data.ObjectGroupData.ObjectGroupObjectDataList.Add(this.CreateObjectData(intermediateNode.DataNodeObjectData)); dataElements.Add(new DataElement(DataElementType.ObjectGroupDataElementData, data)); return; } if (intermediateNode.DataNodeObjectData == null && intermediateNode.IntermediateNodeObjectList != null) { dataElements.Add(new DataElement(DataElementType.ObjectGroupDataElementData, data)); foreach (LeafNodeObject child in intermediateNode.IntermediateNodeObjectList) { this.TravelNodeObject(child, ref dataElements); } return; } throw new System.InvalidOperationException("The DataNodeObjectData and IntermediateNodeObjectList properties in LeafNodeObjectData type cannot be null in the same time."); } } /// <summary> /// This method is used to create ObjectGroupObjectDeclare instance from a node object. /// </summary> /// <param name="node">Specify the node object.</param> /// <returns>Return the ObjectGroupObjectDeclare instance.</returns> private ObjectGroupObjectDeclare CreateObjectDeclare(NodeObject node) { ObjectGroupObjectDeclare objectGroupObjectDeclare = new ObjectGroupObjectDeclare(); objectGroupObjectDeclare.ObjectExtendedGUID = node.ExGuid; objectGroupObjectDeclare.ObjectPartitionID = new Compact64bitInt(1u); objectGroupObjectDeclare.CellReferencesCount = new Compact64bitInt(0u); objectGroupObjectDeclare.ObjectReferencesCount = new Compact64bitInt(0u); objectGroupObjectDeclare.ObjectDataSize = new Compact64bitInt((ulong)node.GetContent().Count); return objectGroupObjectDeclare; } /// <summary> /// This method is used to create ObjectGroupObjectDeclare instance from a data node object. /// </summary> /// <param name="node">Specify the node object.</param> /// <returns>Return the ObjectGroupObjectDeclare instance.</returns> private ObjectGroupObjectDeclare CreateObjectDeclare(DataNodeObjectData node) { ObjectGroupObjectDeclare objectGroupObjectDeclare = new ObjectGroupObjectDeclare(); objectGroupObjectDeclare.ObjectExtendedGUID = node.ExGuid; objectGroupObjectDeclare.ObjectPartitionID = new Compact64bitInt(1u); objectGroupObjectDeclare.CellReferencesCount = new Compact64bitInt(0u); objectGroupObjectDeclare.ObjectReferencesCount = new Compact64bitInt(1u); objectGroupObjectDeclare.ObjectDataSize = new Compact64bitInt((ulong)node.ObjectData.LongLength); return objectGroupObjectDeclare; } /// <summary> /// This method is used to create ObjectGroupObjectData instance from a root node object. /// </summary> /// <param name="node">Specify the node object.</param> /// <returns>Return the ObjectGroupObjectData instance.</returns> private ObjectGroupObjectData CreateObjectData(IntermediateNodeObject node) { ObjectGroupObjectData objectData = new ObjectGroupObjectData(); objectData.CellIDArray = new CellIDArray(0u, null); List<ExGuid> extendedGuidList = new List<ExGuid>(); foreach (LeafNodeObject child in node.IntermediateNodeObjectList) { extendedGuidList.Add(child.ExGuid); } objectData.ObjectExGUIDArray = new ExGUIDArray(extendedGuidList); objectData.Data = new BinaryItem(node.SerializeToByteList()); return objectData; } /// <summary> /// This method is used to create ObjectGroupObjectData instance from a intermediate node object. /// </summary> /// <param name="node">Specify the node object.</param> /// <returns>Return the ObjectGroupObjectData instance.</returns> private ObjectGroupObjectData CreateObjectData(LeafNodeObject node) { ObjectGroupObjectData objectData = new ObjectGroupObjectData(); objectData.CellIDArray = new CellIDArray(0u, null); List<ExGuid> extendedGuidList = new List<ExGuid>(); if (node.DataNodeObjectData != null) { extendedGuidList.Add(node.DataNodeObjectData.ExGuid); } else if (node.IntermediateNodeObjectList != null) { foreach (LeafNodeObject child in node.IntermediateNodeObjectList) { extendedGuidList.Add(child.ExGuid); } } objectData.ObjectExGUIDArray = new ExGUIDArray(extendedGuidList); objectData.Data = new BinaryItem(node.SerializeToByteList()); return objectData; } /// <summary> /// This method is used to create ObjectGroupObjectData instance from a data node object. /// </summary> /// <param name="node">Specify the node object.</param> /// <returns>Return the ObjectGroupObjectData instance.</returns> private ObjectGroupObjectData CreateObjectData(DataNodeObjectData node) { ObjectGroupObjectData objectData = new ObjectGroupObjectData(); objectData.CellIDArray = new CellIDArray(0u, null); objectData.ObjectExGUIDArray = new ExGUIDArray(new List<ExGuid>()); objectData.Data = new BinaryItem(node.ObjectData); return objectData; } } } /// <summary> /// object declaration /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Easy to maintain one group of classes in one .cs file.")] public class ObjectGroupObjectDeclare : StreamObject { /// <summary> /// Initializes a new instance of the ObjectGroupObjectDeclare class. /// </summary> public ObjectGroupObjectDeclare() : base(StreamObjectTypeHeaderStart.ObjectGroupObjectDeclare) { this.ObjectExtendedGUID = new ExGuid(); this.ObjectPartitionID = new Compact64bitInt(); this.ObjectDataSize = new Compact64bitInt(); this.ObjectReferencesCount = new Compact64bitInt(); this.CellReferencesCount = new Compact64bitInt(); this.ObjectPartitionID.DecodedValue = 1; this.ObjectReferencesCount.DecodedValue = 1; this.CellReferencesCount.DecodedValue = 0; } /// <summary> /// Gets or sets an extended GUID that specifies the data element hash. /// </summary> public ExGuid ObjectExtendedGUID { get; set; } /// <summary> /// Gets or sets a compact unsigned 64-bit integer that specifies the partition. /// </summary> public Compact64bitInt ObjectPartitionID { get; set; } /// <summary> /// Gets or sets a compact unsigned 64-bit integer that specifies the size in bytes of the object.binary data opaque /// to this protocol for the declared object. /// This MUST match the size of the binary item in the corresponding object data for this object. /// </summary> public Compact64bitInt ObjectDataSize { get; set; } /// <summary> /// Gets or sets a compact unsigned 64-bit integer that specifies the number of object references. /// </summary> public Compact64bitInt ObjectReferencesCount { get; set; } /// <summary> /// Gets or sets a compact unsigned 64-bit integer that specifies the number of cell references. /// </summary> public Compact64bitInt CellReferencesCount { get; set; } /// <summary> /// Used to de-serialize the element. /// </summary> /// <param name="byteArray">A Byte array</param> /// <param name="currentIndex">Start position</param> /// <param name="lengthOfItems">The length of the items</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { int index = currentIndex; this.ObjectExtendedGUID = BasicObject.Parse<ExGuid>(byteArray, ref index); this.ObjectPartitionID = BasicObject.Parse<Compact64bitInt>(byteArray, ref index); this.ObjectDataSize = BasicObject.Parse<Compact64bitInt>(byteArray, ref index); this.ObjectReferencesCount = BasicObject.Parse<Compact64bitInt>(byteArray, ref index); this.CellReferencesCount = BasicObject.Parse<Compact64bitInt>(byteArray, ref index); if (index - currentIndex != lengthOfItems) { throw new StreamObjectParseErrorException(currentIndex, "ObjectGroupObjectDeclare", "Stream object over-parse error", null); } currentIndex = index; } /// <summary> /// Used to convert the element into a byte List. /// </summary> /// <param name="byteList">A Byte list</param> /// <returns>The number of the element</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { int itemsIndex = byteList.Count; byteList.AddRange(this.ObjectExtendedGUID.SerializeToByteList()); byteList.AddRange(this.ObjectPartitionID.SerializeToByteList()); byteList.AddRange(this.ObjectDataSize.SerializeToByteList()); byteList.AddRange(this.ObjectReferencesCount.SerializeToByteList()); byteList.AddRange(this.CellReferencesCount.SerializeToByteList()); return byteList.Count - itemsIndex; } } /// <summary> /// object data BLOB declaration /// </summary> public class ObjectGroupObjectBLOBDataDeclaration : StreamObject { /// <summary> /// Initializes a new instance of the ObjectGroupObjectBLOBDataDeclaration class. /// </summary> public ObjectGroupObjectBLOBDataDeclaration() : base(StreamObjectTypeHeaderStart.ObjectGroupObjectBLOBDataDeclaration) { this.ObjectExGUID = new ExGuid(); this.ObjectDataBLOBExGUID = new ExGuid(); this.ObjectPartitionID = new Compact64bitInt(); this.ObjectDataSize = new Compact64bitInt(); this.ObjectReferencesCount = new Compact64bitInt(); this.CellReferencesCount = new Compact64bitInt(); } /// <summary> /// Gets or sets an extended GUID that specifies the object. /// </summary> public ExGuid ObjectExGUID { get; set; } /// <summary> /// Gets or sets an extended GUID that specifies the object data BLOB. /// </summary> public ExGuid ObjectDataBLOBExGUID { get; set; } /// <summary> /// Gets or sets a compact unsigned 64-bit integer that specifies the partition. /// </summary> public Compact64bitInt ObjectPartitionID { get; set; } /// <summary> /// Gets or sets a compact unsigned 64-bit integer that specifies the size in bytes of the object.opaque binary data for the declared object. /// This MUST match the size of the binary item in the corresponding object data BLOB referenced by the Object Data BLOB reference for this object. /// </summary> public Compact64bitInt ObjectDataSize { get; set; } /// <summary> /// Gets or sets a compact unsigned 64-bit integer that specifies the number of object references. /// </summary> public Compact64bitInt ObjectReferencesCount { get; set; } /// <summary> /// Gets or sets a compact unsigned 64-bit integer that specifies the number of cell references. /// </summary> public Compact64bitInt CellReferencesCount { get; set; } /// <summary> /// Used to de-serialize the element. /// </summary> /// <param name="byteArray">A Byte array</param> /// <param name="currentIndex">Start position</param> /// <param name="lengthOfItems">The length of the items</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { int index = currentIndex; this.ObjectExGUID = BasicObject.Parse<ExGuid>(byteArray, ref index); this.ObjectDataBLOBExGUID = BasicObject.Parse<ExGuid>(byteArray, ref index); this.ObjectPartitionID = BasicObject.Parse<Compact64bitInt>(byteArray, ref index); this.ObjectReferencesCount = BasicObject.Parse<Compact64bitInt>(byteArray, ref index); this.CellReferencesCount = BasicObject.Parse<Compact64bitInt>(byteArray, ref index); if (index - currentIndex != lengthOfItems) { throw new StreamObjectParseErrorException(currentIndex, "ObjectGroupObjectBLOBDataDeclaration", "Stream object over-parse error", null); } currentIndex = index; } /// <summary> /// Used to convert the element into a byte List. /// </summary> /// <param name="byteList">A Byte list</param> /// <returns>The number of the element</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { int itemsIndex = byteList.Count; byteList.AddRange(this.ObjectExGUID.SerializeToByteList()); byteList.AddRange(this.ObjectDataBLOBExGUID.SerializeToByteList()); byteList.AddRange(this.ObjectPartitionID.SerializeToByteList()); byteList.AddRange(this.ObjectDataSize.SerializeToByteList()); byteList.AddRange(this.ObjectReferencesCount.SerializeToByteList()); byteList.AddRange(this.CellReferencesCount.SerializeToByteList()); return byteList.Count - itemsIndex; } } /// <summary> /// object data /// </summary> public partial class ObjectGroupObjectData : StreamObject { /// <summary> /// Initializes a new instance of the ObjectGroupObjectData class. /// </summary> public ObjectGroupObjectData() : base(StreamObjectTypeHeaderStart.ObjectGroupObjectData) { this.ObjectExGUIDArray = new ExGUIDArray(); this.CellIDArray = new CellIDArray(); this.Data = new BinaryItem(); } /// <summary> /// Gets or sets an extended GUID array that specifies the object group. /// </summary> public ExGUIDArray ObjectExGUIDArray { get; set; } /// <summary> /// Gets or sets a cell ID array that specifies the object group. /// </summary> public CellIDArray CellIDArray { get; set; } /// <summary> /// Gets or sets a byte stream that specifies the binary data which is opaque to this protocol. /// </summary> public BinaryItem Data { get; set; } /// <summary> /// Used to de-serialize the element. /// </summary> /// <param name="byteArray">A Byte array</param> /// <param name="currentIndex">Start position</param> /// <param name="lengthOfItems">The length of the items</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { int index = currentIndex; this.ObjectExGUIDArray = BasicObject.Parse<ExGUIDArray>(byteArray, ref index); this.CellIDArray = BasicObject.Parse<CellIDArray>(byteArray, ref index); this.Data = BasicObject.Parse<BinaryItem>(byteArray, ref index); if (index - currentIndex != lengthOfItems) { throw new StreamObjectParseErrorException(currentIndex, "ObjectGroupObjectData", "Stream object over-parse error", null); } currentIndex = index; } /// <summary> /// Used to convert the element into a byte List /// </summary> /// <param name="byteList">A Byte list</param> /// <returns>The number of the element</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { int itemsIndex = byteList.Count; byteList.AddRange(this.ObjectExGUIDArray.SerializeToByteList()); byteList.AddRange(this.CellIDArray.SerializeToByteList()); byteList.AddRange(this.Data.SerializeToByteList()); return byteList.Count - itemsIndex; } } /// <summary> /// object data BLOB reference /// </summary> public class ObjectGroupObjectDataBLOBReference : StreamObject { /// <summary> /// Initializes a new instance of the ObjectGroupObjectDataBLOBReference class. /// </summary> public ObjectGroupObjectDataBLOBReference() : base(StreamObjectTypeHeaderStart.ObjectGroupObjectDataBLOBReference) { this.ObjectExtendedGUIDArray = new ExGUIDArray(); this.CellIDArray = new CellIDArray(); this.BLOBExtendedGUID = new ExGuid(); } /// <summary> /// Gets or sets an extended GUID array that specifies the object references. /// </summary> public ExGUIDArray ObjectExtendedGUIDArray { get; set; } /// <summary> /// Gets or sets a cell ID array that specifies the cell references. /// </summary> public CellIDArray CellIDArray { get; set; } /// <summary> /// Gets or sets an extended GUID that specifies the object data BLOB. /// </summary> public ExGuid BLOBExtendedGUID { get; set; } /// <summary> /// Used to de-serialize the element. /// </summary> /// <param name="byteArray">A Byte array</param> /// <param name="currentIndex">Start position</param> /// <param name="lengthOfItems">The length of the items</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { int index = currentIndex; this.ObjectExtendedGUIDArray = BasicObject.Parse<ExGUIDArray>(byteArray, ref index); this.CellIDArray = BasicObject.Parse<CellIDArray>(byteArray, ref index); this.BLOBExtendedGUID = BasicObject.Parse<ExGuid>(byteArray, ref index); if (index - currentIndex != lengthOfItems) { throw new StreamObjectParseErrorException(currentIndex, "ObjectGroupObjectDataBLOBReference", "Stream object over-parse error", null); } currentIndex = index; } /// <summary> /// Used to convert the element into a byte List. /// </summary> /// <param name="byteList">A Byte list</param> /// <returns>The number of the elements</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { int itemsIndex = byteList.Count; byteList.AddRange(this.ObjectExtendedGUIDArray.SerializeToByteList()); byteList.AddRange(CellIDArray.SerializeToByteList()); byteList.AddRange(this.BLOBExtendedGUID.SerializeToByteList()); return byteList.Count - itemsIndex; } } /// <summary> /// Object Group Declarations /// </summary> public class ObjectGroupDeclarations : StreamObject { /// <summary> /// Initializes a new instance of the ObjectGroupDeclarations class. /// </summary> public ObjectGroupDeclarations() : base(StreamObjectTypeHeaderStart.ObjectGroupDeclarations) { this.ObjectDeclarationList = new List<ObjectGroupObjectDeclare>(); this.ObjectGroupObjectBLOBDataDeclarationList = new List<ObjectGroupObjectBLOBDataDeclaration>(); } /// <summary> /// Gets or sets a list of declarations that specifies the object. /// </summary> public List<ObjectGroupObjectDeclare> ObjectDeclarationList { get; set; } /// <summary> /// Gets or sets a list of object data BLOB declarations that specifies the object. /// </summary> public List<ObjectGroupObjectBLOBDataDeclaration> ObjectGroupObjectBLOBDataDeclarationList { get; set; } /// <summary> /// Used to de-serialize the element. /// </summary> /// <param name="byteArray">A Byte array</param> /// <param name="currentIndex">Start position</param> /// <param name="lengthOfItems">The length of the items</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { if (lengthOfItems != 0) { throw new StreamObjectParseErrorException(currentIndex, "ObjectGroupDeclarations", "Stream object over-parse error", null); } int index = currentIndex; int headerLength = 0; StreamObjectHeaderStart header; this.ObjectDeclarationList = new List<ObjectGroupObjectDeclare>(); this.ObjectGroupObjectBLOBDataDeclarationList = new List<ObjectGroupObjectBLOBDataDeclaration>(); while ((headerLength = StreamObjectHeaderStart.TryParse(byteArray, index, out header)) != 0) { if (header.Type == StreamObjectTypeHeaderStart.ObjectGroupObjectDeclare) { index += headerLength; this.ObjectDeclarationList.Add(StreamObject.ParseStreamObject(header, byteArray, ref index) as ObjectGroupObjectDeclare); } else if (header.Type == StreamObjectTypeHeaderStart.ObjectGroupObjectBLOBDataDeclaration) { index += headerLength; this.ObjectGroupObjectBLOBDataDeclarationList.Add(StreamObject.ParseStreamObject(header, byteArray, ref index) as ObjectGroupObjectBLOBDataDeclaration); } else { throw new StreamObjectParseErrorException(index, "ObjectGroupDeclarations", "Failed to parse ObjectGroupDeclarations, expect the inner object type either ObjectGroupObjectDeclare or ObjectGroupObjectBLOBDataDeclaration, but actual type value is " + header.Type, null); } } currentIndex = index; } /// <summary> /// Used to convert the element into a byte List /// </summary> /// <param name="byteList">The Byte list</param> /// <returns>A constant value 0</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { if (this.ObjectDeclarationList != null) { foreach (ObjectGroupObjectDeclare objectGroupObjectDeclare in this.ObjectDeclarationList) { byteList.AddRange(objectGroupObjectDeclare.SerializeToByteList()); } } if (this.ObjectGroupObjectBLOBDataDeclarationList != null) { foreach (ObjectGroupObjectBLOBDataDeclaration objectGroupObjectBLOBDataDeclaration in this.ObjectGroupObjectBLOBDataDeclarationList) { byteList.AddRange(objectGroupObjectBLOBDataDeclaration.SerializeToByteList()); } } return 0; } } /// <summary> /// Object Data /// </summary> public class ObjectGroupData : StreamObject { /// <summary> /// Initializes a new instance of the ObjectGroupData class. /// </summary> public ObjectGroupData() : base(StreamObjectTypeHeaderStart.ObjectGroupData) { this.ObjectGroupObjectDataList = new List<ObjectGroupObjectData>(); this.ObjectGroupObjectDataBLOBReferenceList = new List<ObjectGroupObjectDataBLOBReference>(); } /// <summary> /// Gets or sets a list of Object Data. /// </summary> public List<ObjectGroupObjectData> ObjectGroupObjectDataList { get; set; } /// <summary> /// Gets or sets a list of object data BLOB references that specifies the object. /// </summary> public List<ObjectGroupObjectDataBLOBReference> ObjectGroupObjectDataBLOBReferenceList { get; set; } /// <summary> /// Used to convert the element into a byte List /// </summary> /// <param name="byteList">A Byte list</param> /// <returns>A constant value 0</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { if (this.ObjectGroupObjectDataList != null) { foreach (ObjectGroupObjectData objectGroupObjectData in this.ObjectGroupObjectDataList) { byteList.AddRange(objectGroupObjectData.SerializeToByteList()); } } if (this.ObjectGroupObjectDataBLOBReferenceList != null) { foreach (ObjectGroupObjectDataBLOBReference objectGroupObjectDataBLOBReference in this.ObjectGroupObjectDataBLOBReferenceList) { byteList.AddRange(objectGroupObjectDataBLOBReference.SerializeToByteList()); } } return 0; } /// <summary> /// Used to de-serialize the element. /// </summary> /// <param name="byteArray">A Byte array</param> /// <param name="currentIndex">Start position</param> /// <param name="lengthOfItems">The length of the items</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { if (lengthOfItems != 0) { throw new StreamObjectParseErrorException(currentIndex, "ObjectGroupDeclarations", "Stream object over-parse error", null); } int index = currentIndex; int headerLength = 0; StreamObjectHeaderStart header; this.ObjectGroupObjectDataList = new List<ObjectGroupObjectData>(); this.ObjectGroupObjectDataBLOBReferenceList = new List<ObjectGroupObjectDataBLOBReference>(); while ((headerLength = StreamObjectHeaderStart.TryParse(byteArray, index, out header)) != 0) { if (header.Type == StreamObjectTypeHeaderStart.ObjectGroupObjectData) { index += headerLength; this.ObjectGroupObjectDataList.Add(StreamObject.ParseStreamObject(header, byteArray, ref index) as ObjectGroupObjectData); } else if (header.Type == StreamObjectTypeHeaderStart.ObjectGroupObjectDataBLOBReference) { index += headerLength; this.ObjectGroupObjectDataBLOBReferenceList.Add(StreamObject.ParseStreamObject(header, byteArray, ref index) as ObjectGroupObjectDataBLOBReference); } else { throw new StreamObjectParseErrorException(index, "ObjectGroupDeclarations", "Failed to parse ObjectGroupData, expect the inner object type either ObjectGroupObjectData or ObjectGroupObjectDataBLOBReference, but actual type value is " + header.Type, null); } } currentIndex = index; } } /// <summary> /// Object Metadata Declaration /// </summary> public class ObjectGroupMetadataDeclarations : StreamObject { /// <summary> /// Initializes a new instance of the ObjectGroupMetadataDeclarations class. /// </summary> public ObjectGroupMetadataDeclarations() : base(StreamObjectTypeHeaderStart.ObjectGroupMetadataDeclarations) { this.ObjectGroupMetadataList = new List<ObjectGroupMetadata>(); } /// <summary> /// Gets or sets a list of Object Metadata. /// </summary> public List<ObjectGroupMetadata> ObjectGroupMetadataList { get; set; } /// <summary> /// Used to convert the element into a byte List /// </summary> /// <param name="byteList">A Byte list</param> /// <returns>A constant value 0</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { if (this.ObjectGroupMetadataList != null) { foreach (ObjectGroupMetadata objectGroupMetadata in this.ObjectGroupMetadataList) { byteList.AddRange(objectGroupMetadata.SerializeToByteList()); } } return 0; } /// <summary> /// Used to de-serialize the element. /// </summary> /// <param name="byteArray">A Byte array</param> /// <param name="currentIndex">Start position</param> /// <param name="lengthOfItems">The length of the items</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { if (lengthOfItems != 0) { throw new StreamObjectParseErrorException(currentIndex, "ObjectGroupMetadataDeclarations", "Stream object over-parse error", null); } int index = currentIndex; int headerLength = 0; StreamObjectHeaderStart header; this.ObjectGroupMetadataList = new List<ObjectGroupMetadata>(); while ((headerLength = StreamObjectHeaderStart.TryParse(byteArray, index, out header)) != 0) { index += headerLength; if (header.Type == StreamObjectTypeHeaderStart.ObjectGroupMetadata) { this.ObjectGroupMetadataList.Add(StreamObject.ParseStreamObject(header, byteArray, ref index) as ObjectGroupMetadata); } else { throw new StreamObjectParseErrorException(index, "ObjectGroupDeclarations", "Failed to parse ObjectGroupMetadataDeclarations, expect the inner object type ObjectGroupMetadata, but actual type value is " + header.Type, null); } } currentIndex = index; } } /// <summary> /// Specifies an object group metadata. /// </summary> public class ObjectGroupMetadata : StreamObject { /// <summary> /// Initializes a new instance of the ObjectGroupMetadata class. /// </summary> public ObjectGroupMetadata() : base(StreamObjectTypeHeaderStart.ObjectGroupMetadata) { } /// <summary> /// Gets or sets a compact unsigned 64-bit integer that specifies the expected change frequency of the object. /// This value MUST be: /// 0, if the change frequency is not known. /// 1, if the object is known to change frequently. /// 2, if the object is known to change infrequently. /// 3, if the object is known to change independently of any other objects. /// </summary> public Compact64bitInt ObjectChangeFrequency { get; set; } /// <summary> /// Used to de-serialize the element. /// </summary> /// <param name="byteArray">A Byte array</param> /// <param name="currentIndex">Start position</param> /// <param name="lengthOfItems">The length of the items</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { int index = currentIndex; this.ObjectChangeFrequency = BasicObject.Parse<Compact64bitInt>(byteArray, ref index); if (index - currentIndex != lengthOfItems) { throw new StreamObjectParseErrorException(currentIndex, "ObjectGroupMetadata", "Stream object over-parse error", null); } currentIndex = index; } /// <summary> /// Used to convert the element into a byte List /// </summary> /// <param name="byteList">A Byte list</param> /// <returns>The number of elements actually contained in the list</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { List<byte> tmpList = this.ObjectChangeFrequency.SerializeToByteList(); byteList.AddRange(tmpList); return tmpList.Count; } } /// <summary> /// Specifies an data element hash stream object. /// </summary> public class DataElementHash : StreamObject { /// <summary> /// Initializes a new instance of the DataElementHash class. /// </summary> public DataElementHash() : base(StreamObjectTypeHeaderStart.DataElementHash) { } /// <summary> /// Gets or sets a compact unsigned 64-bit integer that specifies the hash schema. This value MUST be 1, indicating Content Information Data Structure Version 1.0. /// </summary> public Compact64bitInt DataElementHashScheme { get; set; } /// <summary> /// Gets or sets the data element hash data. /// </summary> public BinaryItem DataElementHashData { get; set; } /// <summary> /// Used to de-serialize the element. /// </summary> /// <param name="byteArray">A Byte array</param> /// <param name="currentIndex">Start position</param> /// <param name="lengthOfItems">The length of the items</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { int index = currentIndex; this.DataElementHashScheme = BasicObject.Parse<Compact64bitInt>(byteArray, ref index); this.DataElementHashData = BasicObject.Parse<BinaryItem>(byteArray, ref index); if (index - currentIndex != lengthOfItems) { throw new StreamObjectParseErrorException(currentIndex, "DataElementHash", "Stream object over-parse error", null); } currentIndex = index; } /// <summary> /// Used to convert the element into a byte List /// </summary> /// <param name="byteList">A Byte list</param> /// <returns>The number of elements actually contained in the list</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { int startPoint = byteList.Count; byteList.AddRange(this.DataElementHashScheme.SerializeToByteList()); byteList.AddRange(this.DataElementHashData.SerializeToByteList()); return byteList.Count - startPoint; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using Internal.Cryptography; using Internal.Cryptography.Pal; namespace System.Security.Cryptography.X509Certificates { public class X509Certificate : IDisposable { public X509Certificate() { } public X509Certificate(byte[] data) { if (data != null && data.Length != 0) // For compat reasons, this constructor treats passing a null or empty data set as the same as calling the nullary constructor. Pal = CertificatePal.FromBlob(data, null, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate(byte[] rawData, string password) : this(rawData, password, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullArray, nameof(rawData)); if ((keyStorageFlags & ~KeyStorageFlagsAll) != 0) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(keyStorageFlags)); Pal = CertificatePal.FromBlob(rawData, password, keyStorageFlags); } public X509Certificate(IntPtr handle) { Pal = CertificatePal.FromHandle(handle); } internal X509Certificate(ICertificatePal pal) { Debug.Assert(pal != null); Pal = pal; } public X509Certificate(string fileName) : this(fileName, null, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(string fileName, string password) : this(fileName, password, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); if ((keyStorageFlags & ~KeyStorageFlagsAll) != 0) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(keyStorageFlags)); Pal = CertificatePal.FromFile(fileName, password, keyStorageFlags); } public IntPtr Handle { get { if (Pal == null) return IntPtr.Zero; else return Pal.Handle; } } public string Issuer { get { ThrowIfInvalid(); string issuer = _lazyIssuer; if (issuer == null) issuer = _lazyIssuer = Pal.Issuer; return issuer; } } public string Subject { get { ThrowIfInvalid(); string subject = _lazySubject; if (subject == null) subject = _lazySubject = Pal.Subject; return subject; } } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { ICertificatePal pal = Pal; Pal = null; if (pal != null) pal.Dispose(); } } public override bool Equals(object obj) { X509Certificate other = obj as X509Certificate; if (other == null) return false; return Equals(other); } public virtual bool Equals(X509Certificate other) { if (other == null) return false; if (Pal == null) return other.Pal == null; if (!Issuer.Equals(other.Issuer)) return false; byte[] thisSerialNumber = GetRawSerialNumber(); byte[] otherSerialNumber = other.GetRawSerialNumber(); if (thisSerialNumber.Length != otherSerialNumber.Length) return false; for (int i = 0; i < thisSerialNumber.Length; i++) { if (thisSerialNumber[i] != otherSerialNumber[i]) return false; } return true; } public virtual byte[] Export(X509ContentType contentType) { return Export(contentType, null); } public virtual byte[] Export(X509ContentType contentType, string password) { if (!(contentType == X509ContentType.Cert || contentType == X509ContentType.SerializedCert || contentType == X509ContentType.Pkcs12)) throw new CryptographicException(SR.Cryptography_X509_InvalidContentType); if (Pal == null) throw new CryptographicException(ErrorCode.E_POINTER); // Not the greatest error, but needed for backward compat. using (IStorePal storePal = StorePal.FromCertificate(Pal)) { return storePal.Export(contentType, password); } } public virtual byte[] GetCertHash() { ThrowIfInvalid(); return GetRawCertHash().CloneByteArray(); } // Only use for internal purposes when the returned byte[] will not be mutated private byte[] GetRawCertHash() { return _lazyCertHash ?? (_lazyCertHash = Pal.Thumbprint); } public virtual string GetFormat() { return "X509"; } public override int GetHashCode() { if (Pal == null) return 0; byte[] thumbPrint = GetRawCertHash(); int value = 0; for (int i = 0; i < thumbPrint.Length && i < 4; ++i) { value = value << 8 | thumbPrint[i]; } return value; } public virtual string GetKeyAlgorithm() { ThrowIfInvalid(); string keyAlgorithm = _lazyKeyAlgorithm; if (keyAlgorithm == null) keyAlgorithm = _lazyKeyAlgorithm = Pal.KeyAlgorithm; return keyAlgorithm; } public virtual byte[] GetKeyAlgorithmParameters() { ThrowIfInvalid(); byte[] keyAlgorithmParameters = _lazyKeyAlgorithmParameters; if (keyAlgorithmParameters == null) keyAlgorithmParameters = _lazyKeyAlgorithmParameters = Pal.KeyAlgorithmParameters; return keyAlgorithmParameters.CloneByteArray(); } public virtual string GetKeyAlgorithmParametersString() { ThrowIfInvalid(); byte[] keyAlgorithmParameters = GetKeyAlgorithmParameters(); return keyAlgorithmParameters.ToHexStringUpper(); } public virtual byte[] GetPublicKey() { ThrowIfInvalid(); byte[] publicKey = _lazyPublicKey; if (publicKey == null) publicKey = _lazyPublicKey = Pal.PublicKeyValue; return publicKey.CloneByteArray(); } public virtual byte[] GetSerialNumber() { ThrowIfInvalid(); return GetRawSerialNumber().CloneByteArray(); } // Only use for internal purposes when the returned byte[] will not be mutated private byte[] GetRawSerialNumber() { return _lazySerialNumber ?? (_lazySerialNumber = Pal.SerialNumber); } public override string ToString() { return ToString(fVerbose: false); } public virtual string ToString(bool fVerbose) { if (fVerbose == false || Pal == null) return GetType().ToString(); StringBuilder sb = new StringBuilder(); // Subject sb.AppendLine("[Subject]"); sb.Append(" "); sb.AppendLine(Subject); // Issuer sb.AppendLine(); sb.AppendLine("[Issuer]"); sb.Append(" "); sb.AppendLine(Issuer); // Serial Number sb.AppendLine(); sb.AppendLine("[Serial Number]"); sb.Append(" "); byte[] serialNumber = GetSerialNumber(); Array.Reverse(serialNumber); sb.Append(serialNumber.ToHexArrayUpper()); sb.AppendLine(); // NotBefore sb.AppendLine(); sb.AppendLine("[Not Before]"); sb.Append(" "); sb.AppendLine(FormatDate(GetNotBefore())); // NotAfter sb.AppendLine(); sb.AppendLine("[Not After]"); sb.Append(" "); sb.AppendLine(FormatDate(GetNotAfter())); // Thumbprint sb.AppendLine(); sb.AppendLine("[Thumbprint]"); sb.Append(" "); sb.Append(GetRawCertHash().ToHexArrayUpper()); sb.AppendLine(); return sb.ToString(); } internal ICertificatePal Pal { get; private set; } internal DateTime GetNotAfter() { ThrowIfInvalid(); DateTime notAfter = _lazyNotAfter; if (notAfter == DateTime.MinValue) notAfter = _lazyNotAfter = Pal.NotAfter; return notAfter; } internal DateTime GetNotBefore() { ThrowIfInvalid(); DateTime notBefore = _lazyNotBefore; if (notBefore == DateTime.MinValue) notBefore = _lazyNotBefore = Pal.NotBefore; return notBefore; } internal void ThrowIfInvalid() { if (Pal == null) throw new CryptographicException(SR.Format(SR.Cryptography_InvalidHandle, "m_safeCertContext")); // Keeping "m_safeCertContext" string for backward compat sake. } /// <summary> /// Convert a date to a string. /// /// Some cultures, specifically using the Um-AlQura calendar cannot convert dates far into /// the future into strings. If the expiration date of an X.509 certificate is beyond the range /// of one of these these cases, we need to fall back to a calendar which can express the dates /// </summary> internal static string FormatDate(DateTime date) { CultureInfo culture = CultureInfo.CurrentCulture; if (!culture.DateTimeFormat.Calendar.IsValidDay(date.Year, date.Month, date.Day, 0)) { // The most common case of culture failing to work is in the Um-AlQuara calendar. In this case, // we can fall back to the Hijri calendar, otherwise fall back to the invariant culture. if (culture.DateTimeFormat.Calendar is UmAlQuraCalendar) { culture = culture.Clone() as CultureInfo; culture.DateTimeFormat.Calendar = new HijriCalendar(); } else { culture = CultureInfo.InvariantCulture; } } return date.ToString(culture); } private volatile byte[] _lazyCertHash; private volatile string _lazyIssuer; private volatile string _lazySubject; private volatile byte[] _lazySerialNumber; private volatile string _lazyKeyAlgorithm; private volatile byte[] _lazyKeyAlgorithmParameters; private volatile byte[] _lazyPublicKey; private DateTime _lazyNotBefore = DateTime.MinValue; private DateTime _lazyNotAfter = DateTime.MinValue; private const X509KeyStorageFlags KeyStorageFlagsAll = (X509KeyStorageFlags)0x1f; } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.IO; using gView.Framework.Data; using gView.Framework.Geometry; using gView.Framework.IO; using System.Reflection; using System.Runtime.InteropServices; using gView.Framework.system; using System.Xml; namespace gView.DataSources.Fdb.MSSql { public class SqlFDBImageCatalogClass : IRasterCatalogClass, IParentRasterLayer, IFileSystemDependent, IFileWatchingDirectories, IRefreshable, IPointIdentify, IMulitPointIdentify, IGridClass, IMultiGridIdentify, IPersistable { internal enum ImageSpaceType { Database, FileSystem, Invalid } private IPolygon _polygon = null; internal ISpatialReference _sRef = null; private InterpolationMethod _interpolation = InterpolationMethod.Fast; internal IFeatureClass _fc; public SqlFDB _fdb; internal string _dsname = "", _imageSpace = ""; internal ImageSpaceType _imageSpaceType = ImageSpaceType.Database; internal IRasterDataset _dataset = null; internal PlugInManager _compMan = new PlugInManager(); public IRasterClass RasterClass { get { return null; } } internal SqlFDBImageCatalogClass() { } public SqlFDBImageCatalogClass(IRasterDataset dataset, SqlFDB fdb, IFeatureClass polygonsFC, ISpatialReference sRef, string imageSpace) { _dataset = dataset; _dsname = dataset.DatasetName; _fdb = fdb; _fc = polygonsFC; calcPolygon(polygonsFC.Envelope); _sRef = sRef; _imageSpace = (imageSpace == null) ? "" : imageSpace; if (_imageSpace != "" && imageSpace.ToLower() != "database") { try { DirectoryInfo di = new DirectoryInfo(_imageSpace); if (di.Exists) _imageSpaceType = ImageSpaceType.FileSystem; else _imageSpaceType = ImageSpaceType.Invalid; } catch { _imageSpaceType = ImageSpaceType.Invalid; } } } private void calcPolygon(IEnvelope env) { if (env == null) return; _polygon = new Polygon(); Ring ring = new Ring(); ring.AddPoint(new Point(env.minx, env.miny)); ring.AddPoint(new Point(env.maxx, env.miny)); ring.AddPoint(new Point(env.maxx, env.maxy)); ring.AddPoint(new Point(env.minx, env.maxy)); _polygon.AddRing(ring); } public ICursor ImageList { get { try { if (_fc == null) return null; QueryFilter filter = new QueryFilter(); filter.AddField("PATH"); filter.AddField("LAST_MODIFIED"); filter.AddField("PATH2"); filter.AddField("LAST_MODIFIED2"); filter.AddField("MANAGED"); return _fc.Search(filter); } catch { return null; } } } public IFeature this[string filename] { get { IFeatureCursor cursor = null; try { if (_fc == null) return null; QueryFilter filter = new QueryFilter(); filter.AddField("*"); filter.WhereClause = "PATH='" + filename + "'"; cursor = _fc.Search(filter) as IFeatureCursor; if (cursor == null) return null; return cursor.NextFeature; } catch { return null; } finally { if (cursor != null) cursor.Dispose(); } } } #region IRasterClass Members public gView.Framework.Geometry.IPolygon Polygon { get { return _polygon; } } public void BeginPaint(gView.Framework.Carto.IDisplay display, ICancelTracker cancelTracker) { } public void EndPaint(ICancelTracker cancelTracker) { } public System.Drawing.Color GetPixel(double X, double Y) { return System.Drawing.Color.Transparent; } public System.Drawing.Bitmap Bitmap { get { return null; } } public double oX { get { return 0.0; } } public double oY { get { return 0.0; } } public double dx1 { get { return 0.0; } } public double dx2 { get { return 0.0; } } public double dy1 { get { return 0.0; } } public double dy2 { get { return 0.0; } } public gView.Framework.Geometry.ISpatialReference SpatialReference { get { return _sRef; } set { _sRef = value; } } public IRasterDataset Dataset { get { return _dataset; } } #endregion #region IParentLayer Members public InterpolationMethod InterpolationMethod { get { return _interpolation; } set { _interpolation = value; } } public IRasterLayerCursor ChildLayers(gView.Framework.Carto.IDisplay display, string filterClause) { if (_fc == null || display == null || _fdb == null) return new SimpleRasterlayerCursor(new List<IRasterLayer>()); double dpm = Math.Max(display.GraphicsContext.DpiX, display.GraphicsContext.DpiY) / 0.0254; double pix = display.mapScale / dpm;/*display.dpm;*/ // [m] IEnvelope dispEnvelope = display.DisplayTransformation.TransformedBounds(display); //display.Envelope; if (display.GeometricTransformer != null) { dispEnvelope = (IEnvelope)((IGeometry)display.GeometricTransformer.InvTransform2D(dispEnvelope)).Envelope; } SpatialFilter filter = new SpatialFilter(); filter.Geometry = dispEnvelope; filter.SubFields = "*"; filter.WhereClause = filterClause; filter.SpatialRelation = spatialRelation.SpatialRelationIntersects; return new RasterLayerCursor(this, _fc.Search(filter) as IFeatureCursor, dispEnvelope, pix); } #endregion #region IFileSystemDependent Members public bool FileChanged(string filename) { return false; } public bool FileDeleted(string filename) { return false; } #endregion #region IFileWatchingDirectories Members private List<String> _directories = new List<string>(); public List<DirectoryInfo> Directories { get { List<DirectoryInfo> dis = new List<DirectoryInfo>(); foreach (string directory in _directories) { try { DirectoryInfo di = new DirectoryInfo(directory); dis.Add(di); } catch { } } return dis; } } public void AddDirectory(DirectoryInfo di) { if (_directories.Contains(di.FullName.ToLower())) return; _directories.Add(di.FullName.ToLower()); } public void RemoveDirectory(DirectoryInfo di) { if (!_directories.Contains(di.FullName.ToLower())) return; _directories.Remove(di.FullName.ToLower()); } #endregion #region IClass Member public string Name { get { return _dsname; } } public string Aliasname { get { return _dsname; } } IDataset IClass.Dataset { get { return _dataset; } } #endregion #region IFeatureClass Member public string ShapeFieldName { get { if (_fc == null) return ""; return _fc.ShapeFieldName; } } public IEnvelope Envelope { get { if (_fc == null) return null; return _fc.Envelope; } } public int CountFeatures { get { if (_fc == null) return 0; return _fc.CountFeatures; } } public IFeatureCursor GetFeatures(IQueryFilter filter) { if (_fc == null) return null; return _fc.GetFeatures(filter); } #endregion #region ITableClass Member public ICursor Search(IQueryFilter filter) { if (_fc == null) return null; return _fc.Search(filter); } public ISelectionSet Select(IQueryFilter filter) { if (_fc == null) return null; return _fc.Select(filter); } public IFields Fields { get { if (_fc == null) return null; return _fc.Fields; } } public IField FindField(string name) { if (_fc == null) return null; return _fc.FindField(name); } public string IDFieldName { get { if (_fc == null) return ""; return _fc.IDFieldName; } } #endregion #region IGeometryDef Member public bool HasZ { get { if (_fc == null) return false; return _fc.HasZ; ; } } public bool HasM { get { if (_fc == null) return false; return _fc.HasM; } } public geometryType GeometryType { get { if (_fc == null) return geometryType.Unknown; return _fc.GeometryType; } } //public GeometryFieldType GeometryFieldType //{ // get // { // if (_fc == null) return GeometryFieldType.Default; // return _fc.GeometryFieldType; // } //} #endregion #region IRefreshable Member public void RefreshFrom(object obj) { if (!(obj is SqlFDBImageCatalogClass)) return; SqlFDBImageCatalogClass ic = (SqlFDBImageCatalogClass)obj; if (ic.Name != this.Name) return; _polygon = ic._polygon.Clone() as IPolygon; if (_fc is IRefreshable) ((IRefreshable)_fc).RefreshFrom(ic._fc); } #endregion #region IPointIdentify Member public ICursor PointQuery(gView.Framework.Carto.IDisplay display, IPoint point, ISpatialReference sRef, IUserData userdata) { PointCollection pColl = new PointCollection(); pColl.AddPoint(point); return MultiPointQuery(display, pColl, sRef, userdata); } #endregion #region IMulitPointIdentify Member public ICursor MultiPointQuery(gView.Framework.Carto.IDisplay dispaly, IPointCollection points, ISpatialReference sRef, IUserData userdata) { IMultiPoint mPoint = new MultiPoint(points); List<IRasterLayer> layers = QueryChildLayers(mPoint, String.Empty); if (layers == null || layers.Count == 0) return null; List<IRow> cursorRows = new List<IRow>(); for (int i = 0; i < mPoint.PointCount; i++) { IPoint point = mPoint[i]; foreach (IRasterLayer layer in layers) { if (layer == null || !(layer.Class is IRasterClass) || !(layer.Class is IPointIdentify)) continue; if (gView.Framework.SpatialAlgorithms.Algorithm.Jordan( ((IRasterClass)layer.Class).Polygon, point.X, point.Y)) { using (ICursor cursor = ((IPointIdentify)layer.Class).PointQuery(dispaly, point, sRef, userdata)) { if (cursor is IRowCursor) { IRow row; while ((row = ((IRowCursor)cursor).NextRow) != null) { row.Fields.Add(new FieldValue("x", point.X)); row.Fields.Add(new FieldValue("y", point.Y)); cursorRows.Add(row); } } } } } } return new SimpleRowCursor(cursorRows); } #endregion #region IMultiGridIdentify public float[] MultiGridQuery(gView.Framework.Carto.IDisplay display, IPoint[] Points, double dx, double dy, ISpatialReference sRef, IUserData userdata) { if (Points == null || Points.Length != 3) return null; PointCollection pColl = new PointCollection(); pColl.AddPoint(Points[0]); pColl.AddPoint(Points[1]); pColl.AddPoint(Points[2]); double d1x = Points[1].X - Points[0].X, d1y = Points[1].Y - Points[0].Y; double d2x = Points[2].X - Points[0].X, d2y = Points[2].Y - Points[0].Y; double len1 = Math.Sqrt(d1x * d1x + d1y * d1y); double len2 = Math.Sqrt(d2x * d2x + d2y * d2y); int stepX = (int)Math.Round(len1 / dx); int stepY = (int)Math.Round(len2 / dy); d1x /= stepX; d1y /= stepX; d2x /= stepY; d2y /= stepY; List<float> vals = new List<float>(); vals.Add((float)(stepX + 1)); vals.Add((float)(stepY + 1)); List<IRasterLayer> layers = QueryChildLayers(pColl.Envelope, String.Empty); try { for (int y = 0; y <= stepY; y++) { for (int x = 0; x <= stepX; x++) { Point p = new Point(Points[0].X + d1x * x + d2x * y, Points[0].Y + d1y * x + d2y * y); bool found = false; foreach (IRasterLayer layer in layers) { if (layer == null || !(layer.Class is IRasterClass) || !(layer.Class is IGridIdentify)) continue; if (gView.Framework.SpatialAlgorithms.Algorithm.Jordan(((IRasterClass)layer.Class).Polygon, p.X, p.Y)) { ((IGridIdentify)layer.Class).InitGridQuery(); float val = ((IGridIdentify)layer.Class).GridQuery(display, p, sRef); vals.Add(val); found = true; break; } } if (!found) vals.Add(float.MinValue); } } } finally { foreach (IRasterLayer layer in layers) { if (layer.Class is IGridIdentify) ((IGridIdentify)layer.Class).ReleaseGridQuery(); } } return vals.ToArray(); } #endregion #region IGridClass Member private GridColorClass[] _colorClasses = null; private bool _useHillShade = true; private double[] _hillShadeVector = new double[] { -1.0, 1.0, 1.0 }; private bool _useNoDataValue = false; private double _noDataValue = 0.0; public GridRenderMethode ImplementsRenderMethods { get { return GridRenderMethode.Colors | GridRenderMethode.HillShade | GridRenderMethode.NullValue; } } public GridColorClass[] ColorClasses { get { return _colorClasses; } set { _colorClasses = value; } } public bool UseHillShade { get { return _useHillShade; } set { _useHillShade = value; } } public double[] HillShadeVector { get { return _hillShadeVector; } set { if (value != null && value.Length == 3) _hillShadeVector = value; } } public double MinValue { get { return -1000.0; } } public double MaxValue { get { return 1000.0; } } public double IgnoreDataValue { get { return _noDataValue; } set { _noDataValue = value; } } public bool UseIgnoreDataValue { get { return _useNoDataValue; } set { _useNoDataValue = value; } } bool _renderRawGridValues = false; public bool RenderRawGridValues { get { return _renderRawGridValues; } set { _renderRawGridValues = value; } } #endregion public List<IRasterLayer> QueryChildLayers(IGeometry geometry, string filterClause) { List<IRasterLayer> childlayers = new List<IRasterLayer>(); if (_fc == null || _fdb == null) return childlayers; SpatialFilter filter = new SpatialFilter(); filter.Geometry = geometry; filter.SubFields = "*"; filter.WhereClause = filterClause; filter.SpatialRelation = spatialRelation.SpatialRelationIntersects; using (IRasterLayerCursor cursor = new RasterLayerCursor( this, _fc.Search(filter) as IFeatureCursor)) { IRasterLayer layer; while ((layer = cursor.NextRasterLayer) != null) { childlayers.Add(layer); } } return childlayers; } #region IPersistable Member public void Load(IPersistStream stream) { _colorClasses = null; List<GridColorClass> classes = new List<GridColorClass>(); GridColorClass cc; while ((cc = (GridColorClass)stream.Load("GridClass", null, new GridColorClass(0, 0, System.Drawing.Color.White))) != null) { classes.Add(cc); } if (classes.Count > 0) _colorClasses = classes.ToArray(); _useHillShade = (bool)stream.Load("UseHillShade", true); _hillShadeVector[0] = (double)stream.Load("HillShadeDx", 0.0); _hillShadeVector[1] = (double)stream.Load("HillShadeDy", 0.0); _hillShadeVector[2] = (double)stream.Load("HillShadeDz", 0.0); _useNoDataValue = (bool)stream.Load("UseIgnoreData", 0); _noDataValue = (double)stream.Load("IgnoreData", 0.0); _renderRawGridValues = (bool)stream.Load("RenderRawGridValues", false); } public void Save(IPersistStream stream) { if (_colorClasses != null) { foreach (GridColorClass cc in _colorClasses) { stream.Save("GridClass", cc); } } stream.Save("UseHillShade", _useHillShade); stream.Save("HillShadeDx", _hillShadeVector[0]); stream.Save("HillShadeDy", _hillShadeVector[1]); stream.Save("HillShadeDz", _hillShadeVector[2]); stream.Save("UseIgnoreData", _useNoDataValue); stream.Save("IgnoreData", _noDataValue); stream.Save("RenderRawGridValues", _renderRawGridValues); } #endregion } internal class RasterLayerCursor : IRasterLayerCursor { private IFeatureCursor _cursor; private SqlFDBImageCatalogClass _layer; private IEnvelope _dispEnvelope = null; private double _pix = 1.0; public RasterLayerCursor(SqlFDBImageCatalogClass layer, IFeatureCursor cursor) { _layer = layer; _cursor = cursor; } public RasterLayerCursor(SqlFDBImageCatalogClass layer, IFeatureCursor cursor, IEnvelope dispEnvelope, double pix) : this(layer, cursor) { _dispEnvelope = dispEnvelope; _pix = pix; } #region IRasterLayerCursor Member public IRasterLayer NextRasterLayer { get { if (_cursor == null || _layer == null) return null; try { while (true) { IFeature feature = _cursor.NextFeature; if (feature == null) return null; IRasterLayer rLayer = null; double cell = Math.Max((double)feature["CELLX"], (double)feature["CELLY"]); int levels = (int)feature["LEVELS"], level = 0; if ((bool)feature["MANAGED"] && _layer._imageSpaceType == SqlFDBImageCatalogClass.ImageSpaceType.Database) { for (int l = 0; l < levels; l++) { if (cell * Math.Pow(2, l) < _pix) { level = l + 1; } else { break; } } if (level == 0 && levels > 0) level = 1; DataTable tab = _layer._fdb.Select("ID,SHAPE", _layer._dsname + "_IMAGE_DATA", "IMAGE_ID=" + feature.OID + " AND LEV=" + level); if (tab == null) continue; foreach (DataRow row in tab.Rows) { byte[] obj = (byte[])row["SHAPE"]; BinaryReader r = new BinaryReader(new MemoryStream()); r.BaseStream.Write((byte[])obj, 0, ((byte[])obj).Length); r.BaseStream.Position = 0; Polygon polygon = new Polygon(); polygon.Deserialize(r, new GeometryDef(geometryType.Polygon, null, true)); r.Close(); if (gView.Framework.SpatialAlgorithms.Algorithm.IntersectBox(polygon, _dispEnvelope)) { SqlFDBImageDatasetImageClass rClass = new SqlFDBImageDatasetImageClass(_layer._fdb, _layer._dsname, (int)row["ID"], polygon); rLayer = new RasterLayer(rClass); rLayer.InterpolationMethod = _layer.InterpolationMethod; if (rClass.SpatialReference == null) rClass.SpatialReference = _layer._sRef; } } } else if ((bool)feature["MANAGED"] && _layer._imageSpaceType == SqlFDBImageCatalogClass.ImageSpaceType.FileSystem) { gView.DataSources.Raster.File.PyramidFileClass rasterClass = new gView.DataSources.Raster.File.PyramidFileClass(_layer._dataset, _layer._imageSpace + @"\" + (string)feature["MANAGED_FILE"], feature.Shape as IPolygon); if (rasterClass.isValid) { rLayer = LayerFactory.Create(rasterClass) as IRasterLayer; if (rLayer != null) { rLayer.InterpolationMethod = _layer.InterpolationMethod; if (rasterClass.SpatialReference == null) rasterClass.SpatialReference = _layer._sRef; } } } else if (!(bool)feature["MANAGED"]) { if (feature["RF_PROVIDER"] == null || feature["RF_PROVIDER"] == DBNull.Value) { gView.DataSources.Raster.File.RasterFileDataset rDataset = new gView.DataSources.Raster.File.RasterFileDataset(); rLayer = rDataset.AddRasterFile((string)feature["PATH"], feature.Shape as IPolygon); } else { IRasterFileDataset rDataset = _layer._compMan.CreateInstance(new Guid(feature["RF_PROVIDER"].ToString())) as IRasterFileDataset; if (rDataset == null) continue; rLayer = rDataset.AddRasterFile((string)feature["PATH"], feature.Shape as IPolygon); } if (rLayer != null && rLayer.RasterClass != null) { rLayer.InterpolationMethod = _layer.InterpolationMethod; if (rLayer.RasterClass.SpatialReference == null) rLayer.RasterClass.SpatialReference = _layer._sRef; } } if (rLayer != null) { if (rLayer.Class is IGridClass) { IGridClass gridClass = (IGridClass)rLayer.Class; gridClass.ColorClasses = _layer.ColorClasses; gridClass.UseHillShade = _layer.UseHillShade; gridClass.HillShadeVector = _layer.HillShadeVector; gridClass.UseIgnoreDataValue = _layer.UseIgnoreDataValue; gridClass.IgnoreDataValue = _layer.IgnoreDataValue; gridClass.RenderRawGridValues = _layer.RenderRawGridValues; } return rLayer; } } } catch { } return null; } } #endregion #region IDisposable Member public void Dispose() { if (_cursor != null) _cursor.Dispose(); _cursor = null; } #endregion } internal class SqlFDBImageDatasetImageClass : IRasterClass { SqlFDB _fdb; private int _ID; private Polygon _polygon; private ISpatialReference _sRef = null; private string _dsname = ""; private double _X, _Y; private double _dx_X, _dx_Y, _dy_X, _dy_Y; int _iWidth, _iHeight; public SqlFDBImageDatasetImageClass(SqlFDB fdb, string dsname, int ID, Polygon polygon) { _fdb = fdb; _ID = ID; _polygon = polygon; _dsname = dsname; } #region IRasterLayer Members public IPolygon Polygon { get { return _polygon; } } System.Drawing.Bitmap _bm = null; public void BeginPaint(gView.Framework.Carto.IDisplay display, ICancelTracker cancelTracker) { if (_fdb == null) return; try { DataTable tab = _fdb._conn.Select("IMAGE,X,Y,dx1,dx2,dy1,dy2", _dsname + "_IMAGE_DATA", "ID=" + _ID); if (tab == null) return; if (tab.Rows.Count != 1) return; DataRow row = tab.Rows[0]; _bm = (System.Drawing.Bitmap)ImageFast.FromStream((byte[])row["IMG"]); _X = (double)tab.Rows[0]["X"]; _Y = (double)tab.Rows[0]["Y"]; _dx_X = (double)tab.Rows[0]["dx1"]; _dx_Y = (double)tab.Rows[0]["dx2"]; _dy_X = (double)tab.Rows[0]["dy1"]; _dy_Y = (double)tab.Rows[0]["dy2"]; _iWidth = _bm.Width; _iHeight = _bm.Height; } catch { EndPaint(cancelTracker); } } public void EndPaint(ICancelTracker cancelTracker) { if (_bm != null) { _bm.Dispose(); _bm = null; } } public System.Drawing.Color GetPixel(double X, double Y) { return System.Drawing.Color.Transparent; } public System.Drawing.Bitmap Bitmap { get { return _bm; } } public double oX { get { return _X; } } public double oY { get { return _Y; } } public double dx1 { get { return _dx_X; } } public double dx2 { get { return _dx_Y; } } public double dy1 { get { return _dy_X; } } public double dy2 { get { return _dy_Y; } } public ISpatialReference SpatialReference { get { return _sRef; } set { _sRef = value; } } InterpolationMethod _interpolation = InterpolationMethod.Fast; public InterpolationMethod InterpolationMethod { get { return _interpolation; } set { _interpolation = value; } } public IRasterDataset Dataset { get { return null; } } #endregion #region IClass Member public string Name { get { return "image"; } } public string Aliasname { get { return Name; } } IDataset IClass.Dataset { get { return null; } } #endregion } internal class ImageFast { [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] private static extern int GdipLoadImageFromFile(string filename, out IntPtr image); [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] private static extern int GdipLoadImageFromStream(UCOMIStream istream, out IntPtr image); [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] private static extern int GdiplusStartup(out IntPtr token, ref StartupInput input, out StartupOutput output); [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] private static extern int GdiplusShutdown(IntPtr token); [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] private static extern int GdipGetImageType(IntPtr image, out GdipImageTypeEnum type); [DllImport("ole32.dll")] static extern int CreateStreamOnHGlobal(IntPtr hGlobal, bool fDeleteOnRelease, out UCOMIStream ppstm); private static IntPtr gdipToken = IntPtr.Zero; static ImageFast() { #if DEBUG //Console.WriteLine("Initializing GDI+"); #endif if (gdipToken == IntPtr.Zero) { StartupInput input = StartupInput.GetDefaultStartupInput(); StartupOutput output; int status = GdiplusStartup(out gdipToken, ref input, out output); #if DEBUG //if (status == 0) // Console.WriteLine("Initializing GDI+ completed successfully"); #endif if (status == 0) AppDomain.CurrentDomain.ProcessExit += new EventHandler(Cleanup_Gdiplus); } } private static void Cleanup_Gdiplus(object sender, EventArgs e) { #if DEBUG //Console.WriteLine("GDI+ shutdown entered through ProcessExit event"); #endif if (gdipToken != IntPtr.Zero) GdiplusShutdown(gdipToken); #if DEBUG //Console.WriteLine("GDI+ shutdown completed"); #endif } private static Type bmpType = typeof(System.Drawing.Bitmap); private static Type emfType = typeof(System.Drawing.Imaging.Metafile); public static System.Drawing.Image FromFile(string filename) { filename = System.IO.Path.GetFullPath(filename); IntPtr loadingImage = IntPtr.Zero; // We are not using ICM at all, fudge that, this should be FAAAAAST! if (GdipLoadImageFromFile(filename, out loadingImage) != 0) { throw new Exception("GDI+ threw a status error code."); } GdipImageTypeEnum imageType; if (GdipGetImageType(loadingImage, out imageType) != 0) { throw new Exception("GDI+ couldn't get the image type"); } switch (imageType) { case GdipImageTypeEnum.Bitmap: return (System.Drawing.Bitmap)bmpType.InvokeMember("FromGDIplus", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new object[] { loadingImage }); case GdipImageTypeEnum.Metafile: return (System.Drawing.Imaging.Metafile)emfType.InvokeMember("FromGDIplus", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new object[] { loadingImage }); } throw new Exception("Couldn't convert underlying GDI+ object to managed object"); } public static System.Drawing.Image FromStream(byte[] b) { IntPtr loadingImage = IntPtr.Zero; IntPtr nativePtr = Marshal.AllocHGlobal(b.Length); // copy byte array to native heap Marshal.Copy(b, 0, nativePtr, b.Length); // Create a UCOMIStream from the allocated memory UCOMIStream comStream; CreateStreamOnHGlobal(nativePtr, true, out comStream); // We are not using ICM at all, fudge that, this should be FAAAAAST! if (GdipLoadImageFromStream(comStream, out loadingImage) != 0) { //Marshal.FreeHGlobal(nativePtr); throw new Exception("GDI+ threw a status error code."); } //Marshal.FreeHGlobal(nativePtr); GdipImageTypeEnum imageType; if (GdipGetImageType(loadingImage, out imageType) != 0) { throw new Exception("GDI+ couldn't get the image type"); } switch (imageType) { case GdipImageTypeEnum.Bitmap: return (System.Drawing.Bitmap)bmpType.InvokeMember("FromGDIplus", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new object[] { loadingImage }); case GdipImageTypeEnum.Metafile: return (System.Drawing.Imaging.Metafile)emfType.InvokeMember("FromGDIplus", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new object[] { loadingImage }); } throw new Exception("Couldn't convert underlying GDI+ object to managed object"); } private ImageFast() { } } [StructLayout(LayoutKind.Sequential)] internal struct StartupInput { public int GdiplusVersion; public IntPtr DebugEventCallback; public bool SuppressBackgroundThread; public bool SuppressExternalCodecs; public static StartupInput GetDefaultStartupInput() { StartupInput result = new StartupInput(); result.GdiplusVersion = 1; result.SuppressBackgroundThread = false; result.SuppressExternalCodecs = false; return result; } } [StructLayout(LayoutKind.Sequential)] internal struct StartupOutput { public IntPtr Hook; public IntPtr Unhook; } internal enum GdipImageTypeEnum { Unknown = 0, Bitmap = 1, Metafile = 2 } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Reflection; using Aurora.Framework; using OpenSim.Region.Framework.Scenes; namespace Aurora.Modules.Terrain.FileLoaders { /// <summary> /// A virtual class designed to have methods overloaded, /// this class provides an interface for a generic image /// saving and loading mechanism, but does not specify the /// format. It should not be insubstantiated directly. /// </summary> public class GenericSystemDrawing : ITerrainLoader { #region ITerrainLoader Members public string FileExtension { get { return ".gsd"; } } /// <summary> /// Loads a file from a specified filename on the disk, /// parses the image using the System.Drawing parsers /// then returns a terrain channel. Values are /// returned based on HSL brightness between 0m and 128m /// </summary> /// <param name = "filename">The target image to load</param> /// <returns>A terrain channel generated from the image.</returns> public virtual ITerrainChannel LoadFile(string filename, IScene scene) { return LoadBitmap(new Bitmap(filename)); } public ITerrainChannel LoadFile(string filename, int x, int y, int fileWidth, int fileHeight, int w, int h) { // [[THEMAJOR]] Some work on tile loading.. // terrain load-tile Tile.png 5 5 10000 10050 Bitmap tilemap = new Bitmap(filename); // Prevents off-by-one issue fileHeight--; int xoffset = w*x; int yoffset = h*(fileHeight - y); //MainConsole.Instance.DebugFormat( // "[TERRAIN]: Loading tile {0},{1} (offset {2},{3}) from tilemap size of {4},{5}", // x, y, xoffset, yoffset, fileWidth, fileHeight); Rectangle tileRect = new Rectangle(xoffset, yoffset, w, h); PixelFormat format = tilemap.PixelFormat; Bitmap cloneBitmap = null; try { cloneBitmap = tilemap.Clone(tileRect, format); } catch (OutOfMemoryException e) { // This error WILL appear if the number of Y tiles is too high because of how it works from the bottom up // However, this still spits out ugly unreferenced object errors on the console MainConsole.Instance.ErrorFormat( "[TERRAIN]: Couldn't load tile {0},{1} (from bitmap coordinates {2},{3}). Number of specified Y tiles may be too high: {4}", x, y, xoffset, yoffset, e); } finally { // Some attempt at keeping a clean memory tilemap.Dispose(); } return LoadBitmap(cloneBitmap); } public virtual ITerrainChannel LoadStream(Stream stream, IScene scene) { return LoadBitmap(new Bitmap(stream)); } /// <summary> /// Exports a file to a image on the disk using a System.Drawing exporter. /// </summary> /// <param name = "filename">The target filename</param> /// <param name = "map">The terrain channel being saved</param> public virtual void SaveFile(string filename, ITerrainChannel map) { Bitmap colours = CreateGrayscaleBitmapFromMap(map); colours.Save(filename, ImageFormat.Png); } /// <summary> /// Exports a stream using a System.Drawing exporter. /// </summary> /// <param name = "stream">The target stream</param> /// <param name = "map">The terrain channel being saved</param> public virtual void SaveStream(Stream stream, ITerrainChannel map) { Bitmap colours = CreateGrayscaleBitmapFromMap(map); colours.Save(stream, ImageFormat.Png); } #endregion protected virtual ITerrainChannel LoadBitmap(Bitmap bitmap) { ITerrainChannel retval = new TerrainChannel(bitmap.Width, bitmap.Height, null); int x; for (x = 0; x < bitmap.Width; x++) { int y; for (y = 0; y < bitmap.Height; y++) { retval[x, y] = bitmap.GetPixel(x, bitmap.Height - y - 1).GetBrightness()*128; } } return retval; } public override string ToString() { return "SYS.DRAWING"; } /// <summary> /// Protected method, generates a grayscale bitmap /// image from a specified terrain channel. /// </summary> /// <param name = "map">The terrain channel to export to bitmap</param> /// <returns>A System.Drawing.Bitmap containing a grayscale image</returns> protected static Bitmap CreateGrayscaleBitmapFromMap(ITerrainChannel map) { Bitmap bmp = new Bitmap(map.Width, map.Height); const int pallete = 256; Color[] grays = new Color[pallete]; for (int i = 0; i < grays.Length; i++) { grays[i] = Color.FromArgb(i, i, i); } for (int y = 0; y < map.Height; y++) { for (int x = 0; x < map.Width; x++) { // 512 is the largest possible height before colours clamp int colorindex = (int) (Math.Max(Math.Min(1.0, map[x, y]/128.0), 0.0)*(pallete - 1)); // Handle error conditions if (colorindex > pallete - 1 || colorindex < 0) bmp.SetPixel(x, map.Height - y - 1, Color.Red); else bmp.SetPixel(x, map.Height - y - 1, grays[colorindex]); } } return bmp; } /// <summary> /// Protected method, generates a coloured bitmap /// image from a specified terrain channel. /// </summary> /// <param name = "map">The terrain channel to export to bitmap</param> /// <returns>A System.Drawing.Bitmap containing a coloured image</returns> protected static Bitmap CreateBitmapFromMap(ITerrainChannel map) { Bitmap gradientmapLd = new Bitmap("defaultstripe.png"); int pallete = gradientmapLd.Height; Bitmap bmp = new Bitmap(map.Width, map.Height); Color[] colours = new Color[pallete]; for (int i = 0; i < pallete; i++) { colours[i] = gradientmapLd.GetPixel(0, i); } for (int y = 0; y < map.Height; y++) { for (int x = 0; x < map.Width; x++) { // 512 is the largest possible height before colours clamp int colorindex = (int) (Math.Max(Math.Min(1.0, map[x, y]/512.0), 0.0)*(pallete - 1)); // Handle error conditions if (colorindex > pallete - 1 || colorindex < 0) bmp.SetPixel(x, map.Height - y - 1, Color.Red); else bmp.SetPixel(x, map.Height - y - 1, colours[colorindex]); } } return bmp; } } }
// // ContextBackendHandler.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // Hywel Thomas <hywel.w.thomas@gmail.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Linq; using Xwt.Backends; using Xwt.Drawing; using Xwt.GtkBackend; using System.Collections.Generic; namespace Xwt.CairoBackend { class CairoContextBackend : IDisposable { public double GlobalAlpha = 1; public Cairo.Context Context; public Cairo.Surface TempSurface; public double ScaleFactor = 1; public double PatternAlpha = 1; public StyleSet Styles; internal Point Origin = Point.Zero; Stack<Data> dataStack = new Stack<Data> (); struct Data { public double PatternAlpha; public double GlobalAlpha; } public CairoContextBackend (double scaleFactor) { ScaleFactor = scaleFactor; } public virtual void Dispose () { IDisposable d = Context; if (d != null) { d.Dispose (); } d = TempSurface; if (d != null) { d.Dispose (); } } public void Save () { Context.Save (); dataStack.Push (new Data () { PatternAlpha = PatternAlpha, GlobalAlpha = GlobalAlpha }); } public void Restore () { Context.Restore (); var d = dataStack.Pop (); PatternAlpha = d.PatternAlpha; GlobalAlpha = d.GlobalAlpha; } } public class CairoContextBackendHandler: ContextBackendHandler { public override bool DisposeHandleOnUiThread { get { return true; } } #region IContextBackendHandler implementation public override double GetScaleFactor (object backend) { CairoContextBackend gc = (CairoContextBackend)backend; return gc.ScaleFactor; } public override void Save (object backend) { CairoContextBackend gc = (CairoContextBackend)backend; gc.Save (); } public override void Restore (object backend) { CairoContextBackend gc = (CairoContextBackend)backend; gc.Restore (); } public override void SetGlobalAlpha (object backend, double alpha) { CairoContextBackend gc = (CairoContextBackend) backend; gc.GlobalAlpha = alpha; } public override void SetStyles (object backend, StyleSet styles) { CairoContextBackend gc = (CairoContextBackend) backend; gc.Styles = styles; } const double degrees = System.Math.PI / 180d; public override void Arc (object backend, double xc, double yc, double radius, double angle1, double angle2) { CairoContextBackend gc = (CairoContextBackend)backend; gc.Context.Arc (xc, yc, radius, angle1 * degrees, angle2 * degrees); } public override void ArcNegative (object backend, double xc, double yc, double radius, double angle1, double angle2) { CairoContextBackend gc = (CairoContextBackend)backend; gc.Context.ArcNegative (xc, yc, radius, angle1 * degrees, angle2 * degrees); } public override void Clip (object backend) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.Clip (); } public override void ClipPreserve (object backend) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.ClipPreserve (); } public override void ClosePath (object backend) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.ClosePath (); } public override void CurveTo (object backend, double x1, double y1, double x2, double y2, double x3, double y3) { CairoContextBackend gc = (CairoContextBackend) backend; gc.Context.CurveTo (x1, y1, x2, y2, x3, y3); } public override void Fill (object backend) { var gtkc = (CairoContextBackend) backend; Cairo.Context ctx = gtkc.Context; var alpha = gtkc.GlobalAlpha * gtkc.PatternAlpha; if (alpha == 1) ctx.Fill (); else { ctx.Save (); ctx.Clip (); ctx.PaintWithAlpha (alpha); ctx.Restore (); } } public override void FillPreserve (object backend) { var gtkc = (CairoContextBackend) backend; Cairo.Context ctx = gtkc.Context; var alpha = gtkc.GlobalAlpha * gtkc.PatternAlpha; if (alpha == 1) ctx.FillPreserve (); else { ctx.Save (); ctx.ClipPreserve (); ctx.PaintWithAlpha (alpha); ctx.Restore (); } } public override void LineTo (object backend, double x, double y) { CairoContextBackend gc = (CairoContextBackend) backend; gc.Context.LineTo (x, y); } public override void MoveTo (object backend, double x, double y) { CairoContextBackend gc = (CairoContextBackend) backend; gc.Context.MoveTo (x, y); } public override void NewPath (object backend) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.NewPath (); } public override void Rectangle (object backend, double x, double y, double width, double height) { CairoContextBackend gc = (CairoContextBackend) backend; gc.Context.Rectangle (x, y, width, height); } public override void RelCurveTo (object backend, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.RelCurveTo (dx1, dy1, dx2, dy2, dx3, dy3); } public override void RelLineTo (object backend, double dx, double dy) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.RelLineTo (dx, dy); } public override void RelMoveTo (object backend, double dx, double dy) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.RelMoveTo (dx, dy); } public override void Stroke (object backend) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.Stroke (); } public override void StrokePreserve (object backend) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.StrokePreserve (); } public override void SetColor (object backend, Xwt.Drawing.Color color) { var gtkContext = (CairoContextBackend) backend; gtkContext.Context.SetSourceRGBA (color.Red, color.Green, color.Blue, color.Alpha * gtkContext.GlobalAlpha); gtkContext.PatternAlpha = 1; } public override void SetLineWidth (object backend, double width) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.LineWidth = width; } public override void SetLineDash (object backend, double offset, params double[] pattern) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.SetDash (pattern, offset); } public override void SetPattern (object backend, object p) { var cb = (CairoContextBackend)backend; var toolkit = ApplicationContext.Toolkit; Cairo.Context ctx = cb.Context; p = toolkit.GetSafeBackend (p); if (p is ImagePatternBackend) { cb.PatternAlpha = ((ImagePatternBackend)p).Image.Alpha; p = ((ImagePatternBackend)p).GetPattern (ApplicationContext, ((CairoContextBackend)backend).ScaleFactor); } else cb.PatternAlpha = 1; if (p != null) ctx.SetSource ((Cairo.Pattern) p); else ctx.SetSource ((Cairo.Pattern) null); } public override void DrawTextLayout (object backend, TextLayout layout, double x, double y) { var be = (GtkTextLayoutBackendHandler.PangoBackend)ApplicationContext.Toolkit.GetSafeBackend (layout); var pl = be.Layout; CairoContextBackend ctx = (CairoContextBackend)backend; ctx.Context.MoveTo (x, y); if (layout.Height <= 0) { Pango.CairoHelper.ShowLayout (ctx.Context, pl); } else { var lc = pl.LineCount; var scale = Pango.Scale.PangoScale; double h = 0; var fe = ctx.Context.FontExtents; var baseline = fe.Ascent / (fe.Ascent + fe.Descent); for (int i=0; i<lc; i++) { var line = pl.Lines [i]; var ext = new Pango.Rectangle (); var extl = new Pango.Rectangle (); line.GetExtents (ref ext, ref extl); h += h == 0 ? (extl.Height / scale * baseline) : (extl.Height / scale); if (h > layout.Height) break; ctx.Context.MoveTo (x, y + h); Pango.CairoHelper.ShowLayoutLine (ctx.Context, line); } } } public override void DrawImage (object backend, ImageDescription img, double x, double y) { CairoContextBackend ctx = (CairoContextBackend)backend; img.Alpha *= ctx.GlobalAlpha; img.Styles = img.Styles.AddRange (ctx.Styles); var pix = (Xwt.GtkBackend.GtkImage) img.Backend; pix.Draw (ApplicationContext, ctx.Context, ctx.ScaleFactor, x, y, img); } public override void DrawImage (object backend, ImageDescription img, Rectangle srcRect, Rectangle destRect) { CairoContextBackend ctx = (CairoContextBackend)backend; ctx.Context.Save (); ctx.Context.NewPath(); ctx.Context.Rectangle (destRect.X, destRect.Y, destRect.Width, destRect.Height); ctx.Context.Clip (); double sx = destRect.Width / srcRect.Width; double sy = destRect.Height / srcRect.Height; ctx.Context.Translate (destRect.X-srcRect.X*sx, destRect.Y-srcRect.Y*sy); ctx.Context.Scale (sx, sy); img.Alpha *= ctx.GlobalAlpha; img.Styles = img.Styles.AddRange (ctx.Styles); var pix = (Xwt.GtkBackend.GtkImage) img.Backend; pix.Draw (ApplicationContext, ctx.Context, ctx.ScaleFactor, 0, 0, img); ctx.Context.Restore (); } protected virtual Size GetImageSize (object img) { return new Size (0,0); } public override void Rotate (object backend, double angle) { CairoContextBackend gc = (CairoContextBackend)backend; gc.Context.Rotate ((angle * System.Math.PI) / 180); } public override void Scale (object backend, double scaleX, double scaleY) { CairoContextBackend gc = (CairoContextBackend)backend; gc.Context.Scale (scaleX, scaleY); } public override void Translate (object backend, double tx, double ty) { CairoContextBackend gc = (CairoContextBackend)backend; gc.Context.Translate (tx, ty); } public override void ModifyCTM (object backend, Matrix m) { CairoContextBackend gc = (CairoContextBackend)backend; Cairo.Matrix t = new Cairo.Matrix (m.M11, m.M12, m.M21, m.M22, m.OffsetX, m.OffsetY); gc.Context.Transform (t); } public override Matrix GetCTM (object backend) { var cb = (CairoContextBackend)backend; Cairo.Matrix t = cb.Context.Matrix; // Adjust CTM X0,Y0 for ContextBackend Origin (ensures that new CTM is Identity Matrix) Matrix ctm = new Matrix (t.Xx, t.Yx, t.Xy, t.Yy, t.X0-cb.Origin.X, t.Y0-cb.Origin.Y); return ctm; } public override object CreatePath () { Cairo.Surface sf = new Cairo.ImageSurface (null, Cairo.Format.A1, 0, 0, 0); return new CairoContextBackend (1) { // scale doesn't matter here, we are going to use it only for creating a path TempSurface = sf, Context = new Cairo.Context (sf) }; } public override object CopyPath (object backend) { var newPath = CreatePath (); AppendPath (newPath, backend); return newPath; } public override void AppendPath (object backend, object otherBackend) { Cairo.Context dest = ((CairoContextBackend)backend).Context; Cairo.Context src = ((CairoContextBackend)otherBackend).Context; using (var path = src.CopyPath ()) dest.AppendPath (path); } public override bool IsPointInFill (object backend, double x, double y) { return ((CairoContextBackend)backend).Context.InFill (x, y); } public override bool IsPointInStroke (object backend, double x, double y) { return ((CairoContextBackend)backend).Context.InStroke (x, y); } public override void Dispose (object backend) { var ctx = (CairoContextBackend) backend; ctx.Dispose (); } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** File: AssemblyAttributes ** ** <OWNER>[....]</OWNER> ** ** ** Purpose: For Assembly-related custom attributes. ** ** =============================================================================*/ namespace System.Reflection { using System; using System.Configuration.Assemblies; using System.Diagnostics.Contracts; [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyCopyrightAttribute : Attribute { private String m_copyright; public AssemblyCopyrightAttribute(String copyright) { m_copyright = copyright; } public String Copyright { get { return m_copyright; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyTrademarkAttribute : Attribute { private String m_trademark; public AssemblyTrademarkAttribute(String trademark) { m_trademark = trademark; } public String Trademark { get { return m_trademark; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyProductAttribute : Attribute { private String m_product; public AssemblyProductAttribute(String product) { m_product = product; } public String Product { get { return m_product; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyCompanyAttribute : Attribute { private String m_company; public AssemblyCompanyAttribute(String company) { m_company = company; } public String Company { get { return m_company; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyDescriptionAttribute : Attribute { private String m_description; public AssemblyDescriptionAttribute(String description) { m_description = description; } public String Description { get { return m_description; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyTitleAttribute : Attribute { private String m_title; public AssemblyTitleAttribute(String title) { m_title = title; } public String Title { get { return m_title; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyConfigurationAttribute : Attribute { private String m_configuration; public AssemblyConfigurationAttribute(String configuration) { m_configuration = configuration; } public String Configuration { get { return m_configuration; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyDefaultAliasAttribute : Attribute { private String m_defaultAlias; public AssemblyDefaultAliasAttribute(String defaultAlias) { m_defaultAlias = defaultAlias; } public String DefaultAlias { get { return m_defaultAlias; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyInformationalVersionAttribute : Attribute { private String m_informationalVersion; public AssemblyInformationalVersionAttribute(String informationalVersion) { m_informationalVersion = informationalVersion; } public String InformationalVersion { get { return m_informationalVersion; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyFileVersionAttribute : Attribute { private String _version; public AssemblyFileVersionAttribute(String version) { if (version == null) throw new ArgumentNullException("version"); Contract.EndContractBlock(); _version = version; } public String Version { get { return _version; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class AssemblyCultureAttribute : Attribute { private String m_culture; public AssemblyCultureAttribute(String culture) { m_culture = culture; } public String Culture { get { return m_culture; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class AssemblyVersionAttribute : Attribute { private String m_version; public AssemblyVersionAttribute(String version) { m_version = version; } public String Version { get { return m_version; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyKeyFileAttribute : Attribute { private String m_keyFile; public AssemblyKeyFileAttribute(String keyFile) { m_keyFile = keyFile; } public String KeyFile { get { return m_keyFile; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyDelaySignAttribute : Attribute { private bool m_delaySign; public AssemblyDelaySignAttribute(bool delaySign) { m_delaySign = delaySign; } public bool DelaySign { get { return m_delaySign; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class AssemblyAlgorithmIdAttribute : Attribute { private uint m_algId; public AssemblyAlgorithmIdAttribute(AssemblyHashAlgorithm algorithmId) { m_algId = (uint) algorithmId; } [CLSCompliant(false)] public AssemblyAlgorithmIdAttribute(uint algorithmId) { m_algId = algorithmId; } [CLSCompliant(false)] public uint AlgorithmId { get { return m_algId; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class AssemblyFlagsAttribute : Attribute { private AssemblyNameFlags m_flags; [Obsolete("This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")] [CLSCompliant(false)] public AssemblyFlagsAttribute(uint flags) { m_flags = (AssemblyNameFlags)flags; } [Obsolete("This property has been deprecated. Please use AssemblyFlags instead. http://go.microsoft.com/fwlink/?linkid=14202")] [CLSCompliant(false)] public uint Flags { get { return (uint)m_flags; } } // This, of course, should be typed as AssemblyNameFlags. The compat police don't allow such changes. public int AssemblyFlags { get { return (int)m_flags; } } [Obsolete("This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")] public AssemblyFlagsAttribute(int assemblyFlags) { m_flags = (AssemblyNameFlags)assemblyFlags; } public AssemblyFlagsAttribute(AssemblyNameFlags assemblyFlags) { m_flags = assemblyFlags; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true, Inherited=false)] public sealed class AssemblyMetadataAttribute : Attribute { private String m_key; private String m_value; public AssemblyMetadataAttribute(string key, string value) { m_key = key; m_value = value; } public string Key { get { return m_key; } } public string Value { get { return m_value;} } } // We don't support key migration on Silverlight, as libraries should all be distributed with the application. #if FEATURE_STRONGNAME_MIGRATION || FEATURE_NETCORE [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple=false)] public sealed class AssemblySignatureKeyAttribute : Attribute { private String _publicKey; private String _countersignature; public AssemblySignatureKeyAttribute(String publicKey, String countersignature) { _publicKey = publicKey; _countersignature = countersignature; } public String PublicKey { get { return _publicKey; } } public String Countersignature { get { return _countersignature; } } } #endif #if FEATURE_CORECLR || !FEATURE_PAL || MONO [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyKeyNameAttribute : Attribute { private String m_keyName; public AssemblyKeyNameAttribute(String keyName) { m_keyName = keyName; } public String KeyName { get { return m_keyName; } } } #endif // FEATURE_CORECLR || !FEATURE_PAL }
//--------------------------------------------------------------------------- // // <copyright file="WindowsIPAddress" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Win32 IP Common Control proxy // // History: // Kris Krueger Created // Jean-Francois Peyroux Reimplemented // alexsn (2003/08/15) Updated to use IRawElementProviderHwndOverride // //--------------------------------------------------------------------------- using System; using System.Net; using System.Text; using System.ComponentModel; using System.Globalization; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.Windows; using MS.Win32; namespace MS.Internal.AutomationProxies { class WindowsIPAddress: ProxyHwnd, IRawElementProviderHwndOverride, IValueProvider, IGridProvider { // ------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors WindowsIPAddress (IntPtr hwnd, ProxyFragment parent, int item) : base( hwnd, parent, item ) { // IP Address control itself is custom so need to also return LocalizedControlType property _cControlType = ControlType.Custom; _sType = ST.Get( STID.LocalizedControlTypeIPAddress ); ; _fIsKeyboardFocusable = true; // support for events _createOnEvent = new WinEventTracker.ProxyRaiseEvents (RaiseEvents); } #endregion #region Proxy Create // Static Create method called by UIAutomation to create this proxy. // returns null if unsuccessful internal static IRawElementProviderSimple Create(IntPtr hwnd, int idChild, int idObject) { return Create(hwnd, idChild); } private static IRawElementProviderSimple Create(IntPtr hwnd, int idChild) { // Something is wrong if idChild is not zero if (idChild != 0) { System.Diagnostics.Debug.Assert (idChild == 0, "Invalid Child Id, idChild != 0"); throw new ArgumentOutOfRangeException("idChild", idChild, SR.Get(SRID.ShouldBeZero)); } return new WindowsIPAddress(hwnd, null, 0); } internal static void RaiseEvents (IntPtr hwnd, int eventId, object idProp, int idObject, int idChild) { if (idObject != NativeMethods.OBJID_VSCROLL && idObject != NativeMethods.OBJID_HSCROLL) { ProxySimple el = new WindowsIPAddress (hwnd, null, 0); el.DispatchEvents (eventId, idProp, idObject, idChild); } } #endregion Proxy Create //------------------------------------------------------ // // Patterns Implementation // //------------------------------------------------------ #region ProxySimple Interface // Returns a pattern interface if supported. internal override object GetPatternProvider (AutomationPattern iid) { return iid == ValuePattern.Pattern || iid == GridPattern.Pattern ? this : null; } #endregion #region ProxyFragment Interface // Returns a Proxy element corresponding to the specified screen coordinates. internal override ProxySimple ElementProviderFromPoint (int x, int y) { // let UIAutomation do the drilling return null; } #endregion ProxyFragment Interface #region IRawElementProviderHwndOverride IRawElementProviderSimple IRawElementProviderHwndOverride.GetOverrideProviderForHwnd (IntPtr hwnd) { // Find location of passed in hwnd under the parent int index = GetIndexOfChildWindow (hwnd); System.Diagnostics.Debug.Assert (index != -1, "GetOverrideProviderForHwnd: cannot find child hwnd index"); return new ByteEditBoxOverride (hwnd, index); } #endregion IRawElementProviderHwndOverride #region Value Pattern // Sets the IP Address. void IValueProvider.SetValue (string val) { // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } IPAddress ipAddress = GetIPAddressFromString (val); if (ipAddress != null) { byte[] abOctet = ipAddress.GetAddressBytes(); if (abOctet.Length == 4) { uint ipV4 = 0; for (int iPos = 0; iPos < 4; iPos++) { ipV4 = (ipV4 << 8) + abOctet[iPos]; } // no return result for this message, so if it get sent it must have succeeded Misc.ProxySendMessage(_hwnd, NativeMethods.IPM_SETADDRESS, IntPtr.Zero, (IntPtr)unchecked((int)ipV4)); return; } } // this was no a valid IP address throw new InvalidOperationException (SR.Get(SRID.OperationCannotBePerformed)); } // Request to get the value that this UI element is representing as a string string IValueProvider.Value { get { return Misc.ProxyGetText(_hwnd, IP_ADDRESS_STRING_LENGTH); } } bool IValueProvider.IsReadOnly { get { return !Misc.IsEnabled(_hwnd); } } #endregion #region Grid Pattern // Obtain the AutomationElement at an zero based absolute position in the grid. // Where 0,0 is top left IRawElementProviderSimple IGridProvider.GetItem(int row, int column) { // NOTE: IPAddress has only 1 row if (row != 0) { throw new ArgumentOutOfRangeException("row", row, SR.Get(SRID.GridRowOutOfRange)); } if (column < 0 || column >= OCTETCOUNT) { throw new ArgumentOutOfRangeException("column", column, SR.Get(SRID.GridColumnOutOfRange)); } // Note: GridItem position is in reverse from the hwnd position // take this into account column = OCTETCOUNT - (column + 1); IntPtr hwndChild = GetChildWindowFromIndex(column); if (hwndChild != IntPtr.Zero) { return new ByteEditBoxOverride(hwndChild, column); } return null; } int IGridProvider.RowCount { get { return 1; } } int IGridProvider.ColumnCount { get { return OCTETCOUNT; } } #endregion Grid Pattern //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Method private IPAddress GetIPAddressFromString (String strIPAddress) { String [] strIPAddresses = strIPAddress.Split (IP_ADDRESS_SEPERATOR); if (strIPAddresses.Length != 4) { return null; } uint ipV4 = 0; for (int iPos = 3; iPos >= 0; iPos--) { ipV4 = (ipV4 << 8) + byte.Parse(strIPAddresses[iPos], CultureInfo.InvariantCulture); } return new IPAddress ((long) ipV4); } // Index or -1 (if not found) private int GetIndexOfChildWindow (IntPtr target) { int index = 0; IntPtr hwndChild = Misc.GetWindow(_hwnd, NativeMethods.GW_CHILD); while (hwndChild != IntPtr.Zero) { if (hwndChild == target) { return index; } index++; hwndChild = Misc.GetWindow(hwndChild, NativeMethods.GW_HWNDNEXT); } return -1; } // get child window at index (0-based). IntPtr.Zero if not found private IntPtr GetChildWindowFromIndex (int index) { IntPtr hwndChild = Misc.GetWindow(_hwnd, NativeMethods.GW_CHILD); for (int i = 0; ((i < index) && (hwndChild != IntPtr.Zero)); i++) { hwndChild = Misc.GetWindow(hwndChild, NativeMethods.GW_HWNDNEXT); } return hwndChild; } #endregion Private Method //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private const int IP_ADDRESS_STRING_LENGTH = 16; private const char IP_ADDRESS_SEPERATOR = '.'; internal const int OCTETCOUNT = 4; #endregion Private Fields } // ------------------------------------------------------ // // ByteEditBoxOverride Private Class // //------------------------------------------------------ #region ByteEditBoxOverride // Placeholder/Extra Pattern provider for OctetEditBox // @review: 2003/08/15 - alexsn: Deriving from ProxyHwnd class ByteEditBoxOverride : ProxyHwnd, IGridItemProvider, IRangeValueProvider { // ------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors internal ByteEditBoxOverride(IntPtr hwnd, int position) : base(hwnd, null, 0) { _sType = ST.Get(STID.LocalizedControlTypeOctet); _position = position; _sAutomationId = "Octet " + position.ToString(CultureInfo.CurrentCulture); // This string is a non-localizable string _fIsKeyboardFocusable = true; } #endregion Constructors //------------------------------------------------------ // // Patterns Implementation // //------------------------------------------------------ #region ProxySimple Interface internal override ProviderOptions ProviderOptions { get { return base.ProviderOptions | ProviderOptions.OverrideProvider; } } // Returns a pattern interface if supported. internal override object GetPatternProvider(AutomationPattern iid) { if (GridItemPattern.Pattern == iid) { return this; } if (RangeValuePattern.Pattern == iid) { return this; } return null; } // Gets the localized name internal override string LocalizedName { get { return Misc.ProxyGetText(_hwnd); } } #endregion #region RangeValue Pattern // Sets the one of the field of the IP Address. void IRangeValueProvider.SetValue(double val) { // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } int i = (int)val; // Check range if (i > 255) { throw new ArgumentOutOfRangeException("value", val, SR.Get(SRID.RangeValueMax)); } if (i < 0) { throw new ArgumentOutOfRangeException("value", val, SR.Get(SRID.RangeValueMin)); } // Set text Misc.ProxySendMessage(_hwnd, NativeMethods.WM_SETTEXT, IntPtr.Zero, new StringBuilder(i.ToString(CultureInfo.CurrentCulture))); } // Request to get the value that this UI element is representing in a native format double IRangeValueProvider.Value { get { string s = WindowsEditBox.Text(_hwnd); if (string.IsNullOrEmpty(s)) { return double.NaN; } return double.Parse(s, CultureInfo.CurrentCulture); } } bool IRangeValueProvider.IsReadOnly { get { return !SafeNativeMethods.IsWindowEnabled(_hwnd); } } double IRangeValueProvider.Maximum { get { return 255.0; } } double IRangeValueProvider.Minimum { get { return 0.0; } } double IRangeValueProvider.SmallChange { get { return Double.NaN; } } double IRangeValueProvider.LargeChange { get { return Double.NaN; } } #endregion #region GridItem Pattern int IGridItemProvider.Row { get { return 0; } } int IGridItemProvider.Column { get { // Note hwnd locations are in reverse // we need to ajust columns accordnigly return WindowsIPAddress.OCTETCOUNT - 1 - _position; } } int IGridItemProvider.RowSpan { get { return 1; } } int IGridItemProvider.ColumnSpan { get { return 1; } } IRawElementProviderSimple IGridItemProvider.ContainingGrid { get { return WindowsIPAddress.Create(Misc.GetParent(_hwnd), 0, 0); } } #endregion GridItem Pattern //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields // location in the IP private int _position; #endregion Private Fields } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma warning disable 0420 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // SlimManualResetEvent.cs // // // An manual-reset event that mixes a little spinning with a true Win32 event. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Threading; using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading { // ManualResetEventSlim wraps a manual-reset event internally with a little bit of // spinning. When an event will be set imminently, it is often advantageous to avoid // a 4k+ cycle context switch in favor of briefly spinning. Therefore we layer on to // a brief amount of spinning that should, on the average, make using the slim event // cheaper than using Win32 events directly. This can be reset manually, much like // a Win32 manual-reset would be. // // Notes: // We lazily allocate the Win32 event internally. Therefore, the caller should // always call Dispose to clean it up, just in case. This API is a no-op of the // event wasn't allocated, but if it was, ensures that the event goes away // eagerly, instead of waiting for finalization. /// <summary> /// Provides a slimmed down version of <see cref="T:System.Threading.ManualResetEvent"/>. /// </summary> /// <remarks> /// All public and protected members of <see cref="ManualResetEventSlim"/> are thread-safe and may be used /// concurrently from multiple threads, with the exception of Dispose, which /// must only be used when all other operations on the <see cref="ManualResetEventSlim"/> have /// completed, and Reset, which should only be used when no other threads are /// accessing the event. /// </remarks> [DebuggerDisplay("Set = {IsSet}")] public class ManualResetEventSlim : IDisposable { // These are the default spin counts we use on single-proc and MP machines. private const int DEFAULT_SPIN_SP = 1; private const int DEFAULT_SPIN_MP = SpinWait.YIELD_THRESHOLD; private volatile object m_lock; // A lock used for waiting and pulsing. Lazily initialized via EnsureLockObjectCreated() private volatile ManualResetEvent m_eventObj; // A true Win32 event used for waiting. // -- State -- // //For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant. private volatile int m_combinedState; //ie a UInt32. Used for the state items listed below. //1-bit for signalled state private const int SignalledState_BitMask = unchecked((int)0x80000000);//1000 0000 0000 0000 0000 0000 0000 0000 private const int SignalledState_ShiftCount = 31; //1-bit for disposed state private const int Dispose_BitMask = unchecked((int)0x40000000);//0100 0000 0000 0000 0000 0000 0000 0000 //11-bits for m_spinCount private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); //0011 1111 1111 1000 0000 0000 0000 0000 private const int SpinCountState_ShiftCount = 19; private const int SpinCountState_MaxValue = (1 << 11) - 1; //2047 //19-bits for m_waiters. This allows support of 512K threads waiting which should be ample private const int NumWaitersState_BitMask = unchecked((int)0x0007FFFF); // 0000 0000 0000 0111 1111 1111 1111 1111 private const int NumWaitersState_ShiftCount = 0; private const int NumWaitersState_MaxValue = (1 << 19) - 1; //512K-1 // ----------- // #if DEBUG private static int s_nextId; // The next id that will be given out. private int m_id = Interlocked.Increment(ref s_nextId); // A unique id for debugging purposes only. private long m_lastSetTime; private long m_lastResetTime; #endif /// <summary> /// Gets the underlying <see cref="T:System.Threading.WaitHandle"/> object for this <see /// cref="ManualResetEventSlim"/>. /// </summary> /// <value>The underlying <see cref="T:System.Threading.WaitHandle"/> event object fore this <see /// cref="ManualResetEventSlim"/>.</value> /// <remarks> /// Accessing this property forces initialization of an underlying event object if one hasn't /// already been created. To simply wait on this <see cref="ManualResetEventSlim"/>, /// the public Wait methods should be preferred. /// </remarks> public WaitHandle WaitHandle { get { ThrowIfDisposed(); if (m_eventObj == null) { // Lazily initialize the event object if needed. LazyInitializeEvent(); } return m_eventObj; } } /// <summary> /// Gets whether the event is set. /// </summary> /// <value>true if the event has is set; otherwise, false.</value> public bool IsSet { get { return 0 != ExtractStatePortion(m_combinedState, SignalledState_BitMask); } private set { UpdateStateAtomically(((value) ? 1 : 0) << SignalledState_ShiftCount, SignalledState_BitMask); } } /// <summary> /// Gets the number of spin waits that will be occur before falling back to a true wait. /// </summary> public int SpinCount { get { return ExtractStatePortionAndShiftRight(m_combinedState, SpinCountState_BitMask, SpinCountState_ShiftCount); } private set { Debug.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); Debug.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); // Don't worry about thread safety because it's set one time from the constructor m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount); } } /// <summary> /// How many threads are waiting. /// </summary> private int Waiters { get { return ExtractStatePortionAndShiftRight(m_combinedState, NumWaitersState_BitMask, NumWaitersState_ShiftCount); } set { //setting to <0 would indicate an internal flaw, hence Assert is appropriate. Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error."); // it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here. if (value >= NumWaitersState_MaxValue) throw new InvalidOperationException(String.Format(Environment.GetResourceString("ManualResetEventSlim_ctor_TooManyWaiters"), NumWaitersState_MaxValue)); UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask); } } //----------------------------------------------------------------------------------- // Constructs a new event, optionally specifying the initial state and spin count. // The defaults are that the event is unsignaled and some reasonable default spin. // /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with an initial state of nonsignaled. /// </summary> public ManualResetEventSlim() : this(false) { } /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with a Boolen value indicating whether to set the intial state to signaled. /// </summary> /// <param name="initialState">true to set the initial state signaled; false to set the initial state /// to nonsignaled.</param> public ManualResetEventSlim(bool initialState) { // Specify the defualt spin count, and use default spin if we're // on a multi-processor machine. Otherwise, we won't. Initialize(initialState, DEFAULT_SPIN_MP); } /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with a Boolen value indicating whether to set the intial state to signaled and a specified /// spin count. /// </summary> /// <param name="initialState">true to set the initial state to signaled; false to set the initial state /// to nonsignaled.</param> /// <param name="spinCount">The number of spin waits that will occur before falling back to a true /// wait.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="spinCount"/> is less than /// 0 or greater than the maximum allowed value.</exception> public ManualResetEventSlim(bool initialState, int spinCount) { if (spinCount < 0) { throw new ArgumentOutOfRangeException(nameof(spinCount)); } if (spinCount > SpinCountState_MaxValue) { throw new ArgumentOutOfRangeException( nameof(spinCount), String.Format(Environment.GetResourceString("ManualResetEventSlim_ctor_SpinCountOutOfRange"), SpinCountState_MaxValue)); } // We will suppress default spin because the user specified a count. Initialize(initialState, spinCount); } /// <summary> /// Initializes the internal state of the event. /// </summary> /// <param name="initialState">Whether the event is set initially or not.</param> /// <param name="spinCount">The spin count that decides when the event will block.</param> private void Initialize(bool initialState, int spinCount) { m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0; //the spinCount argument has been validated by the ctors. //but we now sanity check our predefined constants. Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount; } /// <summary> /// Helper to ensure the lock object is created before first use. /// </summary> private void EnsureLockObjectCreated() { Contract.Ensures(m_lock != null); if (m_lock != null) return; object newObj = new object(); Interlocked.CompareExchange(ref m_lock, newObj, null); // failure is benign. Someone else set the value. } /// <summary> /// This method lazily initializes the event object. It uses CAS to guarantee that /// many threads racing to call this at once don't result in more than one event /// being stored and used. The event will be signaled or unsignaled depending on /// the state of the thin-event itself, with synchronization taken into account. /// </summary> /// <returns>True if a new event was created and stored, false otherwise.</returns> private bool LazyInitializeEvent() { bool preInitializeIsSet = IsSet; ManualResetEvent newEventObj = new ManualResetEvent(preInitializeIsSet); // We have to CAS this in case we are racing with another thread. We must // guarantee only one event is actually stored in this field. if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null) { // Someone else set the value due to a race condition. Destroy the garbage event. newEventObj.Close(); return false; } else { // Now that the event is published, verify that the state hasn't changed since // we snapped the preInitializeState. Another thread could have done that // between our initial observation above and here. The barrier incurred from // the CAS above (in addition to m_state being volatile) prevents this read // from moving earlier and being collapsed with our original one. bool currentIsSet = IsSet; if (currentIsSet != preInitializeIsSet) { Debug.Assert(currentIsSet, "The only safe concurrent transition is from unset->set: detected set->unset."); // We saw it as unsignaled, but it has since become set. lock (newEventObj) { // If our event hasn't already been disposed of, we must set it. if (m_eventObj == newEventObj) { newEventObj.Set(); } } } return true; } } /// <summary> /// Sets the state of the event to signaled, which allows one or more threads waiting on the event to /// proceed. /// </summary> public void Set() { Set(false); } /// <summary> /// Private helper to actually perform the Set. /// </summary> /// <param name="duringCancellation">Indicates whether we are calling Set() during cancellation.</param> /// <exception cref="T:System.OperationCanceledException">The object has been canceled.</exception> private void Set(bool duringCancellation) { // We need to ensure that IsSet=true does not get reordered past the read of m_eventObj // This would be a legal movement according to the .NET memory model. // The code is safe as IsSet involves an Interlocked.CompareExchange which provides a full memory barrier. IsSet = true; // If there are waiting threads, we need to pulse them. if (Waiters > 0) { Debug.Assert(m_lock != null); //if waiters>0, then m_lock has already been created. lock (m_lock) { Monitor.PulseAll(m_lock); } } ManualResetEvent eventObj = m_eventObj; //Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly //It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic if (eventObj != null && !duringCancellation) { // We must surround this call to Set in a lock. The reason is fairly subtle. // Sometimes a thread will issue a Wait and wake up after we have set m_state, // but before we have gotten around to setting m_eventObj (just below). That's // because Wait first checks m_state and will only access the event if absolutely // necessary. However, the coding pattern { event.Wait(); event.Dispose() } is // quite common, and we must support it. If the waiter woke up and disposed of // the event object before the setter has finished, however, we would try to set a // now-disposed Win32 event. Crash! To deal with this race condition, we use a lock to // protect access to the event object when setting and disposing of it. We also // double-check that the event has not become null in the meantime when in the lock. lock (eventObj) { if (m_eventObj != null) { // If somebody is waiting, we must set the event. m_eventObj.Set(); } } } #if DEBUG m_lastSetTime = DateTime.UtcNow.Ticks; #endif } /// <summary> /// Sets the state of the event to nonsignaled, which causes threads to block. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Reset()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> public void Reset() { ThrowIfDisposed(); // If there's an event, reset it. if (m_eventObj != null) { m_eventObj.Reset(); } // There is a race condition here. If another thread Sets the event, we will get into a state // where m_state will be unsignaled, yet the Win32 event object will have been signaled. // This could cause waiting threads to wake up even though the event is in an // unsignaled state. This is fine -- those that are calling Reset concurrently are // responsible for doing "the right thing" -- e.g. rechecking the condition and // resetting the event manually. // And finally set our state back to unsignaled. IsSet = false; #if DEBUG m_lastResetTime = DateTime.UtcNow.Ticks; #endif } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set. /// </summary> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. /// </remarks> public void Wait() { Wait(Timeout.Infinite, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> receives a signal, /// while observing a <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <exception cref="T:System.OperationCanceledExcepton"><paramref name="cancellationToken"/> was /// canceled.</exception> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. /// </remarks> public void Wait(CancellationToken cancellationToken) { Wait(Timeout.Infinite, cancellationToken); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval. /// </summary> /// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds /// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely. /// </param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return Wait((int)totalMilliseconds, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a <see /// cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds /// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely. /// </param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.Threading.OperationCanceledException"><paramref /// name="cancellationToken"/> was canceled.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return Wait((int)totalMilliseconds, cancellationToken); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// 32-bit signed integer to measure the time interval. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// 32-bit signed integer to measure the time interval, while observing a <see /// cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <exception cref="T:System.Threading.OperationCanceledException"><paramref /// name="cancellationToken"/> was canceled.</exception> public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); // an early convenience check if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout)); } if (!IsSet) { if (millisecondsTimeout == 0) { // For 0-timeouts, we just return immediately. return false; } // We spin briefly before falling back to allocating and/or waiting on a true event. uint startTime = 0; bool bNeedTimeoutAdjustment = false; int realMillisecondsTimeout = millisecondsTimeout; //this will be adjusted if necessary. if (millisecondsTimeout != Timeout.Infinite) { // We will account for time spent spinning, so that we can decrement it from our // timeout. In most cases the time spent in this section will be negligible. But // we can't discount the possibility of our thread being switched out for a lengthy // period of time. The timeout adjustments only take effect when and if we actually // decide to block in the kernel below. startTime = TimeoutHelper.GetTime(); bNeedTimeoutAdjustment = true; } //spin int HOW_MANY_SPIN_BEFORE_YIELD = 10; int HOW_MANY_YIELD_EVERY_SLEEP_0 = 5; int HOW_MANY_YIELD_EVERY_SLEEP_1 = 20; int spinCount = SpinCount; for (int i = 0; i < spinCount; i++) { if (IsSet) { return true; } else if (i < HOW_MANY_SPIN_BEFORE_YIELD) { if (i == HOW_MANY_SPIN_BEFORE_YIELD / 2) { Thread.Yield(); } else { Thread.SpinWait(PlatformHelper.ProcessorCount * (4 << i)); } } else if (i % HOW_MANY_YIELD_EVERY_SLEEP_1 == 0) { Thread.Sleep(1); } else if (i % HOW_MANY_YIELD_EVERY_SLEEP_0 == 0) { Thread.Sleep(0); } else { Thread.Yield(); } if (i >= 100 && i % 10 == 0) // check the cancellation token if the user passed a very large spin count cancellationToken.ThrowIfCancellationRequested(); } // Now enter the lock and wait. EnsureLockObjectCreated(); // We must register and deregister the token outside of the lock, to avoid deadlocks. using (cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCallback, this)) { lock (m_lock) { // Loop to cope with spurious wakeups from other waits being canceled while (!IsSet) { // If our token was canceled, we must throw and exit. cancellationToken.ThrowIfCancellationRequested(); //update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled) if (bNeedTimeoutAdjustment) { realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout); if (realMillisecondsTimeout <= 0) return false; } // There is a race condition that Set will fail to see that there are waiters as Set does not take the lock, // so after updating waiters, we must check IsSet again. // Also, we must ensure there cannot be any reordering of the assignment to Waiters and the // read from IsSet. This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange // operation which provides a full memory barrier. // If we see IsSet=false, then we are guaranteed that Set() will see that we are // waiting and will pulse the monitor correctly. Waiters = Waiters + 1; if (IsSet) //This check must occur after updating Waiters. { Waiters--; //revert the increment. return true; } // Now finally perform the wait. try { // ** the actual wait ** if (!Monitor.Wait(m_lock, realMillisecondsTimeout)) return false; //return immediately if the timeout has expired. } finally { // Clean up: we're done waiting. Waiters = Waiters - 1; } // Now just loop back around, and the right thing will happen. Either: // 1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait) // or 2. the wait was successful. (the loop will break) } } } } // automatically disposes (and deregisters) the callback return true; //done. The wait was satisfied. } /// <summary> /// Releases all resources used by the current instance of <see cref="ManualResetEventSlim"/>. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// When overridden in a derived class, releases the unmanaged resources used by the /// <see cref="ManualResetEventSlim"/>, and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; /// false to release only unmanaged resources.</param> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose(Boolean)"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> protected virtual void Dispose(bool disposing) { if ((m_combinedState & Dispose_BitMask) != 0) return; // already disposed m_combinedState |= Dispose_BitMask; //set the dispose bit if (disposing) { // We will dispose of the event object. We do this under a lock to protect // against the race condition outlined in the Set method above. ManualResetEvent eventObj = m_eventObj; if (eventObj != null) { lock (eventObj) { eventObj.Close(); m_eventObj = null; } } } } /// <summary> /// Throw ObjectDisposedException if the MRES is disposed /// </summary> private void ThrowIfDisposed() { if ((m_combinedState & Dispose_BitMask) != 0) throw new ObjectDisposedException(Environment.GetResourceString("ManualResetEventSlim_Disposed")); } /// <summary> /// Private helper method to wake up waiters when a cancellationToken gets canceled. /// </summary> private static Action<object> s_cancellationTokenCallback = new Action<object>(CancellationTokenCallback); private static void CancellationTokenCallback(object obj) { ManualResetEventSlim mre = obj as ManualResetEventSlim; Debug.Assert(mre != null, "Expected a ManualResetEventSlim"); Debug.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use. lock (mre.m_lock) { Monitor.PulseAll(mre.m_lock); // awaken all waiters } } /// <summary> /// Private helper method for updating parts of a bit-string state value. /// Mainly called from the IsSet and Waiters properties setters /// </summary> /// <remarks> /// Note: the parameter types must be int as CompareExchange cannot take a Uint /// </remarks> /// <param name="newBits">The new value</param> /// <param name="updateBitsMask">The mask used to set the bits</param> private void UpdateStateAtomically(int newBits, int updateBitsMask) { SpinWait sw = new SpinWait(); Debug.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask."); do { int oldState = m_combinedState; // cache the old value for testing in CAS // Procedure:(1) zero the updateBits. eg oldState = [11111111] flag= [00111000] newState = [11000111] // then (2) map in the newBits. eg [11000111] newBits=00101000, newState=[11101111] int newState = (oldState & ~updateBitsMask) | newBits; if (Interlocked.CompareExchange(ref m_combinedState, newState, oldState) == oldState) { return; } sw.SpinOnce(); } while (true); } /// <summary> /// Private helper method - performs Mask and shift, particular helpful to extract a field from a packed word. /// eg ExtractStatePortionAndShiftRight(0x12345678, 0xFF000000, 24) => 0x12, ie extracting the top 8-bits as a simple integer /// /// ?? is there a common place to put this rather than being private to MRES? /// </summary> /// <param name="state"></param> /// <param name="mask"></param> /// <param name="rightBitShiftCount"></param> /// <returns></returns> private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount) { //convert to uint before shifting so that right-shift does not replicate the sign-bit, //then convert back to int. return unchecked((int)(((uint)(state & mask)) >> rightBitShiftCount)); } /// <summary> /// Performs a Mask operation, but does not perform the shift. /// This is acceptable for boolean values for which the shift is unnecessary /// eg (val &amp; Mask) != 0 is an appropriate way to extract a boolean rather than using /// ((val &amp; Mask) &gt;&gt; shiftAmount) == 1 /// /// ?? is there a common place to put this rather than being private to MRES? /// </summary> /// <param name="state"></param> /// <param name="mask"></param> private static int ExtractStatePortion(int state, int mask) { return state & mask; } } }